0
try {
      for (int i = 0; i < 148; i++) {
        zx = zx+1;
        if (zx==15) {
          zx = 0;
          zy = zy+1;
          gbc.gridheight = zy;
        } // end of if
        gbc.gridwidth = zx;
        JButton b = new JButton(champs[i]);
        cp.add(b, gbc);
        b.setName(champs[i]);
        if (b.getModel().isPressed()) {
          System.out.println(b);
        } // end of if
      }          
    } catch(Exception e) {
      System.out.println(e);
    }

I am trying to add an action/response to my 148 JButtons if they are pressed but it seems like I'm using the wrong if-clause. The layout works totally fine and all buttons are displayed in the right place with the right name but I can't add an action to them. I am still a java beginner so please keep that in mind. Any help is appreciated. Thanks in advance.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Shizuja
  • 13
  • 2
  • 1
    Does [this](https://stackoverflow.com/questions/284899/how-do-you-add-an-actionlistener-onto-a-jbutton-in-java) answer your question? – Sweeper Feb 29 '20 at 11:27
  • You can't catch a user-action like this. This may enlighten you: https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html https://stackoverflow.com/questions/17511789/button-actionlistener https://www.mainjava.com/swing/java-jbutton-tutorial-with-actionlistener-programming-examples/ – Melvin Feb 29 '20 at 11:27

1 Answers1

0

You need action listeners.

Once your JButton is created and initialized, you need to add an event listener to it. If you are using a GUI builder, you can go to design mode and right-click on the Button and go to Action/Action Performed and it will create the method for you and you can input your code there.

If you are coding the swing application, you can initialize your button, then add an event listener to it manually. Ex:

    private JButton button = new JButton("Button");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //insert code here
        }
    });
ADSquared
  • 207
  • 3
  • 12