Reputation: 43
The structure likes this:
I have a Frame and two button - btnA, btnB
when I press btnA, a createPanel() function will return a panelA to be displayed in the frame,
and so does btnB.
btnA and btnB can be switched.
Before I add the panel into the frame, I use a clearPanel() function to clear the existing panels in the frame.
but the question is when I resize or click the panel, I can see the previous panels that should be removed already.
Is there anything I lost?
public void actionPerformed(ActionEvent e) {
String buttonString = e.getActionCommand();
if (buttonString.equals("A")) {
clearPanel();
A = new APanel();
this.getContentPane().add(A.createPanel(), BorderLayout.CENTER);
this.pack();
componentMap.put("A", A);
btnB.setEnabled(true);
btnA.setEnabled(false);
}
else if (buttonString.equals("B")) {
clearPanel();
chart = new BPanel();
this.getContentPane().add(B.createPanel(), BorderLayout.CENTER);
this.pack();
componentMap.put("B", B);
btnA.setEnabled(true);
btnB.setEnabled(false);
}
}
private void clearPanel() {
if (!componentMap.isEmpty()) { // I store panels in a HashMap
for (Object o: componentMap.values()) {
this.getContentPane().remove((JPanel)o);
}
this.getContentPane().invalidate();
componentMap.clear();
}
}
Upvotes: 1
Views: 1165
Reputation: 47607
You are adding A.createPanel()
and B.createPanel()
to the contentPane but you store A
and B
in your componentMap. Therefore, when you call this.getContentPane().remove((JPanel)o);
, you are doing this on A
and/or B
which are not in the content pane and therefore you don't remove anything.
You could use a simpler/safer approach if you want to clear the content pane:
this.getContentPane().removeAll();
Upvotes: 2