Auro
Auro

Reputation: 1628

Using same EventHandler for MouseEvent & KeyEvent in JavaFX?

I'm new to Java programming, so this question may sound stupid to many here. I'm trying to get myself comfortable with JavaFX Event handling mechanism.

I'm developing a GUI where I want a button to perform the same function when it's clicked and also when the Enter key is pressed.

Can I do the following?

public class ButtonHandler implements EventHandler<ActionEvent>
{
somefunction();
}

And then use it for both KeyEvent & MouseEvent

button.setOnMouseClicked(new ButtonHandler);
button.setOnKeyPressed(new ButtonHandler);

Upvotes: 0

Views: 1593

Answers (1)

James_D
James_D

Reputation: 209340

As long as you don't need any information from the specific event (such as coordinates of the mouse, or the key that was pressed), you can do

EventHandler<Event> handler = event -> {
    // handler code here...
};

and then

button.addEventHandler(MouseEvent.MOUSE_CLICKED, handler);
button.addEventHandler(KeyEvent.KEY_PRESSED, handler);

Of course, you can also just delegate the actual work to a regular method:

button.setOnMouseClicked(e -> {
    doHandle();
});
button.setOnKeyPressed(e -> {
    doHandle();
});

// ...

private void doHandle() {
    // handle event here...
}

Upvotes: 1

Related Questions