3

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
  • 241
  • 1
  • 9
  • 26

2 Answers2

5

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();
James_D
  • 201,275
  • 16
  • 291
  • 322
  • 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? – CookieMonster Feb 28 '16 at 00:10
  • @CookieMonster: alternative ways to attach data to the node: [`setUserData`](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#setUserData-java.lang.Object-) and [`getProperties`](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#getProperties--) – fabian Feb 28 '16 at 09:37
3

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;
}
Hamburg is nice
  • 369
  • 4
  • 10