使用JComboBox选择时,JPanel不刷新 [英] JPanel not refreshing upon selection with JComboBox

查看:155
本文介绍了使用JComboBox选择时,JPanel不刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个很短的类,将JPanel与JComboBox联系"在一起.我认为我的逻辑不好,但是当我使用JComboBox选择新内容时什么也没有发生……这是(或多或少)我的代码:

I am attempting to write a pretty short class that "ties" a JPanel to a JComboBox. I think I have the logic down, but nothing happens when I select something new using the JComboBox... Here is (more or less) my code:

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()函数,但我确实不确定做到这一点的最佳方法.

I am assuming I need to override the repaint() function somehow, but I am really not sure the best way to do that.

推荐答案

(或多或少)这是我的代码:

Here is (more or less) my code:

这对我们没有帮助,因为我们不知道代码用法的上下文.为了获得更好的帮助,在提出问题时发布 SSCCE .

Which doesn't help us because we don't know the context of how the code is used. For better help post an SSCCE when asking a question.

currentDisplay =显示;

currentDisplay = display;

这行代码似乎不正确.它所做的只是更改变量的值.不会将面板添加到GUI.您的基本代码为:

That line of code doesn't seem correct. All it does is change the value of a variable. It does not add the panel to the GUI. You basic code would be:

panel.remove( theOldPanel );
panel.add( theNewPanel );
panel.revalidate();
panel.repaint();

但是,这正是CardLayout为您所做的,因此正确的解决方案是遵循aardvarkk的建议.

However, this is exactly what a CardLayout does for you, so the proper solution is to follow aardvarkk's suggestion.

这篇关于使用JComboBox选择时,JPanel不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆