Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my application freeze when displaying a JOptionPane on top of a JFrame?

Tags:

java

swing

I have written an application inside a JFrame window, and would like to have an error message pop up if that is needed. However, when I call "JOptionPane.showMessageDialog()", the application freezes and the only way to stop it is by using task manager. Here is a trimmed down version of my code:

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

Does anyone know why it might be doing that?

like image 204
Bartvbl Avatar asked Dec 13 '22 14:12

Bartvbl


2 Answers

private void ShowMessage(String message) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JOptionPane.showMessageDialog(null, message);
        }
    });
}
like image 134
Azamat Avatar answered Dec 28 '22 12:12

Azamat


Try to pass the frame instead of null there

JOptionPane.showMessageDialog(null, "oops!");

And don't mix awt and swing (JFrame and Canvas) together

like image 43
StanislavL Avatar answered Dec 28 '22 11:12

StanislavL