Solved

Java progress bar

Posted on 2013-05-12
12
1,493 Views
Last Modified: 2013-05-13
Attached is a method I have to set up a progress bar.  Once it is set up I have a numeric variable in another method.  I would like to update the progress bar from the method with the numeric variable

    public void progressBar(int value) {
        JDialog f = new JDialog();
        f.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        Container content = f.getContentPane();
        JProgressBar progressBar = new JProgressBar();
        progressBar.setValue(value);
        progressBar.setStringPainted(true);
        Border border = BorderFactory.createTitledBorder("Reading...");
        progressBar.setBorder(border);
        content.add(progressBar, BorderLayout.NORTH);
        f.setSize(300, 100);
        f.setLocation(750, 500);
        f.setVisible(true);
  }
public void updateProgressBar() {

for (int i=1; i<100; i++) {

    // Update progress bar here using i

}
0
Comment
Question by:sargent240
  • 5
  • 4
  • 2
  • +1
12 Comments
 
LVL 35

Expert Comment

by:mccarl
ID: 39160407
Since you have only posted a VERY small part of what you are doing it is hard to give too much advice. But my guess about the best way to do it... have your "progressBar(int value)" method return the "progressBar" object that you create inside that method. Then when you call the "progressBar(int value)" method you can save the return value and then inside your loop, you can just call "setValue(i)" on that returned object.

If you post the rest of your code, we might be able to provide a more appropriate answer.
0
 
LVL 25

Expert Comment

by:Tomas Helgi Johannsson
ID: 39160922
As mccarl said the only thing you need to do is to put
progressBar.setValue(i) inside your for-loop

For the updateProgressBar to be able to access the progressBar object
you will need to set the JProgressBar declaration
JProgressBar progressBar;

as an private class variable like this

class ... {

private JProgressBar progressBar;

public void progressBar(int value) {
....
          progressBar = new JProgressBar();
....

}

public void updateProgressBar() {
   
  for (int i = 0;...){
       progressBar.setValue(i)
   }


}

} // end class

Take a look at these examples to see other usefull tricks using ProgressBar
http://www.java2s.com/Code/Java/Swing-JFC/ProgressBar.htm

Regards,
    Tomas Helgi
0
 

Author Comment

by:sargent240
ID: 39161745
Per mccarl's request, attached is the entire class.  As you can see I going through a data base and trying to eliminate the duplicate entries.  The class works fine.  Sometimes I have to run it a couple of times to get them all.  I can address that problem later.  What happens with the progress bar is, the dialog box comes up but the progress bar does not appear until the the while loop is completed and then the progress bar appears in the dialog box at 100.
progressBar.java
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 86

Expert Comment

by:CEHJ
ID: 39161806
As you can see I going through a data base and trying to eliminate the duplicate entries.  
That's mystifying as it suggests that there are fundamental issues with the db that need to be solved. If that is the case, why are you using user-domain code to do this, as opposed to ddl sql on the db itself, an operation, incidentally, that should be a once-only affair?
0
 

Author Comment

by:sargent240
ID: 39162416
Because at this point this is all I know how to do.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39162493
Well in that case, you're posting in the wrong TA. You need to sort your data out first. Post in the TA for your RDBMS
0
 

Author Comment

by:sargent240
ID: 39163186
My original post did not ask for help with the database.  It asked for help updating a progress bar.  I made a comment in a later post about another problem I was having and I went on to say, "I can address that problem later."  My question remains about the progress bar.  I posted the entire class as suggested by mccarl and Thomas
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39163257
My original post did not ask for help with the database.
Well i can assure you - you need it. It's simply wrong to run user-level code to correct fundamental database design issues
0
 

Author Comment

by:sargent240
ID: 39163307
Is that what is keeping me from being able to update a progress bar?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39163370
No - the progress bar is not relevant, much as the state of cleanliness of a car is not relevant when its wheels are falling off
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39163453
Ok, while I agree fully with CEHJ about fixing your database issues, I still think that the essence of this question, "How to update a progress bar while a long running task is executing" has merit, both to the original author as well as to anyone else that stumbles along this question in the future. I think the DB issue point has been well and truly made, and so we should stay on topic and move on to the problem at hand!

And that is.... I assume that you are calling this "cleanBuyerDuplicates()" method from within an ActionPerformed handler, say from a button being clicked on another screen, etc. The problem then is that all this code gets executed within what Swing calls the "Event Dispatch Thread" which is in charge of keeping the GUI up to date and handling various events that are associated with the GUI. The fact that you are keeping that thread busy while you are doing your long running operation means that it can't do other things, like update the visual state of a progress bar.

You need to use a separate thread to execute your long task, and one of the easier ways to do that, whilst also being able to update things in the GUI is via the "SwingWorker" class. Have a look at the code below, which is basically the same as yours except that the SwingWorker encapsulates the code that runs your task and then it uses "PropertyListeners" to communicate the current 'progress' of the task to a separate thread that can call the actual progressBar.setValue(...) method.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package auctionreports;

import java.awt.BorderLayout;
import java.awt.Container;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.border.Border;

/**
 * 
 * @author al
 */
public class CleanBuyerPermFile {
    
    ConnectDatabase connectDatabase = new ConnectDatabase();
    public Connection con;
    public String entries[] = new String[7000];
    boolean found = true;
    JProgressBar progressBar = new JProgressBar();
    
    public static int countRows(Connection conn, String tableName) throws SQLException {
        // select the number of rows in the table
        Statement stmt = null;
        ResultSet rs = null;
        int rowCount = -1;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName + " WHERE type = 1");
            // get the number of rows from the result set
            rs.next();
            rowCount = rs.getInt(1);
        } finally {
            rs.close();
            stmt.close();
        }
        return rowCount;
    }
    
    public void progressBar(int value) {
        JDialog f = new JDialog();
        f.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        Container content = f.getContentPane();
        progressBar = new JProgressBar();
        progressBar.setValue(value);
        progressBar.setStringPainted(true);
        Border border = BorderFactory.createTitledBorder("Reading...");
        progressBar.setBorder(border);
        content.add(progressBar, BorderLayout.NORTH);
        f.setSize(300, 100);
        f.setLocation(750, 500);
        f.setVisible(true);
    }
    
    public final void cleanBuyerDuplicates() {
        
        progressBar(0);
        SwingWorker worker = new SwingWorker<String, String>() {
            
            @Override
            protected String doInBackground() throws Exception {
                con = connectDatabase.getConnection();
                int i = 1;
                int j = i - 1;
                entries[6749] = "0";
                entries[0] = "";
                String buyer = "1";
                String str = "";
                PreparedStatement pstmt = null;
                try {
                    
                    int totalRows = countRows(con, "customer");
                    
                    Statement st = con.createStatement();
                    String command = "SELECT * FROM customer WHERE type = " + buyer + " ORDER BY name";
                    ResultSet rec = st.executeQuery(command);
                    
                    while (rec.next()) {
                        str = rec.getString("name");
                        System.out.println("str = " + str);
                        setProgress(i); // *************** NOTE: You need to
                                        // make sure 'i' varies from 0 to 100,
                                        // if you can't you have to use the
                                        // following line instead
                        // firePropertyChange("progress", null, i);
                        if (!str.equals("")) {
                            found = true;
                            if (entries[i - 1].equals(str)) {
                                
                                String deleteCommand = "DELETE FROM customer WHERE name=? LIMIT 1";
                                
                                pstmt = con.prepareStatement(deleteCommand);
                                pstmt.setObject(1, str);
                                pstmt.executeUpdate();
                                
                            } else {
                                entries[i] = str;
                                i++;
                            }
                        }
                    }
                    
                    if (i == 0) { // list is blank
                        entries[6749] = "0";
                        return null;
                    }
                    entries[6749] = String.valueOf(i); // set list size
                    con.close();
                    pstmt.close();
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(null, "SQLException Cleaning perm buyer list: " + ex.getMessage());
                }
                return null;
            }
        };
        
        worker.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("progress".equals(evt.getPropertyName())) {
                    progressBar.setValue((Integer) evt.getNewValue());
                }
            }
        });
        
        worker.execute();
    }
    
}

Open in new window

(Note: this code isn't fully tested as I wasn't going to go through and take out your DB specific code and replace with dummy code, but it should be along the right lines)
0
 

Author Closing Comment

by:sargent240
ID: 39163554
Thanks mccarl!  That was the answer to my question.  I appreciate your help.  I will now get after the other problem in your comment
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

A short article about a problem I had getting the GPS LocationListener working.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

839 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