Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One ActionListener for many JButtons

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.

like image 445
Imri Persiado Avatar asked Dec 09 '12 14:12

Imri Persiado


2 Answers

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);
like image 186
Vincent Ramdhanie Avatar answered Nov 04 '22 05:11

Vincent Ramdhanie


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");
}
like image 30
Nikolay Kuznetsov Avatar answered Nov 04 '22 07:11

Nikolay Kuznetsov