4

I am trying to add and remove panel on a swing window JFrame Container with the help of following code. JPanel is being added if it added in the constructor but its not being added runtime .

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);
    }
}
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
Adesh singh
  • 2,083
  • 9
  • 24
  • 36

2 Answers2

6
  1. for your concept (after remove or add JPanel to JFrame) have to call validate() & repaint() to JFrame

  2. better could be to use CardLayout

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • where i have to call validate() and repaint() method. – Adesh singh Dec 10 '12 at 12:54
  • one time, as last code lines, after all changes to the GUI are done, – mKorbel Dec 10 '12 at 12:56
  • @mKorbel calling `revalidate()` is always a better option vs `validate()`/`invalidate()` see [here](http://stackoverflow.com/questions/13549976/how-to-change-the-dimension-of-a-component-in-a-jframe/13551229#13551229) for more, but +1 for the rest. – David Kroukamp Dec 10 '12 at 13:24
  • 1
    @David Kroukamp revalidate(:-) is available for JFrame & Java7(no idea about OPs version), upto Java7 is there only validate(:-), never to use invalidate, for standard LayoutManagers, this notifiers is implemented correctly in APIs, no reason to call this method twice – mKorbel Dec 10 '12 at 14:08
  • Ahh yes Forgot about the Java 7 support of `revalidate()` – David Kroukamp Dec 10 '12 at 14:09
1

I was dealing with similar issue, I wanted to change the panel contained in a panel on runtime
After some testing, retesting and a lot of failing my pseudo-algorithm is this:

parentPanel : contains the panel we want to remove
childPanel : panel we want to switch
parentPanelLayout : the layout of parentPanel
editParentLayout() : builds parentPanel with different childPanel and NEW parentPanelLayout every time

parentPanel.remove(childPanel); 
editParentLayout();
parentPanel.revalidate();
parentPanel.repaint();
Dimitris
  • 3,975
  • 5
  • 25
  • 27