[英]JPanel not refreshing upon selection with JComboBox
我正在尝试编写一个非常短的 class 将 JPanel 与 JComboBox“联系起来”。 我想我的逻辑是错误的,但是当我 select 使用 JComboBox 的一些新东西时没有任何反应......这是(或多或少)我的代码:
private DisplayPanel currentDisplay; //a displaypanel is simply an extended JPanel with an id field, and an overriden .equals() method
private JComboBox selector;
private List<DisplayPanel> displays;
public SelectionPanel(DisplayPanel panel){
displays = new ArrayList<DisplayPanel>();
selector = new JComboBox(new String[]{panel.id});
currentDisplay = panel;
selector.addActionListener(this);
this.add(selector);
this.add(currentDisplay);
this.displays.add(panel);
}
public void addNewSelection(DisplayPanel panel){
displays.add(panel);
selector.addItem(panel.id);
}
@Override
public void actionPerformed(ActionEvent e) {
JComboBox source = (JComboBox) e.getSource();
String id = (String) source.getSelectedItem();
for(DisplayPanel display: displays)
if(id.equals(display.id))
currentDisplay = display;
this.validate();
}
我假设我需要以某种方式覆盖 repaint() function,但我真的不确定最好的方法。
这是(或多或少)我的代码:
这对我们没有帮助,因为我们不知道如何使用代码的上下文。 为了获得更好的帮助,请在提问时发布SSCCE 。
当前显示 = 显示;
那行代码似乎不正确。 它所做的只是改变一个变量的值。 它不会将面板添加到 GUI。 你的基本代码是:
panel.remove( theOldPanel );
panel.add( theNewPanel );
panel.revalidate();
panel.repaint();
然而,这正是 CardLayout 为您所做的,因此正确的解决方案是遵循 aardvarkk 的建议。
当您将 currentDisplay 添加到 GUI 时,您不会将 currentDisplay变量添加到 GUI,而是将 currentDisplay 变量引用的object添加到 GUI。 因此,稍后当您更改 currentDisplay 变量所指的组件时,这应该不会对 GUI 显示的组件产生任何影响,因为它仍然包含原始 object。
我支持 aardvarkk 的出色建议,即您使用 CardLayout(1+ 到 aardvarkk)。 如果您这样做,您会发现它会顺利运行(然后您应该接受 Aardvarkk的答案作为答案)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.