Is there a more efficient way to handle button click events than several if statements?
Asked Answered
K

1

5

So, I will do my best to explain this question...

Basically, I have a GUI whose main window has several buttons on it (probably about 10). I am putting the buttons themselves in an array, but when it comes to handling click events for each button, something different is going to happen depending on which one is clicked.

Instead of doing something like this:

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("Button1Text") { /* do stuff */ }
    else if(e.getActionCommand().equals("Button2Text") { /* do stuff */ }
    else if(e.getActionCommand().equals("Button3Text") { /* do stuff */ }
    else if(e.getActionCommand().equals("Button4Text") { /* do stuff */ }
}

Is there a more efficient way to handle each button's response when it gets clicked? The idea is that whenever a button gets clicked, a new window will open to let the user perform various tasks associated with that button. I was thinking of somehow using getActionCommand() in combination with the Class.forName()/newInstance() methods, but I'm not sure if there is another (or easier) way to do something like this.

Kevyn answered 1/5, 2014 at 1:17 Comment(1)
I'm probably going to make myself look stupid here, but why don't you assign each Button it's own ActionListener?Peart
B
7

The ActionListener you've shown is sometimes known as a "switchboard listener", and you're correct to think that it can be improved upon. It is quite rigid code, making it hard to debug and enhance.

Best I think would be to not have the GUI implement ActionListener at all but rather to use unique Actions (i.e., AbstractActions) for each class of button and then plug the appropriate Action into the appropriate button. To plug with minimal coupling, consider using dependency injection a la Spring or Guice.

Buyse answered 1/5, 2014 at 1:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.