[英]Javafx adding ActionListener to button
button.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
label.setText("Accepted");
}
});
在上面的代碼中,我們定義了按下按鈕時會發生什么。 這一切都很好,但我想創建新的 ActionListener,然后將其添加到我的按鈕中。 通常在 JButton 中,我可以像這樣添加 ActionListener:
button.addActionListener(someControllerClass.createButtonListener());
在上面的代碼中 createButtonListener() 返回 ActionListener。
我的問題是: JButton addActionListener 的等價物是什么?
如果您想重用EventHandler
,請按照JavaFX 文檔中的描述將其定義為:
EventHandler<ActionEvent> buttonHandler = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
label.setText("Accepted");
event.consume();
}
};
您現在可以通過以下方式將定義的buttonHandler
添加到onAction
中:
button.setOnAction(buttonHandler);
並從提供完整刪除選項的文檔中引用:
要刪除由便利方法注冊的事件處理程序,請將 null 傳遞給便利方法,例如
node1.setOnMouseDragged(null).
結果為您:
button.setOnAction(null)
該文檔還提供了一些如何為特定事件添加處理程序的示例 - 這是一個很好的閱讀。
相同的方法,但使用 lamda 表達式更容易:
buttonSave.setOnAction(event -> buttonSaveClicked());
我想這是我應該做的。 創建處理程序:
public EventHandler<Event> createSolButtonHandler()
{
btnSolHandler = new EventHandler<Event>() {
@Override
public void handle(Event event) {
System.out.println("Pressed!");
biddingHelperFrame.getBtnSag().setVisible(false);
}
};
return btnSolHandler;
}
將處理程序添加到按鈕:
btnSol.addEventHandler(MouseEvent.MOUSE_CLICKED, biddingHelperFrameController.createSolButtonHandler());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.