跟踪点击标签 - JavaFx

Track clicked label - JavaFx

我在 vBox 中有 5 个标签。我想创建一种方法来跟踪我单击的标签。现在,我正在使用 5 种方法,每个标签一种。我需要使用监听器还是其他东西? Here is a fragment of my program.

我的 fxml 代码:

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

我的java方法:

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

}

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

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

您可以将 MouseEvent 注入到通用事件处理程序中。像这样:

@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
}

您也可以传递 label.getId()label.getText()

此外,参见 this Stack Overflow discussion on JavaFx mouse events

最后,我建议不要将 class 级字段用作临时变量。您可以将特定于标签的逻辑委托给 openTimePicker 方法,以便控制器可以保持无状态。这减少了以后出现错误的机会!理想情况下,您希望将控制器实现为用户和服务之间的无状态适配器 classes.