这是我的代码:
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
panel_1.add(button);
}
}
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//If Button is clicked, make the button unclickable
if(button == (JButton)e.getSource())
{
button.setEnabled(false);
}
}
});
我想让我从这个10 x 10网格按钮布局中点击的任何JButton都不可点击;但是,这种方法只能使其他没有右键无法点击,有什么不对?我已将ActionListener放在负责制作按钮的for-Loop之外。我不知道发生了什么。
这是它的样子:
编辑:bsd代码有效。在沿这些行添加按钮之前添加ActionListener。
答案 0 :(得分:3)
您只需将ActionListener添加到最后创建的按钮。
您需要将ActionListener添加到循环内创建的每个按钮。
所以代码应该是这样的:
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
button.setEnabled( false );
}
};
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
button.addActionListener( al );
panel_1.add(button);
}
}
答案 1 :(得分:2)
由于您要禁用面板中的所有按钮。按钮动作侦听器应位于for循环中。
button = new JButton();
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//If Button is clicked, make the button unclickable
if(button == (JButton)e.getSource())
{
button.setEnabled(false);
}
}
});