How can I remove JPanel after the panel has been removed from JFrame

I created 2 Jpanels to be added to the JFrame.
First, one of the JPanel is added to the JFrame.
I used the add () method of JFrame to add a JPanel.

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

JFrame has a JMenuBar set on it.
With the addition of 2 JMenuItems in JMenu, which is finally added to JMenuBar.
The 1st JMenuItem, when clicked, removes the knapsack panel from the JFrame and adds another JPanel to the JFrame. The second JMenuItem performs the inverse by removing the early JPanel and placing the new 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);
});

, , , , , - .
, , , ( ), .
, , . , JPanel, dispose() JFrame.

+3
2

JFrame - , JPanel - . , JPanel , .

+1

, . "remove()" , ​​ , - , .

+1

Source: https://habr.com/ru/post/1780714/


All Articles