Javafx 将 ActionListener 添加到按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40757911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javafx adding ActionListener to button
提问by MertG
button.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
label.setText("Accepted");
}
});
In the code above we are defining what will happen when we press the button. This is all good but I wanna create new ActionListener and then add it to my button. Normally in JButton I can just add ActionListener like this:
在上面的代码中,我们定义了按下按钮时会发生什么。这一切都很好,但我想创建新的 ActionListener,然后将其添加到我的按钮中。通常在 JButton 中,我可以像这样添加 ActionListener:
button.addActionListener(someControllerClass.createButtonListener());
In code above createButtonListener() returns ActionListener.
在上面的代码中 createButtonListener() 返回 ActionListener。
My question is: What is the equivalent of JButton addActionListener ?
我的问题是: JButton addActionListener 的等价物是什么?
采纳答案by MertG
I think this is how I should do. Creating the handler:
我想这是我应该做的。创建处理程序:
public EventHandler<Event> createSolButtonHandler()
{
btnSolHandler = new EventHandler<Event>() {
@Override
public void handle(Event event) {
System.out.println("Pressed!");
biddingHelperFrame.getBtnSag().setVisible(false);
}
};
return btnSolHandler;
}
Adding Handler to button:
将处理程序添加到按钮:
btnSol.addEventHandler(MouseEvent.MOUSE_CLICKED, biddingHelperFrameController.createSolButtonHandler());
回答by SSchuette
If you want to e.g. reuse an EventHandler
, define it like described in JavaFX Documentationas:
如果您想重用EventHandler
,请按照JavaFX 文档中的描述将其定义为:
EventHandler<ActionEvent> buttonHandler = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
label.setText("Accepted");
event.consume();
}
};
You can now add your defined buttonHandler
to the onAction
of your button via:
您现在可以通过以下方式将您的定义添加buttonHandler
到onAction
您的按钮中:
button.setOnAction(buttonHandler);
And citing from the documentation providing the remove option for completeness:
并从提供完整删除选项的文档中引用:
To remove an event handler that was registered by a convenience method, pass null to the convenience method, for example,
node1.setOnMouseDragged(null).
要删除由便利方法注册的事件处理程序,请将 null 传递给便利方法,例如,
node1.setOnMouseDragged(null).
Resulting for you in:
结果为您:
button.setOnAction(null)
The documentation furthermore provides some examples how to add handler for specific events - it's a good read.
该文档还提供了一些如何为特定事件添加处理程序的示例 - 这是一个很好的阅读。
回答by D4NT3
Just the same approach, but easier with lamda expressions:
相同的方法,但使用 lamda 表达式更容易:
buttonSave.setOnAction(event -> buttonSaveClicked());