Random Progress Speed for JProgressBar

Random Progress in JProgressBar


Here is a sample tutorial, to randomize JProgressBar progress speed.

Randomize Progress - Example




import javax.swing.*;
import java.awt.*;
import java.util.*;
class RandomProgressbar extends JFrame implements Runnable
{
JProgressBar jb;
Thread t;
Random r;

public RandomProgressbar()
{
setTitle("Random Progress in ProgressBar");
setLayout(new GridBagLayout());
setSize(400,400);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

jb=new JProgressBar();
jb.setStringPainted(true);

r=new Random();

t=new Thread(this);
t.start();
add(jb);
}
public static void main(String args[])
{
new RandomProgressbar();
}
public void run()
{
try
{
for(int i=1;i<=jb.getMaximum();i++)
{
jb.setValue(i);

int rnum=r.nextInt(100);

Thread.sleep(rnum);

// Print random number
System.out.println("Generated number : "+rnum);

// Loop forever

if(i==jb.getMaximum())
i=1;
}
}catch(Exception e){}

}

}


javax.swing.*: JFrame, JProgressBar used.

java.awt.*: GridBagLayout used.

java.util.*: Random class used.

jb.setStringPainted(true): Let the percent complete be visible.

t.start(): Start thread execution. Run is invoked.

jb.getMaximum(): Returns maximum value. Default: 100

jb.setValue(i): Update JProgressBar value to i (declared in loop).

r.nextInt(100): Returns random number from 0 to 100

Thread.sleep(rnum): Set random sleep time, for random speed.

Runnable interface: Contains run() method.



Posted by at on

Tags: Swing Components,