Search code examples
javaswingswingworker

Updating buttons inside or outside of SwingWorker?


I want to disable a number of buttons/menu items of my GUI while a SwingWorker thread is running. The thread is started when a button is clicked.

It looks like the while loop in my code causes the CPU load to go up significantly. Did I get something wrong about how to determine if a SwingWorker thread is still running?

The CPU load's definitely lower when I update the buttons/menu items inside the SwingWorker thread. However, I felt like that shouldn't be the SwingWorker thread's job. Should it?

JButton button = new JButton("Start");
button.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent evt) {
    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        menu.setEnabled(false);

        MySwingWorker worker = new MySwingWorker();
        worker.execute();

        while (true) {
          if (worker.isCancelled() || worker.isDone()) {
            menu.setEnabled(true);
            break;
          }
        }
      }
    });
    t.start();
  }
});

Solution

  • Swing GUI objects should be constructed and manipulated only on the event dispatch thread (EDT). Doing so from t is incorrect. As suggested in examples cited here, condition your GIU elements on the EDT before starting the worker, and update the GUI in process() or done().