问题
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.
回答1:
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.
回答2:
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).
来源:https://stackoverflow.com/questions/6617077/jpanel-not-refreshing-upon-selection-with-jcombobox