Java - repaint component every second?

前端 未结 2 1961
误落风尘
误落风尘 2021-01-20 02:51

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

    try{
        while(true){
            Thread.currentThread         


        
相关标签:
2条回答
  • 2021-01-20 03:09

    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.

    0 讨论(0)
  • 2021-01-20 03:15

    Make sure you're not hogging the UI-thread for this. If you're executing this loop in the UI-thread, then the repaint event will never be dispatched.

    Another note; sleep is a static method, and should be invoked as Thread.sleep(...). (There is no way of doing thatThread.sleep(...) anyway.)

    The "correct" way of doing this is probably to use a SwingWorker. Have a look at the tutorial.

    If you provide more code, we can provide better answers.

    0 讨论(0)
提交回复
热议问题