Java में, स्विंग कंपोनेंट्स स्क्रीन पर प्रदर्शित होने के बाद, केवल एक थ्रेड द्वारा संचालित किए जा सकते हैं जिसे इवेंट हैंडलिंग थ्रेड कहा जाता है। हम अपना कोड एक अलग ब्लॉक में लिख सकते हैं और इस ब्लॉक का रेफरेंस इवेंट हैंडलिंग थ्रेड को दे सकते हैं। SwingUtilities क्लास में दो महत्वपूर्ण स्टेटिक मेथड्स हैं: invokeAndWait() और invokeLater(), जिनका उपयोग कोड ब्लॉक्स के रेफरेंस को इवेंट क्यू पर रखने के लिए किया जाता है।
सिंटैक्स
public static void invokeAndWait(Runnable doRun) throws InterruptedException, InvocationTargetException public static void invokeLater(Runnable doRun)
पैरामीटर doRun Runnable इंटरफेस के एक इंस्टेंस का रेफरेंस है। इस केस में, Runnable इंटरफेस को थ्रेड के कंस्ट्रक्टर में पास नहीं किया जाता। 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){ }
// लेबल बदलने के लिए कोड तैयार करना
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");
}
}
आउटपुट
प्रोग्राम चलाने पर, मेन थ्रेड 3 सेकंड सोता है, फिर SwingUtilities.invokeAndWait() के माध्यम से इवेंट डिस्पैच थ्रेड पर बटन का टेक्स्ट बदलता है। बटन का टेक्स्ट "Not Changed" से "Button Text Changed by AWT-EventQueue-0" में बदल जाता है।