Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความสำคัญของคลาส SwingUtilities ใน Java

ใน Java หลังจากที่คอมโพเนนต์ Swing แสดงบนหน้าจอแล้ว จะสามารถทำงานได้เพียงเธรดเดียว คือ Event Dispatch Thread (EDT) เราสามารถเขียนโค้ดในบล็อกแยกต่างหากและส่งอ้างอิงบล็อกนั้นให้ EDT ประมวลผล คลาส SwingUtilities มีเมธอดสแตติกสำคัญ 2 ตัวคือ invokeAndWait() และ invokeLater() ใช้เพื่อวางอ้างอิงของบล็อกโค้ดลงใน คิวเหตุการณ์ (event queue)

ไวยากรณ์

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

พารามิเตอร์ doRun เป็นอ้างอิงไปยังอินสแตนซ์ของอินเทอร์เฟซ Runnable ในกรณีนี้ Runnable จะไม่ถูกส่งให้คอนสตรัคเตอร์ของ Thread แต่ใช้เพื่อระบุจุดเริ่มต้นสำหรับเธรดเหตุการณ์ คล้ายกับเธรดที่เพิ่งสร้างจะเรียก run() เธรดเหตุการณ์จะเรียก run() เมื่อประมวลผลเหตุการณ์อื่นๆ ในคิวเสร็จแล้ว

  • InterruptedException - โยนเมื่อเธรดที่เรียก invokeAndWait() หรือ invokeLater() ถูกขัดจังหวะก่อนที่บล็อกโค้ดจะเสร็จ
  • InvocationTargetException - โยนเมื่อมีข้อยกเว้นที่ไม่ได้จับในเมธอด run()

ตัวอย่างโค้ด

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){ }

        // เตรียมโค้ดสำหรับเปลี่ยนข้อความปุ่ม
        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");
    }
}

ผลลัพธ์

โปรแกรมจะแสดงการทำงานของ invokeAndWait() ซึ่งบล็อกเธรดหลักจนกว่าการอัปเดต UI จะเสร็จสิ้น แล้วจึงดำเนินการต่อ