监听行动JButton的阵列
-
25-09-2019 - |
题
让我们说我有一个二维数组的按钮,当一个程序,你点击其中一个会变成红色。我不想seperately申报的每一个按钮,所以我刚刚创建的JButton [] []为他们阵。问题是,我不知道如何使用动作监听器上的任何按钮的阵列中,因此会改变这个特定的按钮的颜色,并没有相关的问题是有关这一点。我试图用“为”,但它并不能帮助:
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);
}
}
}
}
}
解决方案
你尝试:
public void actionPerformed(ActionEvent e){
if( e.getSource() instanceof JButton) {
((JButton)e.getSource()).setBackground(Color.red);
}
}
原因之一,你的代码可能无法正常工作是你用来创建按钮JButton[][]
是您的本地MainW
构造。我所提供的方法可以让你忽略此作用域问题。它也将删除你的迭代方法,并用更高效的解决方案替换它。在你的代码,即使该事件由第一项在列表中引发的,甚至不是你的一个按钮触发,你永远遍历整个二维数组并测试每个。
不隶属于 StackOverflow