Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 364
djmordigal Avatar asked May 01 '14 01:05

djmordigal


1 Answers

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.

like image 105
Hovercraft Full Of Eels Avatar answered Nov 12 '22 02:11

Hovercraft Full Of Eels