I'm still having problems with blank JOptionPane
s. Based on research at SO and in Java Docs, this obviously has something to do with not using the EDT
. My question is how exactly do the EDT
and its methods apply to JOptionPane
? For example, the terminal error output makes it quite clear that the JOptionPane
below is not run on the EDT
. What's missing specifically, and how does something like Runnable
fit in?
import javax.swing.*;
public class PaneDemo
{
public static void main(String[] args)
{
final String[] TEXT ={
//message
"Hello, World!",
//title
"Greeting"};//end TEXT
showMyPane(TEXT);
}//end main
public static void showMyPane(final String[] TEXT)
{
JOptionPane.showMessageDialog(null, TEXT[0], TEXT[1],
JOptionPane.INFORMATION_MESSAGE);
if(!SwingUtilities.isEventDispatchThread())
{
System.err.println("Err: GUI failed to use EDT.");
}//end if(!SwingUtilities.isEventDispatchThread())
}//end showMyPane
}//end class PaneDemo
An answer suggested adding invokeLater
. That doesn't seem to render very well in BlueJ, however.
Also isEventDispatchThread() is still returning the error in the terminal. Is that simply because it is now in the wrong location?
You can create JOptionPane
on the Event Dispatch Thread like this:
final String[] TEXT = {
//message
"Hello, World!",
//title
"Greeting"};//end TEXT
...
/**
* Create GUI and components on Event-Dispatch-Thread
*/
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, TEXT[0]
+ "\n is on EDT: " + SwingUtilities.isEventDispatchThread(), TEXT[1],
JOptionPane.INFORMATION_MESSAGE);
}
});
Have a look at the Lesson: Concurrency in Swing it should help you understand what its all about
UPDATE:
as per comment you should initiate the JOptionPane
on the EDT
on each call in showPane(...)
method like so:
public static void showMyPane(final String[] TEXT) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, TEXT[0]
+ "\n is on EDT: " + SwingUtilities.isEventDispatchThread(), TEXT[1],
JOptionPane.INFORMATION_MESSAGE);
}
});
}//end showMyPane
public static void main(String[] args) {
final String[] TEXT = {
//message
"Hello, World!",
//title
"Greeting"};//end TEXT
showMyPane(TEXT);
}