How to update JFrame Label within a Thread? - Java

后端 未结 5 1486
南笙
南笙 2021-01-19 02:20

I have tried a lot, but can\'t seem to get it to work.

I was told to use EDT with the following example.

    SwingUtilities.invokeLater(new Runnable(         


        
5条回答
  •  心在旅途
    2021-01-19 03:05

    If you're all looking to do is update the UI on a known schedule, try something like the following. This assumes that a JFrame is the component you wish to update every 1 second.

    private static final int WAIT_LENGTH = 1000; // 1 second
    private JFrame frame = new JFrame();
    
    // Thread will update the UI (via updateUI() call) about every 1 second
    class UIUpdater extends Thread {
      @Override
      void run() {
        while (true) {
          try {
            // Update variables here
          }
          catch (Exception e) {
            System.out.println("Error: " + e);
          }
          finally {
            frame.repaint();
            Thread.sleep(WAIT_LENGTH);
          }
        }
      }
    }
    

    To start this thread:

    UIUpdater t = new UIUpdater();
    t.start();
    

提交回复
热议问题