假设我有一个带有二维按钮数组的程序,当您单击其中一个按钮时,它会变成红色。我不想单独声明每个按钮,所以我只是为它们创建了 JButton[][] 数组。问题是我不知道如何在数组中的任何按钮上使用动作监听器,因此它会改变这个特定按钮的颜色,并且没有任何相关问题与此相关。我尝试使用“for”,但没有帮助:
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);
}
}
}
}
}