ActionEvent get source of button JavaFX

CookieMonster picture CookieMonster · Feb 27, 2016 · Viewed 24.1k times · Source

I have about 10 buttons which are going to be sent to the same method. I want the method to identify the source. So the method knows button "done" has evoked this function. Then I can add a switch case of if statement to handle them accordingly. This is what I have tried

//Call:
    btnDone.setOnAction(e -> test(e));


   public void test(ActionEvent e) {
        System.out.println("Action 1: " + e.getTarget());
        System.out.println("Action 2: " + e.getSource());
        System.out.println("Action 3: " + e.getEventType());
        System.out.println("Action 4: " + e.getClass());
    }

Output Result:

Action 1: Button@27099741[styleClass=button]'Done'
Action 2: Button@27099741[styleClass=button]'Done'
Action 3: ACTION
Action 4: class javafx.event.ActionEvent

Done is the text on the button. As you can see I could use e.getTarget() and/or e.getSource() then I'll have to substring it, so only the "Done" appears. Is there any other way to get the string in the apostrophe instead of having to substring.

UPDATE: I have tried passing Button and it works but I still want to know a solution using ActionEvent.

//Call:
        btnDone.setOnAction(e -> test(btnDone));


       public void test(Button e) {
            System.out.println("Action 1: " + e.getText());
        }

Output is Action 1: Done

Answer

James_D picture James_D · Feb 28, 2016

Typically I much prefer using a different method for each button. It's generally a very bad idea to rely on the text in the button (e.g. what will happen to the logic if you want to internationalize your application?).

If you really want to get the text in the button (and again, I have to emphasize that you really don't want to do this), just use a downcast:

String text = ((Button)e.getSource()).getText();