Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 105,416 Java Programmers for FREE! Ask your question and get quick answers from experts. There are 1,849 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



progress bar tutorial

 
Reply to this topicStart new topic

> progress bar tutorial, introduction to progress bars and multithreading

alpha02
Group Icon



post 11 May, 2007 - 07:42 PM
Post #1


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:

CODE
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:

CODE
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.

CODE
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:

CODE
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:

CODE
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:

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


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

CODE
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:

CODE
//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.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 8/20/08 06:05AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month