JLabel在入睡前没有出现 [英] JLabel doesn't appear before sleep

查看:50
本文介绍了JLabel在入睡前没有出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的Swing程序,该程序将一个标签放置在框架上,休眠一秒钟,然后将另一个标签放置在框架上,如下所示:

I am working on a simple Swing program that places one label on the frame, sleeps for one second, and then places another label on the frame as follows:

import javax.swing.*;
import java.util.concurrent.*;
public class SubmitLabelManipulationTask {
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame("Hello Swing");
    final JLabel label = new JLabel("A Label");
    frame.add(label);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 100);
    frame.setVisible(true);
    TimeUnit.SECONDS.sleep(1);
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        label.setText("Hey! This is Different!");
      }
    }); 
  }
} 

但是,我无法在睡觉前在屏幕上看到第一个标签.睡眠时屏幕空白.之后,我会立即看到原始标签,然后立即看到最终标签嘿!这不一样!".在屏幕上.为什么原始标签没有出现在JFrame上?

However, I cannot see the first label on the screen before the sleep. The screen is blank while sleeping. Afterwards, I see the original label for a split second and immediately afterwards the final label of "Hey! This is Different!" is on the screen. Why doesn't the original label appear on the JFrame?

推荐答案

使用Swing计时器代替睡眠代码会更好,更安全,因为对睡眠的调用可能会在事件线程上完成,因此可以让整个GUI进入睡眠状态-而不是您想要的.您还需要注意确保GUI实际上确实在Swing事件线程上启动.例如

It is much better and safer to use a Swing Timer in place of your sleep code, since the call to sleep risks being done on the event thread and this can put the entire GUI to sleep -- not what you want. You also want to take care to make sure that your GUI does in fact start on the Swing event thread. For example

import javax.swing.*;
import java.util.concurrent.*;

public class SubmitLabelManipulationTask {
    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Hello Swing");
            final JLabel label = new JLabel("A Label", SwingConstants.CENTER);
            frame.add(label);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 100);
            frame.setVisible(true);
            Timer timer = new Timer(1000, e -> {
                label.setText("Try this instead");
            });
            timer.setRepeats(false);
            timer.start();
        });
    }
}

这篇关于JLabel在入睡前没有出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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