Daniel R. Daniel R. - 9 months ago 64
Java Question

Better way for Getting id of the clicked Object in JavaFX controller

I`m looking for a better way for getting the id of the clicked object inside the event handler for this object.

I already found this:

javafx pass fx:id to controller or parameter in fxml onAction method

But that did not work for me.

Now I'm using the getId() function of the node class like this:

Button btn = (Button) event.getSource();
String id = btn.getId();

But i want to use this method not only for buttons.

Answer Source

Since fx:id is used to bind controls between FXML and Controller, this answer is taking into consideration that OP wants the id of the controls when clicked.

import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class IdForControlsOnClick extends Application{

    public void start(Stage stage) throws Exception {
        BorderPane borderPane = new BorderPane();
        VBox vBox = new VBox(20);

        Button button = new Button("Hi");
        Label label = new Label("Label");
        CheckBox checkBox = new CheckBox();

        button.addEventHandler(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
        label.addEventHandler(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
        checkBox.addEventHandler(MouseEvent.MOUSE_CLICKED, new MyEventHandler());

        vBox.getChildren().addAll(button, label, checkBox);
        Scene scene = new Scene(borderPane, 200, 200);


    public static void main(String[] args) {

    private class MyEventHandler implements EventHandler<Event>{
        public void handle(Event evt) {