如何在JFrame中添加时间延迟? [英] How to add a time delay in JFrame?

查看:112
本文介绍了如何在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 only JComponent (JTextComponent) and only in the case that on second side are some changes

      200milisecond时间很短,您不能在短时间内写短信,我将设置为750milis - one second

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

      使用util.Timer或从Runnable#Thread开始

      使用布尔局部变量代替while(true)(例如while(canRun)),然后有可能在需要时停止和启动循环

      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

      util.Timer/Runnable#ThreadSwing GUI的所有输出必须包装到invokeLater中,只有具有真实变化的方法,来自Swing APIs的方法,例如setText()append()不是整个方法,void负责创建输出,连接等.

      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.

      不要使用SwingWorker,它不是用于无限循环的正确API,只能运行一次

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

      ,那么可能有一些SwingWorkers实例(从任何TimerExecutor调用)的并发性,因为没有人能够保证每个结束并且都没有(几个实例)同时,最好的选择是从Runnable#Thread

      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

      这篇关于如何在JFrame中添加时间延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆