如何在JFrame中添加时间延迟? [英] How to add a time delay in JFrame?
问题描述
我正在JFrame
中建立一个聊天室.
我希望JFrame
刷新每个 200ms ,以便每当输入新文本时,该文本就会出现在JFrame
内.
I am building a chat room in JFrame
.
I want the JFrame
to refresh each 200ms so that whenever a new text is entered, it will appear inside the JFrame
.
我尝试使用while(true)
,但JFrame
冻结.
如何在代码中添加计时器?
How to add timer to the code?
推荐答案
我正在JFrame中建立一个聊天室.我希望JFrame刷新每个 200ms,以便每当输入新文本时,它就会出现在内部 JFrame.
I am building a chat room in JFrame. I want the JFrame to refresh each 200ms so that whenever a new text is entered, it will appear inside the JFrame.
我尝试使用while(true),但JFrame死机了.
I tried using while(true) but JFrame freezes.
如何在代码中添加计时器?
How to add timer to the code?
-
不同意,
JFrame
不能仅刷新JComponent
(JTextComponent
)并且仅在第二面有一些更改的情况下刷新disagree,
JFrame
can't be refreshed onlyJComponent
(JTextComponent
) and only in the case that on second side are some changes200milisecond
时间很短,您不能在短时间内写短信,我将设置为750milis - one second
200milisecond
is very short time, you can't wrote text message on this short period, I'd be to set750milis - one second
使用
util.Timer
或从Runnable#Thread
开始使用布尔局部变量代替
while(true)
(例如while(canRun)
),然后有可能在需要时停止和启动循环use boolean local variable instead of
while(true)
, e.gwhile(canRun)
, then is possible the loop to stop and start if would be need从
util.Timer
/Runnable#Thread
到Swing GUI
的所有输出必须包装到invokeLater
中,只有具有真实变化的方法,来自Swing APIs
的方法,例如setText()
,append()
不是整个方法,void负责创建输出,连接等.all output to the
Swing GUI
fromutil.Timer
/Runnable#Thread
must be wrapped intoinvokeLater
, only methods with real changes, methods fromSwing APIs
e.g.setText()
,append()
not whole method, void which is responsible to create an output, connection, etc.不要使用
SwingWorker
,它不是用于无限循环的正确API,只能运行一次don't to use
SwingWorker
, isn't proper API for endless loop, is designated to runs only once time,,那么可能有一些
SwingWorkers
实例(从任何Timer
或Executor
调用)的并发性,因为没有人能够保证每个结束并且都没有(几个实例)同时,最好的选择是从Runnable#Thread
then there is possible concurency with a few instances of
SwingWorkers
(invoked from anyTimer
orExecutor
), because nobody can to guarantee that every ended and aren't (a few instances) live in the same time, then best of choices is loop invoked fromRunnable#Thread
这篇关于如何在JFrame中添加时间延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!