从JFrame中删除面板后,如何处理JPanel

我创建了2个Jpanel,它将被添加到JFrame中。
首先,将一个JPanel添加到JFrame中。
我使用了JFrame的“add()”方法来添加JPanel。

JPanel panel = new JPanel(); JFrame j = new JFrame(); j.getContentPane().add(panel); 

JFrame上设置了JMenuBar。
将2个JMenuItems添加到JMenu中,最终添加到JMenuBar中。
单击第一个JMenuItem时,从JFrame中删除earliar面板,并将另一个JPanel添加到JFrame。 第二个JMenuItem执行相反的操作,删除了earliar JPanel并放置了较新的JPanel。

 JMenuItem a = new JMenuItem("p1"); a.addActionListener(new... { Frame2 ob = new Frame2();//another class which adds components on the panel. JPanel p1 = ob.getPanel();//method used to return the JPanel from another class j.getContentPane().remove(0); j.getContentPane().add(p1); }); JMenuItem b = new JMenuItem("p2"); a.addActionListener(new... { Frame3 ob2 = new Frame3();//another class which adds components on the panel. JPanel p2 = ob2.getPanel();//method used to return the JPanel from another class j.getContentPane().remove(0); j.getContentPane().add(p2); }); 

我现在面临的问题是,面板在移除时会被丢弃,而在存储器的某处,面板会占用内存。
虽然前一个面板不可见,可以看到更新的面板,但可以在任务管理器中看到前一个面板(不可见面板)占用的内存。
当我在面板之间切换时,随着每次创建面板的新实例,它们的内存不断增加。 我想在移除时处理面板,但没有方法可以像JFrame的dispose()方法一样处理JPanel。

JFrame是窗口,JPanel是容器。 当JPanel实例丢失其引用时,它将被垃圾收集。

看看上面的代码,看起来似乎错过了一步。 “remove()”将从内容窗格中删除引用,但如果面板变量未设置为null或超出范围,则面板仍将具有引用,并且不会进行垃圾回收。