无法在 JFrame 上绘制

unable to draw on JFrame

我想在 JFrame

上画点东西
public class Frame extends JFrame{
    public static final int US=0;
    public static final int GERMANY=1;
    public Frame() {
        super("Frame");
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setContentPane(new JPanel());
        this.setSize(800, 600);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    public void draw() {
        this.removeAll();
        int count;
        JPanel Panel = new JPanel();
        GridLayout layout=new GridLayout(0, 1);
        Panel.setLayout(layout);
        JLabel label2 = new JLabel("Text-Only Label");
        Panel.add(label2);
        this.getContentPane().add(Panel);
        this.validate();
        this.repaint();
    }

}

当我尝试从另一个 class 调用 draw() 时,JFrame 没有更新。

它仍然是构造函数中看到的空白屏幕。

如有任何帮助,我们将不胜感激。

您应该在 contentPane 上调用 removeAll,而不是在框架上。

this.getContentPane().removeAll();

而不是

this.removeAll();

试试这个:

public void draw() {
            this.getContentPane().removeAll();
            int count;
            JPanel Panel = new JPanel();
            GridLayout layout=new GridLayout(0, 1);
            Panel.setLayout(layout);
            JLabel label2 = new JLabel("Text-Only Label");
            Panel.add(label2);
            this.getContentPane().add(Panel);
            this.validate();
            this.repaint();
        }