5

I would like to add an ActionListener to a group of buttons. Is there any class that wrap the buttons? Something like GroupJButtons or something more generally group of objects? so I can set an ActionListener to all of them. After all I don't really care which buttons is pressed I just want to change his text so all I need to do is casting it to a JButton and changing the text.

The whole process would reduce the code lines in 1 or 2 (in case you use a loop) but I want to do that since it sounds logically better.

1
  • 2
    It is a very unusual GUI that has many buttons do exactly the same thing. What is the use-case? Dec 9, 2012 at 15:34

2 Answers 2

7

In this case you can extend the AbstractAction class and simply apply the same action to many buttons.

  class MyAction extends AbstractAction {
       public MyAction(String text, ImageIcon icon,
                  String desc, Integer mnemonic) {
       super(text, icon);
       putValue(SHORT_DESCRIPTION, desc);
        putValue(MNEMONIC_KEY, mnemonic);
   }
   public void actionPerformed(ActionEvent e) {
        //do the action of the button here
    }
  }

Then for each button that you want the same thing to happen you can:

 Action myAction = new MyAction("button Text", anImage, "Tooltip Text", KeyEvent.VK_A);
 button = new JButton(myAction);
4
  • Very nice solution! But doesn't it seem a bit overkill? just for a group of buttons?
    – user1103589
    Dec 9, 2012 at 14:46
  • 2
    @Arno: it doesn't seem over-kill to me. 1+ for the good answer. You could create one MyAction object and use it to create many buttons, if all buttons will have the same text and action. Now if the buttons will have different titles, then you may need to instead create one ActionListener that is then added to several buttons. Dec 9, 2012 at 14:47
  • @HovercraftFullOfEels, yes my solution demonstrates approach for buttons with different titles Dec 9, 2012 at 14:54
  • In the above example if you want different text and images per button then you create different instances of MyAction with different parameters. You can modify the constructor to suit yourself. Dec 9, 2012 at 15:39
4

You can use this to create each button

private JButton createButton(String title, ActionListener al) {
    JButton button = new JButton(title);
    button.addActionListener(al);
    return button;
}

And this to process the action

public void actionPerformed (ActionEvent ae) {
    JButton button = (JButton)ae.getSource();
    button.setText("Wherever you want");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.