2016-02-13 44 views
0

我是Java編程新手,所以這個問題聽起來很愚蠢。我試圖讓自己適應JavaFX事件處理機制。在JavaFX中爲MouseEvent和KeyEvent使用相同的EventHandler?

我正在開發一個圖形用戶界面,我希望一個按鈕在單擊時執行相同的功能,並且還可以按下Enter鍵。

我可以做以下嗎?

public class ButtonHandler implements EventHandler<ActionEvent> 
{ 
somefunction(); 
} 

然後用其來進行KeyEvent的&的MouseEvent

button.setOnMouseClicked(new ButtonHandler); 
button.setOnKeyPressed(new ButtonHandler); 

回答

1

只要你不需要從特定事件(任何信息,如鼠標的座標,或者說是關鍵按下),你可以做

EventHandler<Event> handler = event -> { 
    // handler code here... 
}; 

然後

button.addEventHandler(MouseEvent.MOUSE_CLICKED, handler); 
button.addEventHandler(KeyEvent.KEY_PRESSED, handler); 

當然,你也可以委託實際工作中一個普通的方法:

button.setOnMouseClicked(e -> { 
    doHandle(); 
}); 
button.setOnKeyPressed(e -> { 
    doHandle(); 
}); 

// ... 

private void doHandle() { 
    // handle event here... 
} 
+0

所以,當我想只輸入時,按下處理按鈕事件,我不能跟你的建議去了? – Auro

+0

不,但您可以將實際工作委派給其他方法。查看更新。 –