Page 1 of 1

progress bar tutorial introduction to progress bars and multithreading Rate Topic: -----

#1 alpha02  Icon User is offline

  • Sexy DIC God
  • member icon

Reputation: 47
  • View blog
  • Posts: 803
  • Joined: 20-May 06

Posted 11 May 2007 - 07:42 PM

Introduction

Many people seem to have trouble dealing with progress bars, or the swing control JProgressBar, so this tutorial will take you through the process of creating a simple application in which a button will make the progress bar increment progressively from 0 to 100 in five seconds. This will introduce you another important lesson in Java: multithreading, which allows you to run multiple tasks in your application at the same time. All right, let's get started!

Creating the main class

We will name our main class Program1, but feel free to change the name anytime. Here is the class with the main method declared:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	public static void main (String[] args){
		//Some code here...
	}
}


We have to declare every GUI component. From now on, I assume you have some basics about null layout components, otherwise see my other tutorial about this. All right, we declare, of course, a JFrame and a Container, and we also need a button and a progress bar. All together, you should get:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){
		//Some code here...
	}
}


Simple enough. We will instantiate all components, add them to the container, then position them. Since you know how GUI creation works, I will simply give you the full code since GUI is not the main purpose of this tutorial.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){
		//Set Look and Feel
		try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
		catch (Exception e) {}

		//Create all components
		frmMain = new JFrame("Sample progress bar application");
		frmMain.setSize(300, 100); //Window size 300x100 pixels
		pane = frmMain.getContentPane();
		pane.setLayout(null); //Apply the null layout
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when X is clicked
		btnDo = new JButton("Go!");
		barDo = new JProgressBar(0, 100); //Min value: 0 Max value: 100	

		//Add components to pane
		pane.add(btnDo);
		pane.add(barDo);

		//Position controls (X, Y, width, height)
		barDo.setBounds(10, 10, 280, 20);
		btnDo.setBounds(100, 35, 100, 25);

		//Make frame visible
		frmMain.setResizable(false);
		frmMain.setVisible(true);

		//Add action listeners
		btnDo.addActionListener(new btnDoAction());
	}
}



That's it for the GUI. Now, notice the add action listeners section. When the button is pressed, the actionPerformed method from the btnDoAction class will be fired. This class will be created in the next part.

The button's action

As stated above, the actionPerformed void method from our action listener class will be fired, you will know what I mean by looking at the following example:

public static class btnDoAction implements ActionListener{
	public void actionPerformed (ActionEvent e){
		//Do some events when button is pressed...
	}
}


Take time to study the above code. I put a comment where some code will happen when you click the button. Put this little snippet in your Program1 class, but outside your main method. Make some tests with the action listener, then read the next section.

Starting a thread (multithreading)

Some may think multithreading in Java is difficult, but don't worrk, it's quite easy. Now that you've learning class implementing with the action listener, you will need to apply what you know to implement the run method of a Runnable, which is a thread. Here is what is looks like:

public static class thread1 implements Runnable{
	public void run(){
		
	}
}


As you probably guessed, the run() void will contain the various events which will occur once this thread is started using its start() method. To start this thread, we will need to use:

new Thread(new thread1()).start();


In the thread, we will put the code to increment the progressbar, which goes as follow:

for (int i=0; i<=100; i++){
	barDo.setValue(i);
	barDo.repaint();
	try{Thread.sleep(50);}
	catch (InterruptedException err){}
}


Nothing new here for the for() loop, this is part of Java's basics. The barDo.setValue(i) line changes the value of progressbar to i, which is the incrementing variable, so the bar increments. The repaint() method refreshes the graphics of the bar, this is something important to think of as you update some graphical components. The try...catch stuff is also part of the basics. We use Thread.sleep(50) to make the thread sleep 50 milliseconds, or 1/20 of a second. We have to handle the InterruptedException error which may be thrown by this instruction. Now, if you understant well, the bar will increment slowly to reach its maximum value in ten seconds. Clear enough? So let's put our code to work!

Putting it all together

Now that you master all this stuff (or at least know how to work with), put all the code into place. Not sure how? Take a look at the full code here and all will seem more clear to you:

//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{ //Main class
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){ //Main void
		//Set Look and Feel
		try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
		catch (Exception e) {}

		//Create all components
		frmMain = new JFrame("Sample progress bar application");
		frmMain.setSize(300, 100); //Window size 300x100 pixels
		pane = frmMain.getContentPane();
		pane.setLayout(null); //Use the null layout
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when X is clicked
		btnDo = new JButton("Go!");
		barDo = new JProgressBar(0, 100); //Min value: 0 Max value: 100	

		//Add components to pane
		pane.add(btnDo);
		pane.add(barDo);

		//Position controls (X, Y, width, height)
		barDo.setBounds(10, 10, 280, 20);
		btnDo.setBounds(100, 35, 100, 25);

		//Make frame visible
		frmMain.setResizable(false); //No resize
		frmMain.setVisible(true);

		//Add action listeners
		btnDo.addActionListener(new btnDoAction()); //Add the button's action
	}

	//The action
	public static class btnDoAction implements ActionListener{
		public void actionPerformed (ActionEvent e){
			new Thread(new thread1()).start(); //Start the thread
		}
	}

	//The thread
	public static class thread1 implements Runnable{
		public void run(){
			for (int i=0; i<=100; i++){ //Progressively increment variable i
				barDo.setValue(i); //Set value
				barDo.repaint(); //Refresh graphics
				try{Thread.sleep(50);} //Sleep 50 milliseconds
				catch (InterruptedException err){}
			}
		}
	}
}


Test your code. Click the button. What happens? The bar fills in five seconds!

Conclusion

Well, this is it for now. You've learned the basics of multithreading and this can be used in quite a big bunch of contexts in any application. I'm thinking about FTP clients, browsers, and anything requiring a progress bar. Got questions? Then contact me.

Is This A Good Question/Topic? 1
  • +

Replies To: progress bar tutorial

#2 omordha  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 20-February 09

Posted 20 February 2009 - 02:45 PM

View Postalpha02, on 11 May, 2007 - 06:42 PM, said:

Introduction

Many people seem to have trouble dealing with progress bars, or the swing control JProgressBar, so this tutorial will take you through the process of creating a simple application in which a button will make the progress bar increment progressively from 0 to 100 in five seconds. This will introduce you another important lesson in Java: multithreading, which allows you to run multiple tasks in your application at the same time. All right, let's get started!

Creating the main class

We will name our main class Program1, but feel free to change the name anytime. Here is the class with the main method declared:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	public static void main (String[] args){
		//Some code here...
	}
}


We have to declare every GUI component. From now on, I assume you have some basics about null layout components, otherwise see my other tutorial about this. All right, we declare, of course, a JFrame and a Container, and we also need a button and a progress bar. All together, you should get:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){
		//Some code here...
	}
}


Simple enough. We will instantiate all components, add them to the container, then position them. Since you know how GUI creation works, I will simply give you the full code since GUI is not the main purpose of this tutorial.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){
		//Set Look and Feel
		try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
		catch (Exception e) {}

		//Create all components
		frmMain = new JFrame("Sample progress bar application");
		frmMain.setSize(300, 100); //Window size 300x100 pixels
		pane = frmMain.getContentPane();
		pane.setLayout(null); //Apply the null layout
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when X is clicked
		btnDo = new JButton("Go!");
		barDo = new JProgressBar(0, 100); //Min value: 0 Max value: 100	

		//Add components to pane
		pane.add(btnDo);
		pane.add(barDo);

		//Position controls (X, Y, width, height)
		barDo.setBounds(10, 10, 280, 20);
		btnDo.setBounds(100, 35, 100, 25);

		//Make frame visible
		frmMain.setResizable(false);
		frmMain.setVisible(true);

		//Add action listeners
		btnDo.addActionListener(new btnDoAction());
	}
}



That's it for the GUI. Now, notice the add action listeners section. When the button is pressed, the actionPerformed method from the btnDoAction class will be fired. This class will be created in the next part.

The button's action

As stated above, the actionPerformed void method from our action listener class will be fired, you will know what I mean by looking at the following example:

public static class btnDoAction implements ActionListener{
	public void actionPerformed (ActionEvent e){
		//Do some events when button is pressed...
	}
}


Take time to study the above code. I put a comment where some code will happen when you click the button. Put this little snippet in your Program1 class, but outside your main method. Make some tests with the action listener, then read the next section.

Starting a thread (multithreading)

Some may think multithreading in Java is difficult, but don't worrk, it's quite easy. Now that you've learning class implementing with the action listener, you will need to apply what you know to implement the run method of a Runnable, which is a thread. Here is what is looks like:

public static class thread1 implements Runnable{
	public void run(){
		
	}
}


As you probably guessed, the run() void will contain the various events which will occur once this thread is started using its start() method. To start this thread, we will need to use:

new Thread(new thread1()).start();


In the thread, we will put the code to increment the progressbar, which goes as follow:

for (int i=0; i<=100; i++){
	barDo.setValue(i);
	barDo.repaint();
	try{Thread.sleep(50);}
	catch (InterruptedException err){}
}


Nothing new here for the for() loop, this is part of Java's basics. The barDo.setValue(i) line changes the value of progressbar to i, which is the incrementing variable, so the bar increments. The repaint() method refreshes the graphics of the bar, this is something important to think of as you update some graphical components. The try...catch stuff is also part of the basics. We use Thread.sleep(50) to make the thread sleep 50 milliseconds, or 1/20 of a second. We have to handle the InterruptedException error which may be thrown by this instruction. Now, if you understant well, the bar will increment slowly to reach its maximum value in ten seconds. Clear enough? So let's put our code to work!

Putting it all together

Now that you master all this stuff (or at least know how to work with), put all the code into place. Not sure how? Take a look at the full code here and all will seem more clear to you:

//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{ //Main class
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){ //Main void
		//Set Look and Feel
		try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
		catch (Exception e) {}

		//Create all components
		frmMain = new JFrame("Sample progress bar application");
		frmMain.setSize(300, 100); //Window size 300x100 pixels
		pane = frmMain.getContentPane();
		pane.setLayout(null); //Use the null layout
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when X is clicked
		btnDo = new JButton("Go!");
		barDo = new JProgressBar(0, 100); //Min value: 0 Max value: 100	

		//Add components to pane
		pane.add(btnDo);
		pane.add(barDo);

		//Position controls (X, Y, width, height)
		barDo.setBounds(10, 10, 280, 20);
		btnDo.setBounds(100, 35, 100, 25);

		//Make frame visible
		frmMain.setResizable(false); //No resize
		frmMain.setVisible(true);

		//Add action listeners
		btnDo.addActionListener(new btnDoAction()); //Add the button's action
	}

	//The action
	public static class btnDoAction implements ActionListener{
		public void actionPerformed (ActionEvent e){
			new Thread(new thread1()).start(); //Start the thread
		}
	}

	//The thread
	public static class thread1 implements Runnable{
		public void run(){
			for (int i=0; i<=100; i++){ //Progressively increment variable i
				barDo.setValue(i); //Set value
				barDo.repaint(); //Refresh graphics
				try{Thread.sleep(50);} //Sleep 50 milliseconds
				catch (InterruptedException err){}
			}
		}
	}
}


Test your code. Click the button. What happens? The bar fills in five seconds!

Conclusion

Well, this is it for now. You've learned the basics of multithreading and this can be used in quite a big bunch of contexts in any application. I'm thinking about FTP clients, browsers, and anything requiring a progress bar. Got questions? Then contact me.

Was This Post Helpful? 0
  • +
  • -

#3 omordha  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 20-February 09

Posted 20 February 2009 - 03:01 PM

View Postalpha02, on 11 May, 2007 - 06:42 PM, said:

Introduction

Many people seem to have trouble dealing with progress bars, or the swing control JProgressBar, so this tutorial will take you through the process of creating a simple application in which a button will make the progress bar increment progressively from 0 to 100 in five seconds. This will introduce you another important lesson in Java: multithreading, which allows you to run multiple tasks in your application at the same time. All right, let's get started!

Creating the main class

We will name our main class Program1, but feel free to change the name anytime. Here is the class with the main method declared:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	public static void main (String[] args){
		//Some code here...
	}
}


We have to declare every GUI component. From now on, I assume you have some basics about null layout components, otherwise see my other tutorial about this. All right, we declare, of course, a JFrame and a Container, and we also need a button and a progress bar. All together, you should get:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){
		//Some code here...
	}
}


Simple enough. We will instantiate all components, add them to the container, then position them. Since you know how GUI creation works, I will simply give you the full code since GUI is not the main purpose of this tutorial.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){
		//Set Look and Feel
		try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
		catch (Exception e) {}

		//Create all components
		frmMain = new JFrame("Sample progress bar application");
		frmMain.setSize(300, 100); //Window size 300x100 pixels
		pane = frmMain.getContentPane();
		pane.setLayout(null); //Apply the null layout
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when X is clicked
		btnDo = new JButton("Go!");
		barDo = new JProgressBar(0, 100); //Min value: 0 Max value: 100	

		//Add components to pane
		pane.add(btnDo);
		pane.add(barDo);

		//Position controls (X, Y, width, height)
		barDo.setBounds(10, 10, 280, 20);
		btnDo.setBounds(100, 35, 100, 25);

		//Make frame visible
		frmMain.setResizable(false);
		frmMain.setVisible(true);

		//Add action listeners
		btnDo.addActionListener(new btnDoAction());
	}
}



That's it for the GUI. Now, notice the add action listeners section. When the button is pressed, the actionPerformed method from the btnDoAction class will be fired. This class will be created in the next part.

The button's action

As stated above, the actionPerformed void method from our action listener class will be fired, you will know what I mean by looking at the following example:

public static class btnDoAction implements ActionListener{
	public void actionPerformed (ActionEvent e){
		//Do some events when button is pressed...
	}
}


Take time to study the above code. I put a comment where some code will happen when you click the button. Put this little snippet in your Program1 class, but outside your main method. Make some tests with the action listener, then read the next section.

Starting a thread (multithreading)

Some may think multithreading in Java is difficult, but don't worrk, it's quite easy. Now that you've learning class implementing with the action listener, you will need to apply what you know to implement the run method of a Runnable, which is a thread. Here is what is looks like:

public static class thread1 implements Runnable{
	public void run(){
		
	}
}


As you probably guessed, the run() void will contain the various events which will occur once this thread is started using its start() method. To start this thread, we will need to use:

new Thread(new thread1()).start();


In the thread, we will put the code to increment the progressbar, which goes as follow:

for (int i=0; i<=100; i++){
	barDo.setValue(i);
	barDo.repaint();
	try{Thread.sleep(50);}
	catch (InterruptedException err){}
}


Nothing new here for the for() loop, this is part of Java's basics. The barDo.setValue(i) line changes the value of progressbar to i, which is the incrementing variable, so the bar increments. The repaint() method refreshes the graphics of the bar, this is something important to think of as you update some graphical components. The try...catch stuff is also part of the basics. We use Thread.sleep(50) to make the thread sleep 50 milliseconds, or 1/20 of a second. We have to handle the InterruptedException error which may be thrown by this instruction. Now, if you understant well, the bar will increment slowly to reach its maximum value in ten seconds. Clear enough? So let's put our code to work!

Putting it all together

Now that you master all this stuff (or at least know how to work with), put all the code into place. Not sure how? Take a look at the full code here and all will seem more clear to you:

//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{ //Main class
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){ //Main void
		//Set Look and Feel
		try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
		catch (Exception e) {}

		//Create all components
		frmMain = new JFrame("Sample progress bar application");
		frmMain.setSize(300, 100); //Window size 300x100 pixels
		pane = frmMain.getContentPane();
		pane.setLayout(null); //Use the null layout
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when X is clicked
		btnDo = new JButton("Go!");
		barDo = new JProgressBar(0, 100); //Min value: 0 Max value: 100	

		//Add components to pane
		pane.add(btnDo);
		pane.add(barDo);

		//Position controls (X, Y, width, height)
		barDo.setBounds(10, 10, 280, 20);
		btnDo.setBounds(100, 35, 100, 25);

		//Make frame visible
		frmMain.setResizable(false); //No resize
		frmMain.setVisible(true);

		//Add action listeners
		btnDo.addActionListener(new btnDoAction()); //Add the button's action
	}

	//The action
	public static class btnDoAction implements ActionListener{
		public void actionPerformed (ActionEvent e){
			new Thread(new thread1()).start(); //Start the thread
		}
	}

	//The thread
	public static class thread1 implements Runnable{
		public void run(){
			for (int i=0; i<=100; i++){ //Progressively increment variable i
				barDo.setValue(i); //Set value
				barDo.repaint(); //Refresh graphics
				try{Thread.sleep(50);} //Sleep 50 milliseconds
				catch (InterruptedException err){}
			}
		}
	}
}


Test your code. Click the button. What happens? The bar fills in five seconds!

Conclusion

Well, this is it for now. You've learned the basics of multithreading and this can be used in quite a big bunch of contexts in any application. I'm thinking about FTP clients, browsers, and anything requiring a progress bar. Got questions? Then contact me.



I've spent a ridiculous amount of time trying to add a progress bar to my app without success. This one seemed pretty straightforward, but I'm having problems.

Netbeans doesn't recognize barDO from within the run(). I tried using parentClass.barDO - no dice. The thread class doesn't know anything about the parent class, so it can't access the jProgressBar.

I tried creating a jPanel from within the thread - it works, but creates a new panel every time my event fires. I create an event every time a piece of my task completes.

How can you access a jProgressBar that exists outside of the thread class?



View Postalpha02, on 11 May, 2007 - 06:42 PM, said:

Introduction

Many people seem to have trouble dealing with progress bars, or the swing control JProgressBar, so this tutorial will take you through the process of creating a simple application in which a button will make the progress bar increment progressively from 0 to 100 in five seconds. This will introduce you another important lesson in Java: multithreading, which allows you to run multiple tasks in your application at the same time. All right, let's get started!

Creating the main class

We will name our main class Program1, but feel free to change the name anytime. Here is the class with the main method declared:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	public static void main (String[] args){
		//Some code here...
	}
}


We have to declare every GUI component. From now on, I assume you have some basics about null layout components, otherwise see my other tutorial about this. All right, we declare, of course, a JFrame and a Container, and we also need a button and a progress bar. All together, you should get:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){
		//Some code here...
	}
}


Simple enough. We will instantiate all components, add them to the container, then position them. Since you know how GUI creation works, I will simply give you the full code since GUI is not the main purpose of this tutorial.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){
		//Set Look and Feel
		try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
		catch (Exception e) {}

		//Create all components
		frmMain = new JFrame("Sample progress bar application");
		frmMain.setSize(300, 100); //Window size 300x100 pixels
		pane = frmMain.getContentPane();
		pane.setLayout(null); //Apply the null layout
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when X is clicked
		btnDo = new JButton("Go!");
		barDo = new JProgressBar(0, 100); //Min value: 0 Max value: 100	

		//Add components to pane
		pane.add(btnDo);
		pane.add(barDo);

		//Position controls (X, Y, width, height)
		barDo.setBounds(10, 10, 280, 20);
		btnDo.setBounds(100, 35, 100, 25);

		//Make frame visible
		frmMain.setResizable(false);
		frmMain.setVisible(true);

		//Add action listeners
		btnDo.addActionListener(new btnDoAction());
	}
}



That's it for the GUI. Now, notice the add action listeners section. When the button is pressed, the actionPerformed method from the btnDoAction class will be fired. This class will be created in the next part.

The button's action

As stated above, the actionPerformed void method from our action listener class will be fired, you will know what I mean by looking at the following example:

public static class btnDoAction implements ActionListener{
	public void actionPerformed (ActionEvent e){
		//Do some events when button is pressed...
	}
}


Take time to study the above code. I put a comment where some code will happen when you click the button. Put this little snippet in your Program1 class, but outside your main method. Make some tests with the action listener, then read the next section.

Starting a thread (multithreading)

Some may think multithreading in Java is difficult, but don't worrk, it's quite easy. Now that you've learning class implementing with the action listener, you will need to apply what you know to implement the run method of a Runnable, which is a thread. Here is what is looks like:

public static class thread1 implements Runnable{
	public void run(){
		
	}
}


As you probably guessed, the run() void will contain the various events which will occur once this thread is started using its start() method. To start this thread, we will need to use:

new Thread(new thread1()).start();


In the thread, we will put the code to increment the progressbar, which goes as follow:

for (int i=0; i<=100; i++){
	barDo.setValue(i);
	barDo.repaint();
	try{Thread.sleep(50);}
	catch (InterruptedException err){}
}


Nothing new here for the for() loop, this is part of Java's basics. The barDo.setValue(i) line changes the value of progressbar to i, which is the incrementing variable, so the bar increments. The repaint() method refreshes the graphics of the bar, this is something important to think of as you update some graphical components. The try...catch stuff is also part of the basics. We use Thread.sleep(50) to make the thread sleep 50 milliseconds, or 1/20 of a second. We have to handle the InterruptedException error which may be thrown by this instruction. Now, if you understant well, the bar will increment slowly to reach its maximum value in ten seconds. Clear enough? So let's put our code to work!

Putting it all together

Now that you master all this stuff (or at least know how to work with), put all the code into place. Not sure how? Take a look at the full code here and all will seem more clear to you:

//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Program1{ //Main class
	//Declare GUI components
	static JFrame frmMain;
	static Container pane;
	static JButton btnDo;
	static JProgressBar barDo;

	public static void main (String[] args){ //Main void
		//Set Look and Feel
		try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
		catch (Exception e) {}

		//Create all components
		frmMain = new JFrame("Sample progress bar application");
		frmMain.setSize(300, 100); //Window size 300x100 pixels
		pane = frmMain.getContentPane();
		pane.setLayout(null); //Use the null layout
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Exit when X is clicked
		btnDo = new JButton("Go!");
		barDo = new JProgressBar(0, 100); //Min value: 0 Max value: 100	

		//Add components to pane
		pane.add(btnDo);
		pane.add(barDo);

		//Position controls (X, Y, width, height)
		barDo.setBounds(10, 10, 280, 20);
		btnDo.setBounds(100, 35, 100, 25);

		//Make frame visible
		frmMain.setResizable(false); //No resize
		frmMain.setVisible(true);

		//Add action listeners
		btnDo.addActionListener(new btnDoAction()); //Add the button's action
	}

	//The action
	public static class btnDoAction implements ActionListener{
		public void actionPerformed (ActionEvent e){
			new Thread(new thread1()).start(); //Start the thread
		}
	}

	//The thread
	public static class thread1 implements Runnable{
		public void run(){
			for (int i=0; i<=100; i++){ //Progressively increment variable i
				barDo.setValue(i); //Set value
				barDo.repaint(); //Refresh graphics
				try{Thread.sleep(50);} //Sleep 50 milliseconds
				catch (InterruptedException err){}
			}
		}
	}
}


Test your code. Click the button. What happens? The bar fills in five seconds!

Conclusion

Well, this is it for now. You've learned the basics of multithreading and this can be used in quite a big bunch of contexts in any application. I'm thinking about FTP clients, browsers, and anything requiring a progress bar. Got questions? Then contact me.

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

#4 bayron.jofel  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 6
  • Joined: 16-April 09

Posted 19 April 2009 - 10:40 PM

thanks for your code bro, i learn something new <Removed email>
Was This Post Helpful? 1
  • +
  • -

#5 Aldahbra  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 16
  • Joined: 02-January 10

Posted 02 January 2010 - 03:38 PM

I can't get the program1 to compile

----jGRASP exec: javac -g C:\Users\...\Program1.java

Program1.java:39: cannot find symbol
symbol : class btnDoAction
location: class Program1
btnDo.addActionListener(new btnDoAction());
^
1 error

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1