我正在开发一个简单的 Swing 程序,该程序将一个标签放置在框架上, hibernate 一秒钟,然后将另一个标签放置在框架上,如下所示:
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!");
}
});
}
}
但是,我在 sleep 前看不到屏幕上的第一个标签。 sleep 时屏幕一片空白。之后,我一瞬间看到了原始标签,紧接着就看到了最终标签“嘿!这是不同的!”出现在屏幕上。为什么 JFrame 上没有出现原始标签?
最佳答案
使用 Swing Timer 代替 sleep 代码会更好、更安全,因为对 sleep 的调用有在事件线程上完成的风险,这可能会使整个 GUI 进入休眠状态 - 这不是您想要的。您还需要注意确保 GUI 实际上是在 Swing 事件线程上启动的。例如
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();
});
}
}
关于java - JLabel在 sleep 前不出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43049730/