Add delete panel at jframe runtime

I am trying to add and remove a panel in a swinging JFrame Container window using the following code. JPanel is added if it is added to the constructor, but not added to it.

import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; class test extends JFrame implements ActionListener { test() { Container cp = this.getContentPane(); JButton b1 = new JButton("add"); JButton b2 = new JButton("remove"); cp.add(b1); cp.add(b2); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if (ae.getActionCommand().equals("add")) { panel1 frm = new panel1(); cp.add(frm); } if (ae.getActionCommand().equals("remove")) { remove(frm); } } public static void main(String args[]) { test t1 = new test(); t1.show(true); } } class panel1 extends JPanel { panel1() { JButton b1 = new JButton("ok"); add(b1); } } 
+4
source share
2 answers
  • for your concept (after deleting or adding JPanel in JFrame ) you need to call validate() and repaint() in JFrame

  • it would be better to use CardLayout

+5
source

I was dealing with a similar problem, I wanted to change the panel contained in the panel at runtime
After some testing, retesting and a lot of unsuccessful my pseudo-algorithm:
parentPanel: contains the panel we want to remove
childPanel: the panel we want to switch
parentPanelLayout: parentPanel layout
editParentLayout (): builds a parentPanel with different childPanel and NEW parentPanelLayout each time

 parentPanel.remove(childPanel); editParentLayout(); parentPanel.revalidate(); parentPanel.repaint(); 
+1
source

All Articles