Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - repaint component every second?

Tags:

java

I would like to repaint component after each second, but it didn't work. What I am trying is:

    try{
        while(true){
            Thread.currentThread().sleep(1000);
            gc.cb.next();
            gc.repaint();
        }
    }
    catch(Exception ie){
    }
like image 351
Nick Smith Avatar asked Apr 13 '26 09:04

Nick Smith


1 Answers

I would advise using a javax.swing.Timer for this problem, which will periodically fire an ActionEvent on the Event Dispatch thread (note that you should only call repaint and / or manipulate Swing components from this thread). You can then define an ActionListener to intercept the event and repaint your component at this point.

Example

JComponent myComponent = ...
int delay = 1000; //milliseconds

ActionListener taskPerformer = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    myComponent.repaint();
  }
};

new Timer(delay, taskPerformer).start();

Also note that SwingWorker is probably inappropriate as it is typically used for background tasks that have a defined start and end, rather than a periodic task.

like image 50
Adamski Avatar answered Apr 15 '26 00:04

Adamski