Waiting for frame creation

2019-08-15 02:22发布

问题:

i have problem in java and I do not know him and I resolved. I created a simple program that inserts into the text JPanel using for and sleep function.

Like this(This is an example):

public class example{
  JFrame frame....
  ..
  ..
   public example(){
      //ini frame and label.. then..
      String s = "abcqweewqewqewqewqweqwqeweqweqwq";

      //DO ANIMATION
      try
         {
         for(int i = 0;i<s.length();i++)
         {
         JLABEL.append(String.valueOf(s.charAt(i)));
           Thread.sleep(10);
         }
      }catch(Exception ex){}
   }
  public static void main.......{
     new example();
  }
}

It works perfectly (writes characters after a certain time interval) But, if i call this main using other class-So waiting until everything renders and then the window appears (so does not animation).

Where is a problem? I hope, you understand me.

回答1:

Swing is single threaded, and properly written swing code runs in the event dispatch thread. Your sample breaks the threading rule by creating the GUI outside the EDT, and also runs the loop in the main thread. Normally, when created correctly in the EDT, or as a response to an event from a button click or similar, the loop blocks the event dispatch thread so that no drawing can happen until the loop has completed.

You get that behaviour if you initialize the GUI in the event dispatch thread:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new example()
        }
    });
}

The proper way, instead of sleeping in the EDT, is using a Swing Timer.

To sum the above: your code appears to work only because it has the bug that it runs some of the UI code outside the event dispatch thread.