2

I have a program that opens up a Jframe. inside this Jframe, I have a button that opens another class that has a Jframe too. Is there any way to to get the new class, and new gui opened in the same frame as the first one, and remove the existing content in the first frame?

This is the first class:

public class FirstFrame {

public FirstFrame() {

JFrame frame = new JFrame();
    frame.setTitle("Title");
    frame.setLayout(new BorderLayout());
    frame.setSize(500,350);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Code for a button, that has an actionlistener wich opens the next
    //class

    frame.setVisible(true);
    frame.setResizable(false);
     }



    public static void main(String[] args){


    new FirstFrame();

  }
}

The second class is almost like this one. The difference between the two frames is that they have different content. When I run my program, everything works just fine, but I get two windows. Also, it says in the task manager that the two frames are running as two different programs.

Is there a way to make the content and even the name of the frame change, instead of having to deal with two different frames?

  • 3
    Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). That advice, of course, presumes the content is put in a group of `JComponent` objects (most often a `JPanel`). – Andrew Thompson Feb 26 '15 at 10:09

1 Answers1

1

You can change the content pane of your JFrame. Let's say you have two JComponents called a and b. You initialize your frame:

JFrame frame = new JFrame();
frame.setContentPane(a);

Then you can just call

frame.setContentPane(b);

to change the content. You may also need to call revalidate and repaint to refresh the frame.

In the below example, pressing the button changes the content of JFrame from single JButton a to JLabel b. You can use any JComponent instead, such as JPanel containing multiple JComponents.

public static void main(String[] args) {
    final JFrame frame = new JFrame();
    frame.setTitle("Title");
    frame.setSize(500, 350);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton a = new JButton("button A");
    frame.setContentPane(a);

    frame.setVisible(true); // calling setVisible after content pane has been set to refresh a frame

    a.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JComponent b = new JLabel("label B");
            frame.setContentPane(b);
            frame.revalidate();
        }
    });
}
Jaroslaw Pawlak
  • 5,538
  • 7
  • 30
  • 57