Search This Blog

How to Make a Timer Controlled Progress Bar in Java

Java progress bar value updated using timer. update JProgressBar by thread, set progress of progress bar using timer thread
timer controlled progress bar in java
For some applications we require to use timer and progress-bars. Java has a swing class called
JProgressBar to create progress bars. It can have horizontal or vertical orientation. We can set the maximum and minimum values for JProgressBar. It can also have an indeterminate state in which the progressbar does not show a definite value and plays an animation to show that the process is in progress. JProgressBar can be used in indeterminate mode when neither can you determine how long a process would take to complete nor can you track its progress. In some other cases, you may have to use timers. Java provides a Timer class (Java.util.Timer). But you can create a very simple and flexible timer if you want. If the timer does not have crucial importance, you can use a thread that sleeps for every one second as a timer. I have been using such threads as timers for a long time and never failed. Such timers may fail (although very rarely) when the processor has very heavy workload.

Whatever, in a simple example, we will see how to create a timer using thread and how to use JProgressBar. In this example we control the JProgressBar using the timer. The progress in JProgressBar is set calling the method setValue(). In this example we are using a 1 minute timer. The progress bar should show the progress of timer. The java code for timer controlled JProgressBar is as follows:



import java.awt.Color; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JProgressBar; import javax.swing.WindowConstants; public class MyFrame extends JFrame{ JProgressBar jpb; public MyFrame(){ setLayout(new FlowLayout()); setSize(170,100); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jpb=new JProgressBar(JProgressBar.HORIZONTAL,0, 100); //jpb=new JProgressBar(); is enough. //In that case, Default values for parameters are same as above jpb.setForeground(Color.GREEN);//set foreground color of progressbar jpb.setStringPainted(true);//to show a string on jpb (by default it is percent) jpb.setBackground(Color.BLACK);//set background color of progressbar add(jpb); ProgressUpdate.start();//starting the timer thread } public static void main(String args[]) { new MyFrame().setVisible(true); } //creating a Thread (for timer) within the MyFrame class Thread ProgressUpdate=new Thread() { public void run() { int time=60;//1 min=60 seconds for(int i=0;i<time;i++)     {     try {         Thread.sleep(1000);//Thread is made to sleep for 1 sec         } catch (Exception ex) {}     jpb.setValue(100*i/60);        //i sec out of 60 sec elapsed.         // to convert to range of 0 to 100, 100*i/60     } } };  }

No comments:

Post a Comment