简体   繁体   中英

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. Normally in JButton I can just add ActionListener like this:

button.addActionListener(someControllerClass.createButtonListener());

In code above createButtonListener() returns ActionListener.

My question is: What is the equivalent of JButton addActionListener ?

If you want to eg reuse an EventHandler , define it like described in JavaFX Documentation as:

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:

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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