viper
viper

Reputation: 734

how to set same action / process to multiple buttons in java

I want to create the same actions on multiple buttons of my interface. Is it only feasible by creating seperate action listener methods and calling the method which does the actions or is there any other way? Is it possible by putting the buttons in a group and doing as:-

groupButton.setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent event){ //some other method called } }

Upvotes: 0

Views: 1525

Answers (1)

James_D
James_D

Reputation: 209225

(You should really use setOnAction(...) to handle button presses, rather than setOnMousePressed(), but I'll answer the question as posed.)

Just create the handler and assign it to a variable:

EventHandler<MouseEvent> handler = new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent event) {
        // handle event...
    }
};

groupButton.setOnMousePressed(handler);
someOtherButton.setOnMousePressed(handler);

Upvotes: 2

Related Questions