3

How do I call a button to perform an action in my code? I know to use action listeners, but what if the button doesn't have a variable name like below?

I'm new to Java, so please be patient with me.

public class Game
{
    public static void main (String[] args)
    {
        JFrame frame = new JFrame ("Game");

        frame.setLayout(new GridLayout(7, 6));

        for(int i = 0; i < 42; i++)
        {
            frame.add(new JButton()); // This is the part I'm talking about!!!
        }

        frame.getContentPane().add(new gameBoard());
        frame.pack();
        frame.setVisible(true);
    }

Thanks.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
javacodex
  • 31
  • 1
  • Usually the button's action is much more important than the button. I often create buttons anonymously, don't care about giving them variable names or having references to them, but yes having reference to the Action (AbstractAction derived object) that is passed into the button. – Hovercraft Full Of Eels Jun 08 '16 at 17:19

3 Answers3

3

If you want to add an ActionListener to each of the JButton objects you will have to do something like this:

    private void createButtons(){  
        for(int i=0;i<42;i++){
                JButton button = new JButton("Name");
                button.addActionListener(YourActionListenerHere);
                frame.add(button);
         }
    }

In the piece of code above all i am doing is create the button as you do, but i make it in the form of a variable accessible through my code named 'button' here: JButton button = new JButton("Name"); and then i add an ActionListener to the button (i supose you already have a class implementing ActionListener) and lastly i add it to the frame with frame.add(button);.

fill͡pant͡
  • 1,147
  • 2
  • 12
  • 24
3

The big point in your question that is complicating a little your wish is the fact that you are adding buttons anonymously to the frame...

I would suggest you to try this:

  1. Create a list of JButtons
  2. Get the button by the index, add the listener
  3. Add it to the frame

Example:

public static void main(String[] args) {
int _k = 3;
JFrame frame = new JFrame("Game");
frame.setLayout(new GridLayout(7, 6));
List<JButton> jbl = new ArrayList<>();
    for (int i = 0; i < _k; i++) {
        jbl.add(new JButton(":)" + i));
        jbl.get(i).addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(((JButton) e.getSource()).getText());
            }
        });
        frame.add(jbl.get(i)); // This is the part I'm talking
    }
frame.getContentPane().add(new gameBoard());
frame.pack();
frame.setVisible(true);
}
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • I think initializing a button object, then doing operations on it, then finally adding to the list looks a bit cleaner than getting it back out of the list to do those operations, no? – OneCricketeer Jun 08 '16 at 17:20
2
package test;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Game
{
    public static void main (String[] args)
    {
        JFrame frame = new JFrame ("Game");

        frame.getContentPane().setLayout(new GridLayout(7, 6));


        for(int i = 0; i < 42; i++)
        {
            String buttonName = "Button "+ i;
            
             //create the button
            JButton button = new JButton(buttonName);
            
            //add an action listener to it so it can do something
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                 
                  //... here goes what ever the button needs to do  
                  System.out.println(buttonName+" clicked");

                }
            });
   
            frame.getContentPane().add(button); //add the button 
        }

        //you need to change the layout if you want to add more
        //frame.getContentPane().add(new gameBoard());
        frame.pack();
        frame.setVisible(true);
    }
}

This is how it looks: enter image description here

Practically you may need to store refrences to all butons as in @ΦXoce 웃 Пepeúpa answer, if you want to relate to those buttons again.

Community
  • 1
  • 1
c0der
  • 18,467
  • 6
  • 33
  • 65