How can I change the JPanel from another Class?

Hi, I’m new to Java and I have the following problem:

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:

first class:

public class program {

    public static void main (String [] args) {

        new window(new panel1());


second class:

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


third class:

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


        ActionListener changePanel = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                new window(new panel2());


fourth class:

public class panel2 extends JPanel {

    private static final long serialVersionUID = 1L;

    panel2() {

        JLabel text = new JLabel("You pressed the Button!");



But I just want to change the JPanel without opening a new window. Is there a way to do that?

Thanks in advance!