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);
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.addActionListene开发者_开发技巧r(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);
});
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.JFrame is window and JPanel is a container. The moment the JPanel instance loses its reference, it will be garbage collected.
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.
精彩评论