Solved

Progress bar in java swings

Posted on 2008-06-25
11
1,185 Views
Last Modified: 2008-10-04
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.
0
Comment
Question by:FranklinRaj22
11 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 21864067
If the speed is not calculable, you should probably do

pb.setIndeterminate(true);
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 21864145
0
 
LVL 2

Expert Comment

by:sandeep1984
ID: 21864588

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
Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 

Author Comment

by:FranklinRaj22
ID: 21865703
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
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 21868403
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
 

Author Comment

by:FranklinRaj22
ID: 21873708
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 21873749
>>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
 

Author Comment

by:FranklinRaj22
ID: 21874311
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 21874367
>>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

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jar file executable 12 52
windows explorer path to command prompt 5 44
servlet example issue 6 39
jboss wildfly 10.1 10 89
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question