使用 JComboBox 更新 JDialog 中的 JPanel 时出现问题
我创建了一个 JDialog,其中包含一个 JComboBox 和一个面板,该面板应根据 JComboBox 中选择的值显示不同的内容。我创建了一个 JPanel (panel_1),它被添加到对话框的内容窗格中,并为 JComboBox 中的每个可能的项目创建了一个附加 JPanel(例如 panel_item_1 和 panel_item_2,如果它只有 2 个项目)。我已在 JComboBox 中附加了以下侦听器类:
public class SelectedListener implements ActionListener {
private SettingsDialog dialog;
public SelectedListener(SettingsDialog dialog){
this.dialog = dialog;
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String selected_settings = (String)cb.getSelectedItem();
if(selected_settings.compareTo("Option 1") == 0){
dialog.panel_1 = dialog.panel_item_1;
dialog.panel_1.updateUI();
}else if(selected_settings.compareTo("Option 2") == 0 ){
dialog.panel_1 = dialog.panel_item_2;
dialog.panel_1.updateUI();
}
}
}
但是,这不会使面板更新为新内容。有什么建议吗?提前致谢
I have created a JDialog which contains a JComboBox and a panel underneath which should display a different content based on the value selected in the JComboBox. I have created a JPanel (panel_1) which is added to the content pane of the dialog and an additional JPanel for each of the possible items in the JComboBox (for example panel_item_1 and panel_item_2 if it does have only 2 items). I have attached the following listener class in the JComboBox:
public class SelectedListener implements ActionListener {
private SettingsDialog dialog;
public SelectedListener(SettingsDialog dialog){
this.dialog = dialog;
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String selected_settings = (String)cb.getSelectedItem();
if(selected_settings.compareTo("Option 1") == 0){
dialog.panel_1 = dialog.panel_item_1;
dialog.panel_1.updateUI();
}else if(selected_settings.compareTo("Option 2") == 0 ){
dialog.panel_1 = dialog.panel_item_2;
dialog.panel_1.updateUI();
}
}
}
However this doesn't make the panel update with the new content. Any suggestion? Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
阅读 Swing 教程中有关如何使用卡片布局的部分其中有一个工作示例可以完全满足您的需求。
编辑:
真正的问题是您不能只更改对变量的引用并期望组件显示在面板上。在面板上执行 revalidate() 之前,您仍然需要将组件添加到面板中。所以你的代码是这样的:
但是,更好的解决方案是使用 CardLayout 来为你完成所有这些工作。
Read the section from the Swing tutorial on How to Use Card Layout which has a working example that does exactly what you want.
Edit:
The real problem is that you can't just change the reference to a variable and expect the component to show up on the panel. You still need to add the component to the panel before you do a revalidate() on the panel. So your code is like:
However, the better solution is to use a CardLayout which does all this work for you.