Practical 9: Write a program to launch a JProgressBar

1) Write a program to demonstrate the following output:

Ans:
import javax.swing.*;
import java.awt.*;

public class JProgresBarDemo 
{
    JProgressBar JProgressBarObj;
    int i=0,num=0;
    
    JProgresBarDemo()
    {
        JFrame JFrameMain  = new JFrame();

        JFrameMain.setVisible(true);
        JFrameMain.setSize(400,400);
        JFrameMain.setLayout(new FlowLayout());
        
        JProgressBarObj = new JProgressBar(0,2000);
        JProgressBarObj.setValue(0);
        JProgressBarObj.setStringPainted(true);

        JFrameMain.add(JProgressBarObj);
    }

    public static void main(String[] args) 
    {
        JProgresBarDemo jpd = new JProgresBarDemo();
        jpd.iterate();
    }

    public void iterate()
    {
        while(i<=2000){
            JProgressBarObj.setValue(i);
            i =i+20;
            try
            {
                Thread.sleep(150);
            } 
            catch(Exception e)
            {

            }
        }
    }

}

2) Write a Program using JProgressBar to show the progress of Progressbar when user clicks on JButton.
Ans:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JProgressBarApplet extends JApplet implements ActionListener
{
    JProgressBar JProgressBarObj;
    JButton JButtonObj;
    int i=0;

    public void init()
    {
        setSize(400,400);
        setVisible(true);
        setLayout(new FlowLayout());

        JButtonObj = new JButton("Click Me");
        JButtonObj.addActionListener(this);

        JProgressBarObj = new JProgressBar();
        JProgressBarObj.setStringPainted(true);
        JProgressBarObj.setValue(0);

        add(JButtonObj);
        add(JProgressBarObj);
    }

    public void actionPerformed(ActionEvent ie)
    {
        this.iterate();
    }

    public void iterate()
    {
        while(i<=2000)
        {
            JProgressBarObj.setValue(i);
            i=i+20;
            try
            {
                Thread.sleep(150);
            }
            catch(Exception e)
            {}
        }
    } 
}
/* 
   
*/

Output:
JProgressBar when user clicks on JButton

Previous
Next Post »