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.
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.
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:
However, this is exactly what a CardLayout does for you, so the proper solution is to follow aardvarkk’s suggestion.