简体   繁体   English

Javafx 将 ActionListener 添加到按钮

[英]Javafx adding ActionListener to button

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.这一切都很好,但我想创建新的 ActionListener,然后将其添加到我的按钮中。 Normally in JButton I can just add ActionListener like this:通常在 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 的等价物是什么?

If you want to eg reuse an EventHandler , define it like described in JavaFX Documentation as:如果您想重用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.该文档还提供了一些如何为特定事件添加处理程序的示例 - 这是一个很好的阅读。

相同的方法,但使用 lamda 表达式更容易:

buttonSave.setOnAction(event -> buttonSaveClicked());

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM