SwingUtilities.invokeLater()

烂漫一生 提交于 2019-12-24 04:32:19

问题


How do I feel the essentialness of SwingUtilities.invokeLater() in any swing application.Please give some code example.


回答1:


Whenever you need to update something inside your GUI you should do it through the AWT Event Thread.

This because AWT (and Swing on top) has its own thread that manages everything of a GUI. Without it the graphical interface couldn't handle events and similar things in an asynchronous way while your program is doing something else.

So for example if you have a long task declared in a Thread:

public void MyThread extends Thread
{
  class GUIUpdate implements Runnable
  {
    GUIUpdate(String msg)
    {
      ...
    }

    public void run()
    {
      guiElement.appendText(msg);
    }
  }

  public void run()
  {
     while (finished)
     {
        //do long calculations

        //send partial output to gui
        SwingUtilities.invokeLater(new GUIUpdate("something has changed!"));
     }
   }
 }


来源:https://stackoverflow.com/questions/3162631/swingutilities-invokelater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!