Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a button to perform an action in my code? [duplicate]

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.

like image 231
javacodex Avatar asked Jan 25 '26 09:01

javacodex


2 Answers

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);.

like image 87
fill͡pant͡ Avatar answered Jan 26 '26 23:01

fill͡pant͡


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);
}
like image 35
ΦXocę 웃 Пepeúpa ツ Avatar answered Jan 26 '26 22:01

ΦXocę 웃 Пepeúpa ツ