我创建了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 中,最后将 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的方法。
setVisible(false)
吗? - khachik