Reputation: 308
I'm having trouble understanding why this super, super simple method isn't working. Basically what I've got is the standard MVC setup - so I have a controller that controls my layout (the FXML file). In the FXML, I've created various shapes to see if it was an issue with shapes in particular (it wasn't...). I just want to attach a method in my controller to a shape in my FXML that causes a counter to increase by 1 per click of the shape, and outputs the current count to the console. It's not working!
Here's the relevant code:
(Controller class)
@FXML Sphere asteroid;
private int counter = 0;
@FXML void addRandomResource(ActionEvent event) {
asteroid.setOnMousePressed(new EventHandler<MouseEvent>(){
public void handle(MouseEvent event){
counter += 1;
System.out.println(counter);
}
});
}
(FXML)
<Sphere fx:id="asteroid" layoutX="250.0" layoutY="300.0" radius="125.0" />
I know the controller is properly connected because other buttons on the page work... so that's not the issue. And I can't add an "onAction" property to a shape, which so it should be able to use the fx:id to recognize it, right?
Any help is appreciated, thanks!
Upvotes: 0
Views: 627
Reputation: 159291
What you are doing wrong
Mouse clicks generate MOUSE_CLICKED MouseEvents which are serviced by onMouseClicked event handlers. ActionEvents are for other purposes, such as button firings.
How to fix your program to handle click events
In your fxml you need to reference your controller's click event handler:
<Sphere fx:id="asteroid" onMouseClicked="#addRandomResource" layoutX="250.0" layoutY="300.0" radius="125.0" /
In your controller you need to use the correct signature to accept the event:
@FXML void addRandomResource(MouseEvent event) {
counter += 1;
System.out.println(counter);
}
Upvotes: 2