问题
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,
JFramecan't be refreshed onlyJComponent(JTextComponent) and only in the case that on second side are some changes200milisecondis very short time, you can't wrote text message on this short period, I'd be to set750milis - one seconduse
util.Timeror to start endless loop fromRunnable#Thread,use boolean local variable instead of
while(true), e.gwhile(canRun), then is possible the loop to stop and start if would be needall output to the
Swing GUIfromutil.Timer/Runnable#Threadmust be wrapped intoinvokeLater, only methods with real changes, methods fromSwing APIse.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 anyTimerorExecutor), 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
回答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