我仍然有空白JOptionPane
的问题。基于SO和 Java Docs 的研究,这显然与不使用EDT
有关。我的问题是EDT
及其方法究竟如何适用于JOptionPane
?例如,终端错误输出清楚地表明下面的JOptionPane
未在EDT
上运行。具体缺少什么,以及Runnable
之类的内容如何适用?
import javax.swing.*;
public class PaneDemo
{
public static void main(String[] args)
{
final String[] TEXT ={
//message
"Hello, World!",
//title
"Greeting"};//end TEXT
showMyPane(TEXT);
}//end main
public static void showMyPane(final String[] TEXT)
{
JOptionPane.showMessageDialog(null, TEXT[0], TEXT[1],
JOptionPane.INFORMATION_MESSAGE);
if(!SwingUtilities.isEventDispatchThread())
{
System.err.println("Err: GUI failed to use EDT.");
}//end if(!SwingUtilities.isEventDispatchThread())
}//end showMyPane
}//end class PaneDemo
答案建议添加invokeLater
。然而,这似乎并没有在BlueJ中表现得很好。
isEventDispatchThread()仍然在终端中返回错误。这仅仅是因为它现在位于错误的位置吗?
答案 0 :(得分:10)
您可以在Event Dispatch Thread上创建JOptionPane
,如下所示:
final String[] TEXT = {
//message
"Hello, World!",
//title
"Greeting"};//end TEXT
...
/**
* Create GUI and components on Event-Dispatch-Thread
*/
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, TEXT[0]
+ "\n is on EDT: " + SwingUtilities.isEventDispatchThread(), TEXT[1],
JOptionPane.INFORMATION_MESSAGE);
}
});
看看Lesson: Concurrency in Swing 它应该有助于您了解它的全部内容
更新:
根据评论,您应该使用JOptionPane
方法在EDT
方法的showPane(...)
上发起 public static void showMyPane(final String[] TEXT) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, TEXT[0]
+ "\n is on EDT: " + SwingUtilities.isEventDispatchThread(), TEXT[1],
JOptionPane.INFORMATION_MESSAGE);
}
});
}//end showMyPane
public static void main(String[] args) {
final String[] TEXT = {
//message
"Hello, World!",
//title
"Greeting"};//end TEXT
showMyPane(TEXT);
}
,如下所示:
{{1}}