Ok I've read an searched all over the web, and I've not found the solution to my problem yet, perhaps I'm missing something simple, hence here I am...
I've got a rather large project, that handles work orders for a repair business. It's all database connected, many many pages of code, and classes. But i just added a short bit of code to the front end that essentially checks for new messages in our notes area.
Anyway, I display a simple JFrame with two JLabels while a separate thread queries the database. This all happens at the start of the program. The problem is my little "please wait" JFrame comes up with its frame but no guts, no background, and no JLabels, during the wait (which is the rest of the program loading, not the database thread), afterwords it displays, but by then its missing its point.
I wrote the following example program. It displays a simple JFrame (CheckingMessagesGUI: a JFrame with two JLabels, nothing more) sleeps for 5 sec then displays the Example (main program) JFrame, then instantly closes (System.exit(0)
) in this example, of course my real program goes on to do a lot more. What I found is that invokeLater
seems to be causing the problem. Once the sleep timer runs out the window will display, but the code to display it was given before the Thread.sleep
command, and should have been done in that order correct?
My question is why does invokeLater
cause my JFrame not to display correctly?
Its my understanding that the purpose of invokeLater
is so that the items run on the correct AWT event thread, which would make me think that this window would get painted correctly. Anyway I'm sure I'm missing something obvious. I commented out the invokeLater
part in the code below, and it runs correctly, if you put it back it doesn't...
Many thanks in advance.
package javaapplication6;
public class Example extends javax.swing.JFrame {
public Example() {
System.out.println("Example started");
setBounds(100,100,200,200);
System.out.println("cmGUI instantiated");
CheckingMessagesGUI cmGUI = new CheckingMessagesGUI();
System.out.println("Set cmGUI visible");
cmGUI.setVisible(true);
cmGUI.validate();
try {
System.out.println("timer started");
Thread.sleep(5000);
System.out.println("timer done");
} catch(InterruptedException e){
}
System.exit(0);
}
public static void main(String[] args) {
/*java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() { */
System.out.println("Started");
System.out.println("example Instantiated");
Example example = new Example();
System.out.println("example visible");
example.setVisible(true);
/* }
});
*/
}
}
UPDATE:
To clarify, I realize Thread.sleep()
will block everything, but shouldn't my CheckingMessagesGUI already have been fully drawn before I call sleep? That is the issue.