3

I have a JButton in my Java Applet. After pressing it, ActionListener have to make huge amount of actions. So, because of it, when user clicks the button, it "stay pressed" for a while (sometimes even 5 minuts) instead of disable itself immidiately (it disable itself after these 5 minuts).

public void actionPerformed(ActionEvent e) {
  JButton.setEnabled(false);
  //...
}

I don't want user to see that. I would like all these action execute in the background. What can I do to achive it?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Jerry
  • 31
  • 1
  • 2

2 Answers2

8

You should do such intensive tasks in another thread, not the dispatcher thread.

Some useful reading: Worker Threads and SwingWorker

mdrg
  • 3,242
  • 2
  • 22
  • 44
  • Thank you for your answer. Unfortunately, there are several Threads defined and suppose to start in actionPerformed(). So, putting all this into another Thread is not a very optimal idea, is it? – Jerry May 24 '11 at 15:15
  • The first thing you do while processing is to disable the button, the last - enable it. It should disallow user clicking the button while processing. – Miki May 24 '11 at 15:17
  • @Sorrow: That's right. And that's why I put in the beginning "JButton.setEnabled(false);". After executing all actions button is enabling again. – Jerry May 24 '11 at 15:22
  • @Jerry: Right, my mistake, I missed that. However, still, putting it to the worker should be the solution, despite creating new threads. You may eventually need some synchronisation at the end. – Miki May 24 '11 at 15:31
  • @Jerry, 5 people have upvoted this answer. That should help you feel better about it. – jzd May 24 '11 at 15:58
  • @jzd Right, but I doubt that everyone who voted up, did it before I added my comment. – Jerry May 24 '11 at 16:03
  • Which comment? I voted after your last one, not sure when others voted, but using a SwingWorker to do this is absolutely correct. – jzd May 24 '11 at 16:06
  • @jzd Even if I have to put some other Threads into that Thread? – Jerry May 24 '11 at 16:09
  • @Jerry, not sure what you are calling a Thread, but if it is blocking the EDT then it is not on another Thread. – jzd May 24 '11 at 16:36
  • @jzd I meant sth like Runnable a = new Runnable() {} – Jerry May 24 '11 at 16:46
4

The problem is that the GUI-Thread is busy and will not repaint the component until processing has finsihed

You could do the activities in a backgroud thread.

king_nak
  • 11,313
  • 33
  • 58