简体   繁体   English

如何在Java中仅显示字符串几秒钟?

[英]How can I show a String for only a few seconds in Java?

I would like to show a String for only 5 secs on the center of my JFrame. 我只想在JFrame的中心显示一个String,持续5秒钟。 How can I do it? 我该怎么做?

  1. Add a JLabel to your JFrame . JLabel添加到您的JFrame
  2. Set the text of the JLabel . 设置JLabel的文本。
  3. For waiting, don't use the Event Dispatch Thread on which you are when creating the UI elements. 等待时,请勿在创建UI元素时使用您正在使用的事件调度线程。 Use a Swing Timer instead: Swing Timer 请改用Swing计时器: Swing计时器
  4. When the timer fires, set the text of the JLabel to the empty string or remove it entirely. 当计时器启动时,将JLabel的文本设置为空字符串或将其完全删除。

This is a Swing question and so the solution is to use a Swing Timer not Thread.sleep(...) . 这是一个Swing问题,因此解决方案是使用Swing计时器而不是Thread.sleep(...) If you use thread sleep, you will risk sleeping the Swing event thread, putting the entire GUI to sleep, preventing any new text from showing. 如果使用线程睡眠,则有冒险将Swing事件线程睡眠,使整个GUI进入睡眠状态,从而阻止显示任何新文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM