Search code examples
javajavafxfxmlscenebuilder

How to get the calling node inside the controller of JavaFX program


I'm doing a javafx program, and I'm stuck when I trying to let many node share the same onAction function.

Here's 37 of label node inside the program and I added them into an ArrayList, and all of them shares the same function blockChange

<Label fx:id="b66" onMouseClicked="#blockChange" text="Label" GridPane.columnIndex="3">
    <font>
        <Font name="System Bold" size="14.0" />
    </font>
</Label>

I tried to implement the function that change the text of the label every time I clicked the label. But I cannot specify which is the label that call the function. I'm wondering if there's any way to get the calling node inside the Controller?

@FXML
void blockChange(MouseEvent event){
    //I want to get the calling label here
}

Solution

  • You can get the source like this:

    @FXML
    void blockChange(MouseEvent event) {
        Object source = event.getSource();
        if (source instanceof Label) {
            ((Label) source).setText("new Text");
        }
    }
    

    But as mentioned in the comments, if you already have all the labels in one collection, you can iterate over the collection and add EventHandler for each of them:

    public void initialize(URL url, ResourceBundle rb) {
        //...
        labels.forEach(this::addMouseClickedEventHandler);
    }
    
    private void addMouseClickedEventHandler(Label label) {
        label.setOnMouseClicked(event -> {
            label.setText("new text");
            event.consume();
        });
    }