为什么我的应用程序在JFrame上显示JOptionPane时会冻结?

Bar*_*vbl 2 java swing

我在JFrame窗口中编写了一个应用程序,如果需要,可能会弹出一条错误消息.但是,当我调用"JOptionPane.showMessageDialog()"时,应用程序冻结,停止它的唯一方法是使用任务管理器.这是我的代码的精简版:

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.JFrame;

public class GameMain {
    public JFrame jframe;
    public Canvas canvas;

    private AtomicReference<Dimension> canvasSize = new AtomicReference<Dimension>();

    public void initialize(int width, int height) {
    try {
        Canvas canvas = new Canvas();
        JFrame frame = new JFrame("testapp");
        this.canvas = canvas;
        this.jframe = frame;
        ComponentAdapter adapter = new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                resize();
            }
        };

        canvas.addComponentListener(adapter);
        canvas.setIgnoreRepaint(true);
        frame.setSize(640, 480);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(canvas);
        frame.setVisible(true);
        Dimension dim = this.canvas.getSize();
        } catch (LWJGLException le) {
            le.printStackTrace();
        }

        JOptionPane.showMessageDialog(null, "oops!");
    }
    public void resize()
    {
        Dimension dim = this.canvas.getSize();
        canvasSize.set(dim);
        dim = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

有谁知道它为什么这样做?

小智 8

private void ShowMessage(String message) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JOptionPane.showMessageDialog(null, message);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)