Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 477
MertG Avatar asked Nov 23 '16 06:11

MertG


People also ask

How do I add an Actionlistener to a Button?

To add an action listener, you just call addActionListener from Abstract Button.

Can a Button fire an ActionEvent?

A Button can fire an ActionEvent. A Button can fire a MouseEvent. A Button can fire a KeyEvent. A TextField can fire an ActionEvent.

What's the method used to set a handler for processing a Button clicked action?

Use the setOnAction method of the Button class to define what will happen when a user clicks the button.

Is JavaFX an MVC?

JavaFX enables you to design with Model-View-Controller (MVC), through the use of FXML and Java. The "Model" consists of application-specific domain objects, the "View" consists of FXML, and the "Controller" is Java code that defines the GUI's behavior for interacting with the user.


1 Answers

If you want to e.g. 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.

like image 83
SSchuette Avatar answered Oct 05 '22 05:10

SSchuette