我正在 JFrame
中构建聊天室。
我希望 JFrame
每 200ms 刷新一次,这样每当输入新文本时,它就会出现在 JFrame
中。
我尝试使用 while(true)
但 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.
I tried using while(true) but JFrame freezes.
How to add timer to the code?
不同意,
JFrame
不能只刷新JComponent
(JTextComponent
),只有在第二面是一些变化200milisecond
时间很短,这么短的时间不能写短信,我会设置750milis - 一秒
使用
util.Timer
或从Runnable#Thread
开始无限循环,使用 boolean 局部变量而不是
while(true)
,例如while(canRun)
,这样循环就可以在需要时停止和启动util.Timer
/Runnable#Thread
到Swing GUI
的所有输出都必须包装到invokeLater
,仅具有实际更改的方法,来自Swing API
的方法,例如setText()
、append()
不是整个方法,void 负责创建输出、连接等。不要使用
SwingWorker
,它不是适合无限循环的 API,被指定只运行一次,然后可能会与
SwingWorkers
的几个实例并发(从任何Timer
或Executor
调用),因为没有人可以为了保证每个结束的和不结束的(少数情况)同时存在,那么最好的选择是从Runnable#Thread
调用循环
关于java - 如何在 JFrame 中添加时间延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17042458/