Solved

Progress bar in java swings

Posted on 2008-06-25
11
1,189 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 

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

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jboss wildfly 10.1 10 586
ejb entity bean example 2 56
swing controls 2 35
convert Absolute path to relative path of FTP location 7 48
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
In this post we will learn different types of Android Layout and some basics of an Android App.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses

739 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