Adesh singh Adesh singh - 2 months ago 10
Java Question

add remove panel on jframe runtime

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);
}
}

Answer
  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

Comments