【问题标题】:ActionListener of JComboBox and initialize JPanelJComboBox的ActionListener并初始化JPanel
【发布时间】:2015-05-30 10:41:03
【问题描述】:

感谢JComboBox,我想编写一个程序,让您可以在其中遇到场景(JPanel)。 我用了ActionListener,但是不行。

在构造函数的开头,我将 panel 定义为 final,但没有帮助。

scene.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String choice = String.valueOf(scene.getSelectedItem());
        if(choice=="Sceneria"||choice=="Scene"){
            slider.setEnabled(false);
            panel = new JPanel();// problem here
        }
    }
});

错误

The final local variable panel cannot be assigned, since it is defined in an enclosing type

【问题讨论】:

  • == 更改为 equals(String)
  • 我的如果没问题。我在其他课上也做过类似的事情,而且效果很好。问题在这里:panel = new JPanel();
  • 1) 为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)或SSCCE(简短、自包含、正确示例)。 2) 但改用CardLayout,如this answer所示。

标签: java swing compiler-errors actionlistener jcombobox


【解决方案1】:

我建议您将panel 设为您班级的一个属性。 然后调用panelYourClass.this.panel

public class YourClass {

    private JPanel panel;

    public YourClass() {

        // ...

        scene.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String choice = String.valueOf(scene.getSelectedItem());
                if(choice.equals("Sceneria") || choice.equals("Scene")) {
                    slider.setEnabled(false);
                    YourClass.this.panel = new JPanel();
                    YourClass.this.panel.revalidate();
                    YourClass.this.panel.repaint();
                }
            }
        });
    }
}

【讨论】:

  • 现在,没有错误,但是 JPanel 不起作用。 ActionListener 工作,因为我可以看到滑块的变化。
  • 你的意思是它不起作用?你期望什么,实际结果是什么?您是否在新的 JPanel 中添加了新组件? 如果您需要更多帮助,请阅读Andrew Thompson's comment
  • youtube.com/watch?v=zHl-VNwNwMU 看看这个。 DrawScene1 是 JPanel 扩展的类
  • 尝试致电YourClass.this.panel.revalidate(); 和/或YourClass.this.panel.repaint();。也可以在getContentPane() 上试试这个。
猜你喜欢
  • 2013-08-04
  • 2014-04-05
  • 2015-06-23
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多