如何从线程更改Java标签?

时间:2018-09-16 11:27:27

标签: java multithreading label

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();
      }
}

我想更新jframe标签值(变量值)。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果从“ EventDispatchingThread”以外的其他线程更新Swing UI组件,请务必确保采用以下方式:

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

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