Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the Progress Bar in Java (Netbeans GUI)

I am not too experienced with Java and am having trouble getting a progress bar to work. I am using Netbeans' built-in GUI maker. Currently my program reads in images from a directory into an image array. Obviously this takes a bit of time, thus I would like a simple progress bar to update the user to know how far the loading is. I have used one of those drag-and-drop progress bar components.

  • I currently can get the number of files in a directory and can calculate the percentage of files loaded
  • The files successfully load into the array, but the progress bar is only updated after all files are loaded. I have tried revalidating and repainting while I loop but this does not work
  • I have tried the various tutorials on docs.oracle but can't seem to get anything working.
  • I believe SwingWorker is the class I should be using, is this correct?

Any help with an example or some advice would be greatly appreciated! Thanks!

like image 508
Matthew Mills Avatar asked Nov 03 '22 17:11

Matthew Mills


1 Answers

Yes, you have run into the trap of all new Swing programers - the Event Dispatching Thread

Basically speaking, this Thread is the heart of any Swing system. Is is responsible for dispatching events to all the UI components, as well as making requests to the repaint manager to update the UI.

If you do any time consuming tasks while in the EDT, you will prevent the UI from been updated.

I'd suggest you start by having a read through Worker Threads and SwingWorker and Concurrency in Swing and, because I know you're going to ask, have a read of this answer, it has a number of examples of using SwingWorker, JTextArea appending problems

like image 63
MadProgrammer Avatar answered Nov 09 '22 10:11

MadProgrammer