public class ButtonGrid extends JFrame{
private final JButton[][] grid;
private int length,width;
public ButtonGrid(int width,int length){
JPanel panel = new JPanel();
JButton start = new JButton("Start");
JButton reset = new JButton("Reset");
panel.add(start);
//start.addActionListener(this);
panel.add(reset);
add(panel,BorderLayout.PAGE_START);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(width,length));
grid = new JButton[width][length];
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]=new JButton();
grid[x][y].setBackground(Color.WHITE);
panel1.add(grid[x][y]);
grid[x][y].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
JButton b1 = (JButton)source;
if(b1 == source){
b1.setBackground(Color.BLACK);
}
}
});
reset.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
JButton b1 = (JButton)source;
if(b1 == source){
b1.setBackground(Color.WHITE);
}
}
});
}
}
add(panel1,BorderLayout.CENTER);
panel1.setBackground(Color.RED);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
ButtonGrid bg = new ButtonGrid(25,25);
}
});
}
}
在这段代码中,我可以更改网格中按钮的背景,但我想通过再次将背景更改为白色来重置网格。我不能这样做,因为我的 actionListener 不允许使用 grid[x][y] 设置背景。请帮助我如何进行。