title: How can I change the JPanel from another Class?
body: <p><strong>Hi, I'm new to Java and I have the following problem:</strong></p>
  
  <p>I created a JFrame and I want the JPanel to change when clicking a JButton. That does almost work.The only problem is that the program creates a new window and then there are two windows. One with the first JPanel and one with the second JPanel.
  Here is my current code:</p>
  
  <p><strong>first class:</strong></p>
  
  <pre><code>public class Program {
  
      public static void main (String [] args) {
  
          new window(new panel1());
  
      }
  }
  </code></pre>
  
  <p><strong>second class:</strong></p>
  
  <pre><code>import java.awt.Toolkit;
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  
  public class Window extends JFrame {
  
      private static final long serialVersionUID = 1L;
  
      Window(JPanel panel) {
  
          setLocation((int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2 - 200,
                      (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2 - 100);
          setSize(400, 200);
          setTitle("test");
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setResizable(false);
          setContentPane(panel);
          setVisible(true);
  
      }
  }
  </code></pre>
  
  <p><strong>third class:</strong></p>
  
  <pre><code>import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import javax.swing.JButton;
  import javax.swing.JPanel;
  
  public class Panel1 extends JPanel {
  
      private final long serialVersionUID = 1L;
  
      Panel1() {
  
          JButton nextPanelButton = new JButton("click here");
  
          add(nextPanelButton);
  
          ActionListener changePanel = new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent event) {
                  new window(new panel2());
              }
          };
          nextPanelButton.addActionListener(changePanel);
  
      }
  }
  </code></pre>
  
  <p><strong>fourth class:</strong></p>
  
  <pre><code>public class Panel2 extends JPanel {
  
      private static final long serialVersionUID = 1L;
  
      Panel2() {
  
          JLabel text = new JLabel("You pressed the Button!");
  
          add(text);
  
      }
  }
  </code></pre>
  
  <p><strong>But I just want to change the JPanel without opening a new window. Is there a way to do that?</strong></p>
  
  <p>Thanks in advance!</p>