java - 错误: local variable referenced from inner class must be final or effective final

标签 java swing

JButton[] button = new JButton[noOfDays];

for(int j=0 ;j<studentNameList.size() ;j++) {
    for(int i=0 ;i<button.length ;i++) {
        button[i]=new JButton((i+1)+"");
        attendencepanels.add(button[i]);

        button[i].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
        ---->  button[i].setBackground(Color.red); //Local variable refenced from inner class must be final or effective final

                //JOptionPane.showMessageDialog(null, "test");
                }
            });

我如何解决actionPerformed方法中button[i]中的这个问题

最佳答案

虽然我不确定,但您也许可以从 ActionEvent e 参数获取 JButton 引用。看起来这就是 getSource() 返回的内容(事件最初发生的对象):

而不是

button[i].setBackground(Color.red);

尝试

JButton button = (JButton) e.getSource();
button.setBackground(Color.red);

关于java - 错误: local variable referenced from inner class must be final or effective final,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39483665/

相关文章:

java - 比较Java中的Date对象

java - POJO类中序列版本id的唯一性

java - ComponentAdapter 中 componentResized 方法的任何替代方法

JPanel 中的 java swing 快捷键/键绑定(bind)

java - 如何保持 2 个 JPanel 彼此垂直对齐?

java - 所见即所得的 XML 编辑器 java

java - 将 Google Play 服务包含到 Android Studio 项目中

java - 返回匹配列表项的计数而不迭代(java)

java - 尝试从另一个类修改 JFrame 时出现空指针异常?

java - 从 ArrayList<HashMap<String, String>> 中检索某些值