等待框架创建 [英] Waiting for frame creation

查看:68
本文介绍了等待框架创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中遇到问题,但我不认识他,因此解决了。
我创建了一个简单的程序,使用 for 插入文本 JPanel 睡眠函数。



就像这样(这是一个示例):

 公共类示例{
JFrame frame ....
..
..
public example(){
// ini框架和标签。然后..
字符串s = abcqweewqewqewqewqweqwqeweqweqwq;

// DO动画
尝试
{
for(int i = 0; i< s.length(); i ++)
{
JLABEL.append(String.valueOf(s.charAt(i)));
Thread.sleep(10);
}
} catch(异常例外){}
}
public static void main ....... {
new example();
}
}

它可以完美工作(在一定时间间隔后写入字符)
但是,如果我使用其他类调用此main,请等到所有内容渲染完毕后再出现窗口(动画也不会)。



哪里有问题?希望您能理解我。

解决方案

Swing是单线程的,并且正确编写的swing代码在事件分配线程。您的示例通过在EDT外部创建GUI来打破线程规则,并且还在主线程中运行循环。通常,如果在EDT中正确创建了该循环,或者作为对单击按钮或类似操作所引起的事件的响应,则循环会阻塞事件分发线程,以便在循环完成之前不会进行绘制。 / p>

如果在事件分发线程中初始化GUI,则会得到该行为:

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

正确的方法不是使用EDT,而是使用摇摆计时器



总结一下:您的代码似乎仅能工作,因为它具有在事件分发线程之外运行某些UI代码的错误。


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.

解决方案

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.

这篇关于等待框架创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆