3
JPanel p = new JPanel();
    p.setLayout(new GridLayout(4, 4, 5, 5));
    String[] buttons = {
        "1", "2", "3", "/", "4",
        "5", "6", "*", "7", "8", "9", "-", "0", ".", "=", "+"
    };
    for (int i = 0; i < buttons.length; i++) {
            p.add(new JButton(buttons[i]));
   add(p);

This code produces a nice calculator layout is there a way to addActionListener to each button while at the same time keeping this layout what i mean is not doing it for each and every button like so.

JButton button1 = new JButton("1");
     button1.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent event) {
// interesting code for button1 goes here
      }
   });
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Meesh
  • 508
  • 1
  • 5
  • 17

4 Answers4

4

Yes, instead of an array of String, have an array of Action instances. Each such Action has a name and is also an ActionListener. Several examples are cited here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
3

You could simply add an ActionListener to each button in your for loop in the form of an AbstractAction:

for (int i = 0; i < buttons.length; i++) {
   JButton button = new JButton(buttons[i]);
   button.addActionListener(new MyAction());
   p.add(button);
}

where

class MyAction extends AbstractAction {
   @Override
   public void actionPerformed(ActionEvent event) {
   ...
   }
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

From my experience you can create list of buttons and run in loop to add ActionListener:

List<JButton> buttonsList = new ArrayList<JButton>(buttons.length):

for (JButton currButton : buttonsList) {

       currButton.addActionListener(){
         ....
       }
   ....
}
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
2

i did it using this code...

   String[] buttons = {
        "1", "2", "3", "/", "4",
        "5", "6", "*", "7", "8", "9", "-", "0", ".", "=", "+"
    };

    Action[] allActions = new Action[buttons.length];

    for ( i = 0; i < buttons.length; i++) {

        allActions[i] = new ButtonAction(buttons[i],i);

        JButton button = new JButton(allActions[i]);

           panel.add(button);


        }

with the class ButtonAction as follows

  public class ButtonAction extends AbstractAction 
  {
int i;
   public ButtonAction(String text, int i) {
    super(text);
    this.i = i;
    }
   public void actionPerformed(ActionEvent e) {
    /* you can put any action here. either make the action depend on array value or 
      the string text */
   System.out.println(i);

   }
 }
Meesh
  • 508
  • 1
  • 5
  • 17