This is a difficult ask, but how do I add an ActionListener
to multiple buttons that I have created in a for loop?
Here's my code so far:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Loop extends JFrame {
public Loop() {
this.setSize(700, 300);
this.setLocation(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jpanel = new JPanel();
jpanel.setBackground(Color.CYAN);
jpanel.setLayout(new GridLayout(0,6));
JButton[] jButton = new JButton[6];
String string[] = {"One","Two","Three","Four","Five","Six"};
this.add(jpanel);
int j=0;
for(int i =0; i<jButton.length;i++) {
while(j < 6) {
jButton[i]= new JButton();
jButton[i].setPreferredSize(new Dimension(50, 50));
jButton[i].setText(string[j++]);
jpanel.add(jButton[i]);
jButton[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Works");
}
});
}
}
}
public static void main(String[] args) {
Loop myLoop = new Loop();
myLoop.setVisible(true);
}
}
(It seems from the code that to add the ActionListener
in a for
loop gives all the buttons the same action. Problem is I want the actions to be different for each button).
Any response would be greatly appreciated.