1

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();
  }
});
not_a_number
  • 305
  • 1
  • 6
  • 18

1 Answers1

1

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().

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • One more question: Would it be allowed to dynamically create a JOptionPane from the button's ActionListener ("Congratulations, you clicked a button")? Having a worker for that seems a bit oversized for that purpose. – not_a_number Apr 14 '14 at 11:16
  • Unless you intentionally do otherwise, the button's listener will be invoked on the EDT. Note, for [example](http://stackoverflow.com/a/18728637/230513), that the EDT will continue to process events posted from `process()`, even if a modal dialog blocks user interaction with other windows. – trashgod Apr 14 '14 at 13:11