Java 中 SwingUtilities 類的重要性是什麼?


在 Java 中,Swing 元件顯示在螢幕上後,只能由一個名為**事件處理執行緒**的執行緒操作。我們可以在單獨的程式碼塊中編寫程式碼,並將此程式碼塊的引用傳遞給**事件處理執行緒**。**SwingUtilities** 類有兩個重要的靜態方法,**invokeAndWait()** 和 **invokeLater()**,用於將程式碼塊的引用放入**事件佇列**。

語法

public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException
public static void invokeLater(Runnable doRun)

引數 **doRun** 是 **Runnable** 介面例項的引用。在這種情況下,**Runnable** 介面不會傳遞給 Thread 的建構函式。**Runnable** 介面只是被用作標識事件執行緒入口點的一種方式。就像新生成的執行緒將呼叫 **run()** 一樣,事件執行緒將在處理完佇列中所有其他待處理事件後呼叫 **run()** 方法。如果在目標引用的程式碼塊完成之前中斷呼叫 **invokeAndWait()** 或 **invokeLater()** 的執行緒,則會丟擲 **InterruptedException**。如果 **run()** 方法內部丟擲未捕獲的異常,則會丟擲 **InvocationTargetException**。

示例

import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
public class SwingUtilitiesTest {
   public static void main(String[] args) {
      final JButton button = new JButton("Not Changed");
      JPanel panel = new JPanel();
      panel.add(button);
      JFrame f = new JFrame("InvokeAndWaitMain");
      f.setContentPane(panel);
      f.setSize(300, 100);
      f.setVisible(true);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      System.out.println(Thread.currentThread().getName()+" is going into sleep for 3 seconds");
      try {
         Thread.sleep(3000);
      } catch(Exception e){ }
      //Preparing code for label change
      Runnable r = new Runnable() {
         @Override
         public void run() {
            System.out.println(Thread.currentThread().getName()+"is going into sleep for 10 seconds");
            try {
               Thread.sleep(10000);
            } catch(Exception e){ }
          button.setText("Button Text Changed by "+ Thread.currentThread().getName());
          System.out.println("Button changes ended");
      }
    };
      System.out.println("Component changes put on the event thread by main thread");
          try {
            SwingUtilities.invokeAndWait(r);
         } catch (InvocationTargetException | InterruptedException e) {
            e.printStackTrace();
         }
      System.out.println("Main thread reached end");
   }
}

輸出

                                                         


更新於:2020年2月7日

1K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告