Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào chúng ta có thể gọi phương thức invokeLater () trong Java?


An invokeLater () phương thức là một tĩnh phương pháp của SwingUtilities và nó có thể được sử dụng để thực hiện một tác vụ không đồng bộ trong AWT Chuỗi người điều phối sự kiện . SwingUtilities.invokeLater () phương thức hoạt động như SwingUtilities.invokeAndWait () ngoại trừ việc nó đưa yêu cầu vào hàng đợi sự kiện trả lại ngay lập tức . Một invokeLater () phương thức không đợi khối mã bên trong Runnable được giới thiệu bởi một mục tiêu để thực thi.

Cú pháp

public static void invokeLater(Runnable target)

Ví dụ

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InvokeLaterTest extends Object {
   private static void print(String msg) {
      String name = Thread.currentThread().getName();
      System.out.println(name + ": " + msg);
   }
   public static void main(String[] args) {
      final JLabel label= new JLabel("Initial text");
      JPanel panel = new JPanel(new FlowLayout());
      panel.add(label);
      JFrame f = new JFrame("InvokeLater Test");
      f.setContentPane(panel);
      f.setSize(400, 300);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
      try {
         print("sleeping for 5 seconds");
         Thread.sleep(5000);
      } catch(InterruptedException ie) {
         print("interrupted while sleeping");
      }
      print("creating the code block for an event thread");
      Runnable setTextRun = new Runnable() {
         public void run() {
            try {
               Thread.sleep(100);
               print("about to do setText()");
               label.setText("New text");
            } catch(Exception e) {
               e.printStackTrace();
            }
         }
      };
      print("about to call invokeLater()");
      SwingUtilities.invokeLater(setTextRun);
      print("back from invokeLater()");
   }
}

Đầu ra

Làm thế nào chúng ta có thể gọi phương thức invokeLater () trong Java?


main: sleeping for 5 seconds
main: creating the code block for an event thread 
main: about to call invokeLater() 
main: back from invokeLater() 
AWT-EventQueue-0: about to do setText()


Làm thế nào chúng ta có thể gọi phương thức invokeLater () trong Java?