How to add a time delay in JFrame?

喜夏-厌秋 提交于 2019-12-08 07:28:49

问题


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?


回答1:


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?

  • disagree, JFrame can't be refreshed only JComponent (JTextComponent) and only in the case that on second side are some changes

  • 200milisecond is very short time, you can't wrote text message on this short period, I'd be to set 750milis - one second

  • use util.Timer or to start endless loop from Runnable#Thread,

  • use boolean local variable instead of while(true), e.g while(canRun), then is possible the loop to stop and start if would be need

  • all output to the Swing GUI from util.Timer / Runnable#Thread must be wrapped into invokeLater, only methods with real changes, methods from Swing APIs e.g. setText(), append() not whole method, void which is responsible to create an output, connection, etc.

  • don't to use SwingWorker, isn't proper API for endless loop, is designated to runs only once time,

  • then there is possible concurency with a few instances of SwingWorkers(invoked from any Timer or Executor), 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 from Runnable#Thread




回答2:


You can give a try to timer class as well

Timer timer = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Some code here

}
});
timer.start();

for more details see How to Use Swing Timers

Hope this will help you.



来源:https://stackoverflow.com/questions/17042458/how-to-add-a-time-delay-in-jframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!