我创建了 2 个 Jpanel,它将添加到 JFrame 中。
首先将一个 JPanel 添加到 JFrame 中。
我使用了 JFrame 的“add()”方法来添加 JPanel。
JPanel panel = new JPanel();
JFrame j = new JFrame();
j.getContentPane().add(panel);
JFrame 上设置了一个 JMenuBar。
将 2 个 JMenuItem 添加到 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 实例失去引用时,它将被垃圾回收。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)