动作监听器
Action Listeners
我有 jbutton 的行和列,单击每个按钮时它们应该变成红色,第二次单击时它们应该 return 到它们的原始颜色。到目前为止,我写的代码如下:
public class MainPanel extends JPanel
{
private JButton[][] btn1 = new JButton[3][5];
public MainPanel()
{
JPanel MainPanel= new JPanel();
MainPanel.setPreferredSize(new Dimension(700,700));
JPanel p1 = new JPanel();
{
p1.setLayout(new GridLayout(3,5,10,10));
p1.setBackground(Color.WHITE);
for(int i = 0; i < 3; i++)
for(int j = 0; j < 5; j++)
{
btn1[i][j] = new JButton();
btn1[i][j].setBackground(Color.YELLOW);
p1.add(btn1[i][j]);
btn1[i][j].addActionListener
(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btn1[i][j].setBackground(Color.RED);
}
}
);
}
}
}
}
第 btn1[i][j].setBackground(Color.RED);
行表示 'local variables referenced from an inner class must be final or effectively final'。有谁知道如何解决这个问题?
在循环中添加侦听器:
for(int i = 0; i < 3; i++)
for(int j = 0; j < 5; j++) {
final JButton btn = btn1[i][j];
btn1[i][j].addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
btn.setBackground(Color.RED);
}
}
);
}
您只为第一个按钮添加了侦听器。
我有 jbutton 的行和列,单击每个按钮时它们应该变成红色,第二次单击时它们应该 return 到它们的原始颜色。到目前为止,我写的代码如下:
public class MainPanel extends JPanel
{
private JButton[][] btn1 = new JButton[3][5];
public MainPanel()
{
JPanel MainPanel= new JPanel();
MainPanel.setPreferredSize(new Dimension(700,700));
JPanel p1 = new JPanel();
{
p1.setLayout(new GridLayout(3,5,10,10));
p1.setBackground(Color.WHITE);
for(int i = 0; i < 3; i++)
for(int j = 0; j < 5; j++)
{
btn1[i][j] = new JButton();
btn1[i][j].setBackground(Color.YELLOW);
p1.add(btn1[i][j]);
btn1[i][j].addActionListener
(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btn1[i][j].setBackground(Color.RED);
}
}
);
}
}
}
}
第 btn1[i][j].setBackground(Color.RED);
行表示 'local variables referenced from an inner class must be final or effectively final'。有谁知道如何解决这个问题?
在循环中添加侦听器:
for(int i = 0; i < 3; i++)
for(int j = 0; j < 5; j++) {
final JButton btn = btn1[i][j];
btn1[i][j].addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
btn.setBackground(Color.RED);
}
}
);
}
您只为第一个按钮添加了侦听器。