简体   繁体   中英

JPanel not refreshing upon selection with 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();        
}

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:

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 = display;

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();

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

When you add currentDisplay to the GUI, you're not adding the currentDisplay variable to the GUI, but rather the object that the currentDisplay variable refers to. So later when you change what component the currentDisplay variable refers to, it should make sense that this will have absolutely no effect on the component displayed by the GUI since it still holds the original object.

I second the excellent recommendation by aardvarkk that you use a CardLayout (1+ to aardvarkk). If you do this, you will find that it will work smoothly (and then you should accept Aardvarkk's answer as the answer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM