ActionEvent get source of button JavaFX

26,721

Solution 1

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

Solution 2

As @James_D pointed out, relying on the button text displayed to the user is a bad idea for various reason (tho probably sufficient for your case!)

A different approach would be, to assign IDs to the buttons and then retrieving them in the callback method. That would look something like that:

// that goes to the place where you create your buttons
buttonDone.setId("done");

...

// that goes inside the callback method
String id = ((Node) event.getSource()).getId()

switch(id) {
    case "done":
        // your code for "buttonDone"
        break;
}
Share:
26,721
CookieMonster
Author by

CookieMonster

Updated on July 09, 2022

Comments

  • CookieMonster
    CookieMonster almost 2 years

    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

  • CookieMonster
    CookieMonster over 8 years
    I see, so casting it worked. Thanks, exactly what I was looking for. I'm always opened for learning, so what would you prefer instead of this?
  • fabian
    fabian over 8 years
    @CookieMonster: alternative ways to attach data to the node: setUserData and getProperties