我在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();
}
答案 0 :(得分:0)
您可以将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。
最后,我建议不要使用类级字段作为临时变量。您可以将特定于标签的逻辑委派给openTimePicker
方法,以便控制器可以保持无状态。这减少了以后出错的机会!理想情况下,您希望将控制器实现为用户和服务类之间的无状态适配器。