idd be glad to have fun & contribute to this project.
threads - nasty little buggers to get ahold of.
1.) All GUI related activity occurs on the Event Dispatch Thread (EDT), and since swing is "light weight" all comonent drawing and stuff happens there.
The way i like to do this, there are other ways, is to create a private class that looks something like this.
Code: Select all
private class DoCrap implements Runnable
{
public DoCrap()
{
}
public void run()
{
for(int x=0; x<SOME_NUM; x++)
{
/** length code, can be a method from other class **/
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
progressBar.setValue(NUM);
}
});
}
}
}
"But eman, you scallion, what is that doing?" Well, all threads in java implement runable which has one thing you NEED to define,
run(). inside the run method, we do what we want, and have access to all the methods and variables since we are a private internal class (or whatever the "proper" wording is). So, we do our work, and then when we finish an increment of work, we want to let the user know.
SwingUtilities.invokeLater() will take any Runnable object and launch its run() method, BUT it does this on the EDT at the next convinent time. I simple chose to define my new Runnable object inside the call to it. This way, the GUI related task is done were it should be & the user will see it update without freezing the current thread or GUI. Additional, this WONT que up hundreds of new run events, it will only launch the most recent one, so if we have called invokeLater() 7 times before the EDT gets a turn, only the most recent call will be processed, saving overhead and redundant method calls.
You will want to declare the jproggres bar synchronized so that two threads can access the object simultaneously, and you will have to define the range of the progress bar before you try to set its progress (
setMaximum(int maxValue). So, lets say were about to do something, it would be done like so
Code: Select all
/** show dialog with focus & jProggresbar **/
setStuffUp();
disableButtons(); //we don't want them clicking while we are busy!
new Thread(new DoCrap()).start();
You COULD save the thread object and declare it inside the scope of the entire program to save a smidgion of overhead, but it wont make a difference since its a few milliseconds compared to a multi second task. and its more OOP to keep things in a proper scope
There are other ways, many people are a fan of the SwingWorker class (comes with the JRE in 1.6+, packported completly to 1.5, can be used in 1.4 w/o generics dl:
https://swingworker.dev.java.net/). But my way is just a personal preffrence, that i feel teaches you a littble bit more of what exactly is going on if you look up the class docs (i tried to sum it up in a short, conceptual bite... okay maybe a few bites).