JPanel 在启动程序后有时会移动到左上角

JPanel is sometimes moved to the top left after starting the program

在我的程序中,我使用 JFrame 并通过 setContentPane() 将其内容窗格设置为 JPanel。有时 JPanel 会向左上角移动大约 10 到 15 个像素,因此右侧和底部是白色区域。

我测试了面板的位置、大小和插图,但它们都是一样的,没有问题。

public class Window extends JFrame {

    private static final long serialVersionUID = 1L;

    private DrawPanel dp;

    public Window(int width, int height, String title) {
        dp = new DrawPanel(); // constructor only calls setFocusable(true);

        setResizable(false);
        setSize(width, height);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle(title);
        setLocationRelativeTo(null);
        setContentPane(dp);
        setVisible(true);

        dp.init(); // only initializes a BufferedImage
    }

    public DrawPanel getDrawPanel() {
        return dp;
    }

}

上图是应该的样子,下图是问题所在:

希望您能理解我的问题并能帮助我。谢谢

好的,感谢 camickr 的评论,我设法解决了我的问题。我在SwingUtilities中使用了invokeAndWait方法。现在 Event Dispatch Thread 上的 JFrame 和 JPanel 运行,问题不再出现。

SwingUtilities.invokeAndWait(new Runnable() {
    @Override
    public void run() {
        dp = new DrawPanel();

        setResizable(false);
        setSize(width, height);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle(title);
        setLocationRelativeTo(null);
        setContentPane(dp);
        setVisible(true);

        dp.init();
    }
});

谢谢camickr