Adesh singh Adesh singh - 1 year ago 109
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");

public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("add")) {
panel1 frm = new panel1();
if (ae.getActionCommand().equals("remove")) {

public static void main(String args[]) {
test t1 = new test();;

class panel1 extends JPanel {
panel1() {
JButton b1 = new JButton("ok");

Answer Source
  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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download