我已经创建了 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 中删除早期面板并将另一个 JPanel 添加到 JFrame。
第二个 JMenuItem 执行相反的操作,移除早期的 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 实例失去其引用的那一刻,它将被垃圾收集。
关于java - 面板从 JFrame 中移除后如何处理 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4463026/