[英]Java FX Scene Builder: Handling Multiple mouseClick() events from different source objects
我是Java FX的新手,尤其是場景構建器的新手。 我有一個小應用程序,可以根據體重計算成績。 我向其中添加了一個菜單欄,但是Scene Builder僅允許我在事件上綁定mouseClick()
。 問題是,我已經有一個與此事件相關的“計算”按鈕(用於計算成績)。 我希望MenuItem
打開單擊時創建的對話框。
這是我目前試圖使該方法起作用的嘗試:
@FXML
public void mouseClick(MouseEvent mouseEvent)
{
if (mouseEvent.getSource().equals(calcBtn))
{
DecimalFormat df = new DecimalFormat("#.##");
double result = calcGrade();
resultLbl.setText("Overall Grade: " + df.format(result) + "%");
}
if (mouseEvent.getSource().equals(aboutMenu))
{
DialogBox.showInformation("About", "Some dialog here.");
}
}
在Swing中,我記得做這樣的事情來處理多個源對象:
if (e.getSource() == menuItem)
{
//do stuff
}
else if (e.getSource() == calculateBtn)
{
//calculate stuff
}
但是,這不起作用,並且無論如何都會執行“計算”按鈕的代碼。
由於Scene Builder將動作與Controller類聯系在一起的方式,我不確定單擊鼠標按鈕時如何在這兩個不同的源之間分隔動作。 當我嘗試在事件上綁定自定義項時,“場景”構建器對我大吼,並且只允許mouseClick()
。 處理此類情況的一個好的解決方案是什么?
我建議對兩個事件使用不同的處理程序方法。 此外,應該使用onAction
事件處理程序( MenuItem
不是Node
因此不能作為MouseEvent
的源):
<MenuItem text="Do Something" onAction="#doSomething" />
...
<Button text="Do something else" onAction="#doSomethingElse" />
@FXML
private void doSomething() {
System.out.println("Menu Item clicked");
}
@FXML
private void doSomethingElse() {
System.out.println("Button clicked");
}
這樣,更易於維護代碼。 (想象一下,您需要更改菜單項之一的操作的實現,並使用相同的方法來處理其中的30個;找到if / else if的正確部分要花多長時間。大多數IDE支持導航方法)。
如果您要堅持檢查源,那么只要事件類型可分配給method參數,就可以了:
<MenuItem fx:id="menuItem" text="Do Something" onAction="#doSomething" />
...
<Button fx:id="button" text="Do something else" onAction="#doSomething" />
@FXML Button button;
@FXML MenuItem menuItem;
@FXML
private void doSomething(ActionEvent event) {
Object source = event.getSource();
if (button == source) {
System.out.println("button clicked");
} else if (menuItem == source) {
System.out.println("menu item clicked");
}
}
如果要使用同一方法處理MouseEvent
和ActionEvent
,則可能需要將方法的參數類型更改為Event
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.