从JFrame中删除面板后,如何处理JPanel [英] How can JPanel be disposed after the panel has been removed from the JFrame

查看:167
本文介绍了从JFrame中删除面板后,如何处理JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了2个Jpanel,它将添加到JFrame。

首先将一个JPanel添加到JFrame。

我使用了add() JFrame添加JPanel的方法。

I have created 2 Jpanel which will be added to a JFrame.
At first one of the JPanel is added to the JFrame.
I have used the "add()" method of JFrame to add the JPanel.

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

JFrame上设置了JMenuBar。

添加了2个JMenuItems最后添加到JMenuBar的JMenu。

单击第一个JMenuItem时,从JFrame中删除earliar面板并将另一个JPanel添加到JFrame。
第二个JMenuItem执行相反的操作,删除earliar JPanel并放置更新的JPanel。

The JFrame has a JMenuBar set on it.
With 2 JMenuItems added to a JMenu which is finally added to the JMenuBar.
The 1st JMenuItem when clicked remove the earliar panel from the JFrame and add the other JPanel to the JFrame. The 2nd JMenuItem does the inverse,removing the earliar JPanel and placing the newer 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。


The problem i face now is that the panels donot get disposed when removed and somewhere in the memory the panels are occupuing memory.
Although the previous panel is not visible and the newer panel can be seen, but the memory that the previous panel(not visible panel) is taking up can be seen in the task manager.
And as i switch between the panels the memory they ocuppy goes on increasing, as a new instance of the panel is being created every time. I want to dispose the panels when removed, but there is no method to dispose a JPanel like the dispose() method for JFrame.

推荐答案

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

Looking at the code above, it looks like a step is missed. "remove()" will remove the reference from the content pane, but if the panel variable is not set to null or goes out of scope, the panel will still have a reference and it will not be garbage collected.

这篇关于从JFrame中删除面板后,如何处理JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆