简体   繁体   中英

Java Swing how to clear a JFrame?

Unfortunately, I have not been able to find an answer to my problem anywhere.

Here is my programme:

import javax.swing.*;
import java.awt.*;

public class TestClass {

    public static void main(String[] args) {

        JFrame window = new JFrame("Window");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1,1));

        JButton button = new JButton("Button");
        button.addActionListener(e -> windowPreparation(window));

        panel.add(button);

        window.add(panel);
        window.setSize(800, 600);
        window.setVisible(true);
    }

    private static void windowPreparation(JFrame window) {
        window.removeAll();
        window.validate();
        window.repaint();
    }
}

What I want to achieve: As soon as the button is pressed, the JFrame should be reset (I want to remove that JPanel with that Button) so that I can pass it to another class which then does other things with this JFrame. So that this class can do this without problems, I would like to clear the JFrame beforehand. I have just tried it as it is written here in my code, the problem is that it just doesn't work, as soon as I press the button the window just freezes. Does anyone know what I am doing wrong?

Do window.remove(panel); instead of window.removeAll() :

ie:

import javax.swing.*;
import java.awt.*;

public class TestClass {

    public static void main(String[] args) {

        JFrame window = new JFrame("Window");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1,1));

        JButton button = new JButton("Button");
        button.addActionListener(e -> windowPreparation(window, panel));

        panel.add(button);

        window.add(panel);
        window.setSize(800, 600);
        window.setVisible(true);
    }

    private static void windowPreparation(JFrame window, JPanel panel) {
        window.remove(panel);
        window.validate();
        window.repaint();
    }
}

I stand to be corrected on why your original solution doesn't work, but I think it's because there are "infrastructure" Component s in a JFrame which aren't related to the components you have added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM