Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Cancelling a progress bar

 
ivin jacob
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to have a cancel feature in a jprogress bar .
The genericButton1 click invokes the progress bar and the jButton invokes the cancel button .
The code pasted below does not cancel the progress bar.

However i found out that if i invoke the updateBar method using a thread like this





Could any one explain me why it does not work without a thread and also
whether what i have followed with a thread to cancel the progress is a good approach else suggest the best practice


 
dave taubler
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Threads and JProgressBars are tricky. They're tricky primarily because by their nature, JProrgessBars are used whenever some long-running activity is occurring (because the whole purpose of a JProgressBar is to inform the user of the progress of such an activity).

The root of the problem is if the activity occurs on the Event Dispatch thread, then calling a method to update the JProgressBar won't have any visible effect; the Event Dispatch thread--which is usually the thread that is tasked with redrawing the JProgressBar--is already busy with the activity. In your case, the activity is the for loop.

Your approach to forcing jProgressBar1 to repaint by using another thread works, but is considered "incorrect". Components should *always* be updated by the Event Dispatch thread, to ensure that data corruption does not occur. It's a little too lengthy to go into here, but you can probably Google "awt event dispatch thread" or something like that and find various discussions on the issue. Understanding the Event Dispatch thread is key to doing good Swing/AWT programming, particularly with an issue like the one you're describing.

The best approach is to have your long-running activity--again, the for loop in this case--execute in a separate thread. Then, you call SwingUtilities.invokeLater() to update your JProgressBar, something like:

The call to SwingUtilities.invokeLater(Runnable r) puts r on the Event Dispatch thread, where it belongs.
[ December 10, 2007: Message edited by: dave taubler ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!