我正在尝试通过扩展 JDialog 类来创建自己的对话框 这是我用来启动的代码:
import javax.swing.JDialog;
public class ColorManager extends JDialog {
private static final long serialVersionUID = 1L;
public ColorManager(){
super();
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
}
}
当我尝试运行代码时,它工作正常,但出现以下异常:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, or DISPOSE_ON_CLOSE
我读到 WINDOWS_EXIT
或类似的问题存在问题,但我传递的参数应该可以完成这项工作。
更奇怪的是,当我更改我的类时,它将包含一个 JDialog 字段而不是扩展它,它似乎工作得很好。
我让一个 friend 在他的电脑上测试一下,代码没有抛出异常,他使用的是jre版本1.6.022,我使用的是1.6.022,我们都使用64位。
所以我做错了什么?或者这是 JRE 中的错误?
编辑:忘了提及,我正在使用 eclipse
Edit2:我在 Netbeans 中尝试了相同的代码,它工作正常,我的问题可能是什么?
最佳答案
您在构造函数中调用的所有方法都应该在 EDT 线程上调用。不建议在构造函数内执行此操作,但如果您坚持要确保它在 Swing (EDT) 线程上运行,例如:
import javax.swing.JDialog;
public class ColorManager extends JDialog {
private static final long serialVersionUID = 1L;
public ColorManager(){
super();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
}
});
}
}
在我看来,完成此任务的最佳方法是将其移至单独的方法中,然后在创建 ColorManager
实例后调用它。
使用 Swing 时,您应该始终遵守 Swing 线程规则。更多信息请参见
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
关于java - Swing JDialog 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5442973/