Asperger
Asperger

Reputation: 3222

Java use event handler on multiple buttons dynamically and in a clean way

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?

Upvotes: 1

Views: 787

Answers (1)

Zarwan
Zarwan

Reputation: 5767

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.

Upvotes: 1

Related Questions