Let's say I have a program with a 2D array of buttons, and when you click one of them, it turns red. I did not want to declare each individual button separately, so I created a JButton [] [] array for them. The problem is that I don’t know how to use the action listener on any of the buttons in the array, so that it changes the color of this particular button, and none of the related questions have anything to do with this. I tried using the "for", but that does not help:
package appli;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainW extends JFrame implements ActionListener {
public MainW(){
setSize(640,480);
setTitle("title");
setLayout(null);
JButton[][] btnz = new JButton[5][5];
for(Integer i=0;i<5;i++)
{
for(Integer j=0;j<5;j++)
{
btnz[i][j]= new JButton("");
btnz[i][j].setBackground(Color.WHITE);
btnz[i][j].setBounds(10+20*i,10+20*j,20,20);
add(btnz[i][j]);
btnz[i][j].addActionListener(this);
}
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
for(Integer i=0;i<5;i++)
{
for(Integer j=0;j<5;j++)
{
if (e.getSource()==btnz[i][j]);
{
btnz[i][j].setBackground(Color.RED);
}
}
}
}
}
source
share