2

I have a dialog containing several buttons. When a particular button is clicked, it's ActionListener iniates a process that takes several seconds to complete. During this time I want to provide some feedback to the user. To take a simple approach, I have a label in the dialog "Computing..." which is initially not visible. A code segment looks like this

button_OpenHoursReport.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        lbl_Computing.setVisible(true);
        new runAndRenderReport();
        RunAndRenderReport.main(null);
        lbl_Computing.setVisible(false);
    }
});

The problem is, the lbl_Computing text does not become visible until the RunAndRenderReport is completed. Obviously, that's not much help to the user. Don't know where to go from here. Does this have to do with threads? If so, I could use some guidance on how to get started.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Paul
  • 117
  • 1
  • 1
  • 9

2 Answers2

5

actionPerformed() is executed on the GUI-thread (EDT), so avoid executing intensive operations on it. Instead use SwingWorker.

See How SwingWorker works.

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

A trick which is much easier than using SwingWorker is to call paintImmediately on your label after calling setVisible(true). You should see the effects - immediately.

lbl_Computing.paintImmediately(0, 0, lbl_Computing.getWidth(), lbl_Computing.getHeight());

But SwingWorker is the way to go if you want your GUI to be responsive in other ways as well while the reporting is running.

lbalazscs
  • 17,474
  • 7
  • 42
  • 50
  • Thanks. I'll take the paintImmediately approach for now since my GUI can wait a few seconds for the process to complete. I'll look into SwingWorker in the future when I need the GUI to be responsive. – Paul Feb 28 '13 at 19:33
  • For a short, deterministic lag also consider setting `WAIT_CURSOR`. – trashgod Feb 28 '13 at 21:57