system.out.println必须是edt吗?

时间:2012-06-28 20:28:37

标签: java swing event-dispatch-thread println swingutilities

我正在运行一些在swingworker中打印输出的代码。我没有得到打印输出所以我使用了SwingUtilities.invokeLater,现在它可以工作了。我没想到这个结果,这是怎么发生的?我原以为System.out.println可以在EDT之外运行。

4 个答案:

答案 0 :(得分:2)

这可能很容易测试(更不用说,即使输入所有代码来测试这个,也不会在此处发布):

import java.awt.EventQueue;
public class HelloWorld {
  public static void main( String[] args ) {
    System.out.println("Hello world");
    System.out.println( EventQueue.isDispatchThread());
  }
}

结果

Hello world
false

在控制台上。

是的,System.out.println可以在EDT之外使用

答案 1 :(得分:1)

  

我想thinkystem.out.println可以在edt之外运行。

这是事实。要对此进行测试,请创建一个放置循环和打印输出的线程,并亲自查看:)

答案 2 :(得分:0)

System.out.println确实在edt之外运行。当你使用swingworker运行它时,你让它在里面运行。从理论上讲,您应该始终能够直接从代码块中打印结果。 我建议:

Runnable runnable = new Runnable() {

        public void run() {

        }
    };
SwingUtilities.invokeLater(runnable);

答案 3 :(得分:0)

尽管可以,但它在调试之外的应用程序很少。

备用输出的示例是JOptionPane:

JOptionPane.showMessageDialog(frame/* sets up the message, can also be replaced with null to remove formatting*/,
"Eggs are not supposed to be green."/* this is your main message*/,
"A plain message"/* this is what shows in the title spot (first parameter must not be null)*/,
JOptionPane.PLAIN_MESSAGE/*shows no icon, also replacable with WARNING_MESSAGE, ERROR_MESSAGE, INFORMATION_MESSAGE*/);

所有这一切都在一行,但我把它分解为格式化 一行版本:

JOptionPane.showMessageDialog(frame/* sets up the message, can also be replaced with null to remove formatting*/, "Eggs are not supposed to be green."/* this is your main message*/, "A plain message"/* this is what shows in the title spot (first parameter must not be null)*/, JOptionPane.PLAIN_MESSAGE/*shows no icon, also replacable with WARNING_MESSAGE, ERROR_MESSAGE, INFORMATION_MESSAGE*/);

没有评论:

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "A plain message", JOptionPane.PLAIN_MESSAGE);

在你的课程中,将Seuss博士引用你的老师很有趣。