Mazzone Mazzone - 1 year ago 64
Java Question

Unable to connect Javafx controller event with FXML shape. (Java)

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;


<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!

Answer Source

What you are doing wrong

  1. You are using the wrong event type.
  2. You are not referencing your event handler from your FXML.
  3. You should not try to register an event handler in an event handler for a case like this.

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;