JProgressBar and Thread class - Coding Together

I've brought you today, a new Java Tutorial using the JProgressBar with Thread class. Here is it. Check it out.

import javax.swing.*;
import java.awt.*;
class JProgressBarThread extends JFrame
JProgressBar jp;
Thread t;
public JProgressBarThread()
}catch(Exception e){}
setTitle("JProgressBar with Thread Demo");
setLayout(new FlowLayout());
jp=new JProgressBar();
jp.setPreferredSize(new Dimension(350,30));
t=new Thread(new Runnable(){
public void run()
for(int i=0;i<=jp.getMaximum();i++)
// Loop it forever
// Update value
// Get the effect
}catch(Exception e){}
} }
// Start thread
// Set the size now
// Make it center now
public static void main(String args[])
new JProgressBarThread();
setStringPainted(true): Set the percentage painted on the progress bar. It is of your wish.
setPreferredSize(new Dimension(350,25)): Make the progress bar quite fat :)
new Runnable(){}: Thread class constructor takes Runnable as parameter and instead of writing a new class and implementing the Runnable, i've used an anonymous inner-class which is simple. It looks like writing the body of the Runnable interface, providing the body to the run() method in it.
setValue(): Sets a given value to the progress bar.
jp.getMaximum(): Get the maximum value of the progress bar. By default, it returns '100' if nothing is set. You can set it by using the setMaximum() method.
t.start(): Start the execution of the thread.
Thread.sleep(200): Wait for sometime after updating the value, so that it looks like in motion, else the value will be updated at once and hence its effect is not observed.
For Loop: Written so that the value will be updated as it is in the loop.

How do i use JProgressBar in Real time?
The answer is simple. Just get the changing value and paint it on the Progress bar. If you have no changing value, then use the Timer class to update the progress bar instead. Here is a tutorial for using progress bar with the Timer class.

Posted by at on

Tags: Swing Components,