1

I want the event handler to be added to one parent that contains many buttons. That event listener then analyzes bubbled events to find a match on child nodes which I can target. With other words, right now I do this:

for(Object button: menuButtons) {
 button.setOnAction(handler);
}

Now I have all buttons attached to an event handler, great but not what I want. I just want them to have one handler on the parent and use that to somehow fire the different buttons. Is it possible?

asked Sep 27, 2016 at 5:07
3
  • You could make your own custom Button class that extends Button and pass in a listener to apply to all the buttons. Commented Sep 27, 2016 at 5:10
  • @Zar could you show a simple example? Commented Sep 27, 2016 at 5:11
  • I'll write an answer. Commented Sep 27, 2016 at 5:11

1 Answer 1

1

One way is to make your own Button class to apply the listener for you:

public class MyButton extends Button {
 public MyButton(MyHandler handler) {
 super();
 setOnAction(handler);
 }
}

Then in your parent code:

MyHandler handler = new MyHandler(...);
MyButton menuButton1 = new MyButton(handler);
MyButton menuButton2 = new MyButton(handler);
...

I'm not sure why you want to do this though, because the handler will receive events from all the buttons. You'll have to distinguish between them.

Edit: Actually, after reading the question again I'm not sure if this is what you're asking for. You want to apply the listener to the parent and have it indirectly be passed to the buttons? I'm not sure if that is possible. It would depend on what type of object the parent is, and even then if the parent was to receive events it wouldn't be able to know what buttons were clicked (unless you do some ugly stuff maybe, like checking the coordinates of the touch with the coordinates of the buttons, but I don't think that's worth it). With this solution you are keeping it to one MyHandler object, but that was the case in your original solution too.

answered Sep 27, 2016 at 5:15
Sign up to request clarification or add additional context in comments.

2 Comments

Not really yep but it is an alternative so I accepted. You also explained that it's not possible in java without dirty work arounds. Your information is valuable.
Glad to be of help.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.