Progress bar in java swings

My Swings GUI when clicked calls a method from the backend (which is again plain java)
the responsetime varies from 3 sec to 3 mins , so i would lik to place a progress bar which would show the user the progress of his request.

But when i tried to browse through the net , they hav used a timer mostly and this timer generates a random number and the progress is based on that. Now i cannot place a timer since my progress bar sure move wit the speed of my response. How to accomplish this.
FranklinRaj22Asked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
You've got some of the right ideas - they're just not in the right place. Full marks for using SwingWorker though ;-)

You can use the org.jdesktop SwingWorker as below (since it's compatible with the one in the latest JDK), or use the one in JDK 1.6. You would just need to override the method below called 'doTheBusiness'
import java.awt.*;
import org.jdesktop.swingworker.SwingWorker;
import java.awt.event.*;
 
import javax.swing.*;
import javax.swing.event.*;
 
 
class ProgressBarExample extends JFrame implements ActionListener {
	private JProgressBar progress;
	private JButton button;
	private JLabel label1;
	private JPanel topPanel;
 
	public ProgressBarExample(String a) {
		super(a);
		topPanel = new JPanel();
		topPanel.setPreferredSize(new Dimension(310, 130));
		getContentPane().add(topPanel);
		label1 = new JLabel("");
		label1.setPreferredSize(new Dimension(280, 24));
		topPanel.add(label1);
		progress = new JProgressBar(0, 100);
		progress.setPreferredSize(new Dimension(300, 20));
		progress.setMinimum(0);
		progress.setMaximum(20);
		progress.setValue(25);
		progress.setBounds(20, 35, 260, 20);
		topPanel.add(progress);
		JButton bnStart = new JButton("Start");
		bnStart.addActionListener(this);
		topPanel.add(bnStart);
		progress.setVisible(true);
	}
 
	public void go() {
		label1.setText("Retrieving data...");
		progress.setIndeterminate(true);
	}
 
	public void stop() {
		progress.setIndeterminate(false);
	}
 
	public void actionPerformed(ActionEvent e) {
	    go();
	    GetTablesAction gta = new GetTablesAction();
	    gta.execute();
	}
 
	public void doTheBusiness() {
	    try {
		Thread.sleep((int)(Math.random() * 1000 * 5));
	    }
	    catch(InterruptedException e) {
		/* ignore */
	    }
	}
 
	private class GetTablesAction extends SwingWorker {
	    
	    public Object doInBackground() {
		doTheBusiness();
		return null;
	    }
 
	    public void done() {
		label1.setText("Data retrieved");
		stop();
	    }
 
	}
 
	public static void main(String[] args) {
	    EventQueue.invokeLater(new Runnable() {
		public void run() {
		    ProgressBarExample pbe = new ProgressBarExample("Test");
		    pbe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		    pbe.setSize(300, 200);
		    pbe.setVisible(true);
		}
	    });
	}
}

Open in new window

0
 
CEHJCommented:
If the speed is not calculable, you should probably do

pb.setIndeterminate(true);
0
 
ksivananthCommented:
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
sandeep1984Commented:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
class Test extends JFrame implements Runnable
{
	int length	=	1000;
	JProgressBar progressBar;
	
	public Test()
	{
		progressBar = new JProgressBar(0,length);
		progressBar.setBounds(20,20,200,25);
		this.getContentPane().setLayout(null);
		this.getContentPane().add(progressBar);
		progressBar.setValue(0);
		progressBar.setStringPainted(true);
		this.setSize(300,100);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		new Thread(this).start();
	}
	
	public void run()
	{
		for(int s=0;s<length;s++)
		{
			progressBar.setValue(s);
			try
			{
				Thread.sleep(10);
			}catch(Exception exp){}
		}
	}
	
	public static void main(String args[])
	{
		Test test	=	new Test();
		test.setVisible(true);
	}
}

Open in new window

0
 
FranklinRaj22Author Commented:
Guys am still stuck very badly.... will giv u my code piece please advice.

SwingWorker worker = new SwingWorker() {
                public Object construct() {  
                    startProgress();
                    return new Object();
                }
        };
                //length = 1000;
            worker.start();
            schemMap = (Map)this.getTables(dbProperties);  
            worker.interrupt();

This is the initial piece , where the .getTables method is the method in the back end... till it finishes the job i need to run my progress bar.

As u see the swing worker call the method  startProgress(); to run simultanesouly

public void startProgress()
    {
        System.out.println("WEN IS THIS HYAPP" + new Date());
        mainFrame = new ProgressBarExample("SIT");
                    mainFrame.setBounds(400,400,100,100);
                    mainFrame.setVisible( true );
                    mainFrame.pack();
                    mainFrame.go();
    }

 AND THIS IS MY ProgressBarExample :

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class ProgressBarExample extends JFrame
{
    private JProgressBar    progress;
    private JButton         button;
    private JLabel          label1;
    private JPanel          topPanel;
    public ProgressBarExample(String a)
    {
                super(a);
               
                topPanel = new JPanel();
                topPanel.setPreferredSize( new Dimension( 310, 130 ) );
                getContentPane().add( topPanel );    
                label1 = new JLabel( "getting tables" );
                label1.setPreferredSize( new Dimension( 280, 24 ) );
                topPanel.add( label1 );
                System.out.println("am i here1");
                progress = new JProgressBar(0,100);
                progress.setPreferredSize( new Dimension( 300, 20 ) );
                progress.setMinimum( 0 );
                progress.setMaximum( 20 );
                progress.setValue( 25 );
                progress.setBounds( 20, 35, 260, 20 );
                topPanel.add( progress );
                //progress.setIndeterminate(true);
                progress.setVisible(true);
                System.out.println("am i here12");
    }

 
     
    public void go() {
       
        progress.setIndeterminate(true);
        }  

   

    public void stop() {
       
        progress.setMaximum(0);
    }    
   }
Now to my problems :

First My progress bar does stop even wen i worker.interuppt is called
Second my progress bar comes up only after the get tables is done , until then its jus a small frame. I can see i hav made a small mistake smewhere couldn find where


0
 
FranklinRaj22Author Commented:
CEHJ , the sollution u gave was too... but i did not satisfy one of my requirments... let me explain please help !

My main program extends a JFrame and its has all the GUI needed along with some back end calls.
One type cal only needs this progress bar. My progress bar I hav kept it as a seperate class. Now if i mov my backend call to the Progress bar class everythin goes fine  except that this backend call gives the data to feed my GUI , so i need to mak my main prog wait til this back end procees goin in the thread gets over . now rthis wont happen...
to be more clear  ,in the main prog if i add a few statements below ( System.out.println("i need help");) I want them to be executed only after the main job is over... now they will run simultaneously.


public static void main(String[] args) {
          EventQueue.invokeLater(new Runnable() {
            public void run() {
                ProgressBarExample pbe = new ProgressBarExample("Test");
                pbe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                pbe.setSize(300, 200);
                pbe.setVisible(true);
            }
          });
     System.out.println("i need help");
      }




0
 
CEHJCommented:
>>to be more clear  ,in the main prog if i add a few statements below ( System.out.println("i need help");)

Well you wouldn't normally have application code in there - only code to start the app. Is it really only a print out that you want when the main processing is finished?
0
 
FranklinRaj22Author Commented:
nope its an app code... in this example since we have called the Progressbar example in main it looks so but in my real app i would call it on a button click in the middle of my app... so after the progress bar ends i hav lotsa code to execute but they should be only after the exit of the progress bar.
0
 
CEHJCommented:
>>so after the progress bar ends i hav lotsa code to execute but they should be only after the exit of the progress bar.

Well you can see in my example i have code executing at that point too, so just place it after that - i.e. in the stop() method
0
All Courses

From novice to tech pro — start learning today.