Search code examples
javajavafxvbox

Track clicked label - JavaFx


I have 5 labels in a vBox. I want to create a method for tracking which label I clicked. Right now, I am using 5 methods, one for each label. Do I need to use a listener or something else? Here is a fragment of my program.

My fxml code:

<VBox layoutX="13.0" layoutY="106.0" prefHeight="117.0" prefWidth="68.0" spacing="8.0">
     <children>
        <Label fx:id="firstLabelTime" onMouseClicked="#setFirstLabelTime" text="Input time" />
        <Label fx:id="secondLabelTime" onMouseClicked="#setSecondLabelTime" text="Label" />
        <Label fx:id="thirdLabelTime" onMouseClicked="#setThirdLabelTime" text="Label" />
        <Label fx:id="fourthLabelTime" onMouseClicked="#setFourthLabelTime" text="Label" />
        <Label fx:id="fifthLabelTime" onMouseClicked="#setFifthLabelTime" text="Label" />
     </children>
  </VBox>

My java methods:

private Label tempLabelTime;
@FXML
private void setFirstLabelTime() {
        tempLabelTime = firstLabelTime;
        openTimePicker();

}

@FXML
private void setSecondLabelTime() {
    tempLabelTime = secondLabelTime;
    openTimePicker();
}

@FXML
private void setThirdLabelTime() {
    tempLabelTime = thirdLabelTime;
    openTimePicker();
}

Solution

  • You can inject the MouseEvent into a common event handler. Like this:

    @FXML
    private void labelClicked(MouseEvent e) {
        Label label = (Label) e.getSource();  // this is the label that initiated the event
        openTimePicker(label);                // openTimePicker knows what to do with each label clicked
    }
    

    You could also pass label.getId() or label.getText().

    Additionally, see this Stack Overflow discussion on JavaFx mouse events.

    Finally, I'd recommend against using the class-level field as a temporary variable. You can delegate the label-specific logic to the openTimePicker method instead so that the controller can remain stateless. This reduces the opportunity for bugs later on! Ideally, you want to implement your controller as a stateless adapter between the user and your service classes.