Kal100
Kal100

Reputation: 1

How do I change the Java label from a thread?

class firstThread implements Runnable {

      public Thread t;

      @Override
      public void run() { 
        for (int x = 1; true; x++) { 
          System.out.print(x + " "); 
          NewJFrame.a = x;
          try {
            Thread.sleep(1000);
          } catch (InterruptedException ex) {
            Logger.getLogger(firstThread.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
      }

      public void start() {
        t = new Thread(this, "first");
        t.start();
      }
}

I want to update jframe label value (a variable value).

How can I do that?

Upvotes: 0

Views: 121

Answers (1)

Tommy Brettschneider
Tommy Brettschneider

Reputation: 1500

if you update Swing UI components from a thread other than the "EventDispatchingThread" always make sure to do it this way:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        label.setText("new_label_text");
    }
});

https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html

Upvotes: 1

Related Questions