Nick Nick - 1 month ago 14
Java Question

Handling nested events

I have a game that displays an archer and I am trying to set it up so that when my button is pressed, the user is then allowed to click anywhere on the screen and then a new archer would be set to where the click happen. My code currently allows me to click the screen and set a new archer regardless of whether the button was pressed or not. Could someone explain what is wrong becuase I though MouseEvent would occur on the scene once the button was pressed.

myButton.setOnMouseClicked(
new EventHandler<MouseEvent>()
{
public void handle(MouseEvent e)
{
gc.setFill(color);
gc.fillRect(0,0,width,height);
scene.setOnMouseClicked(new EventHandler<MouseEvent>()
{
public void handle(MouseEvent e)
{
archer.setX((int)e.getSceneX());
archer.setY((int)e.getSceneY());
archer.drawCharStand(gc);
}
});
}
});

Answer

You could use a ToggleButton, so that you only place the archer when the toggle button is selected:

private ToggleButton myButton = new ToggleButton("Place Archer");

// ...

scene.setOnMouseClicked(e -> {
    if (myButton.isSelected()) {
         archer.setX((int)e.getSceneX());
         archer.setY((int)e.getSceneY());
         archer.drawCharStand(gc);
         myButton.setSelected(false);
    }
});

The last line will unselect the toggle button "automatically" after placing the archer. If you want the user to be able to place multiple archers easily (and have to manually switch off that mode), omit that line.