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.
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);.
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:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With