0

So I am trying to code a typical clock software where you have a stopwatch, clock, alarms, etc. And now I am stuck because my Jlabel does not update. My Thread is working and I already tried it with a System.out.println(); command but it does not work with my JLabel. (Sorry for my bad english)

SwingUtilities.invokeLater(new Runnable() {
        public void run() {
    
        int fullmin = 60;
         
        while(stopwatchtimemil != fullmin){
            
           try {
            thread.sleep(10);
        
                stopwatchtimemil++;
                stopwatchUI.setText(stopwatchtimemin + " : " + stopwatchtimesec + " : " + stopwatchtimemil);
                
            
            } catch (InterruptedException e) {
            
                e.printStackTrace();
            }

            if(stopwatchtimemil==fullmin){
                
                stopwatchtimemil=0;
                stopwatchtimesec++;
                
            }
            if(stopwatchtimesec == fullmin){

                stopwatchtimesec =0;
                stopwatchtimemin++;
                
            }
        }
    }
    });
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • You are not using a background thread but rather are queuing a Runnable onto the Swing event thread by passing it into `SwingUtilities.invokeLater(...)`. You're then calling `Thread.sleep` ***on*** this same event thread, putting your whole GUI to sleep. Don't do this, and I suggest that you not even use a background thread directly, but instead use a [Swing Timer](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html). – Hovercraft Full Of Eels Dec 20 '21 at 20:57
  • I did not use the Timer on purpose because I wanted to practice – CodingAdrian Dec 20 '21 at 21:02
  • But *again* you're not creating a new thread. This, `SwingUtilities.invokeLater(new Runnable() {...});` is *not* creating a new background thread but instead is forcing the code to be called on the GUI's event thread. This, `new Thread(new Runnable).start();` *would* create a background thread, but then your code wouldn't be Swing thread-safe. Use the Swing Timer for thread safety. – Hovercraft Full Of Eels Dec 20 '21 at 21:03
  • If you really *must* use a background thread, then either use a SwingWorker, carefully and correctly, or use a `new Thread(...)`, and inside the Runnable, be sure to queue any Swing calls onto the event thread using `SwingUtilities.invokeLater(...)` – Hovercraft Full Of Eels Dec 20 '21 at 21:04

0 Answers0