gpt4 book ai didi

java - JComboBox的ActionListener并初始化JPanel

转载 作者:太空宇宙 更新时间:2023-11-04 13:48:46 35 4
gpt4 key购买 nike

我想编写一个程序,借助 JComboBox,您可以在其中偶然发现场景 (JPanel)。我使用了 ActionListener,但它不起作用。

在构造函数的开头,我将面板定义为最终面板,但这没有帮助。

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

最佳答案

我建议你将panel作为你的类的一个属性。然后调用panel,例如YourClass.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();
}
}
});
}
}

关于java - JComboBox的ActionListener并初始化JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30545118/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com