Why does my application freeze when displaying a JOptionPane on top of a JFrame?
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();
}
JOptionPa开发者_JS百科ne.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?
private void ShowMessage(String message) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, message);
}
});
}
Try to pass the frame instead of null there
JOptionPane.showMessageDialog(null, "oops!");
And don't mix awt and swing (JFrame and Canvas) together
That's because you have passed true to setAlwaysOnTop of the JFrame.Try passing false.
setAlwaysOnTop(false);
精彩评论