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?
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?
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
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.