Solved

JProgressBar

Posted on 2006-10-20
5
446 Views
Last Modified: 2012-08-14
I am new to Swing so I have a question concerning JProgressBar.

I have a task to do that takes about 5 minutes ( updating a database ). I would like to add a progressBar. I have copied a few classes  from http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html.
I have three classes LongTask.java, SwingWorker.java and ProgressBarDemo.java.
I have my main class that update the database from a menu button and I have another class that execute the task.

Now I am a bit lost. How do I connect them together so that it works.
Where do ProgressBarDemo.java knows the task to do

Thank you
0
Comment
Question by:blarouche
  • 4
5 Comments
 

Author Comment

by:blarouche
ID: 17773263
Do I have to put my code into the ActualTask class below ?



/**
     * The actual long running task.  This runs in a SwingWorker thread.
     */
    class ActualTask {
        ActualTask() {
            //Fake a long task,
            //making a random amount of progress every second.
            while (!canceled && !done) {
                try {
                    Thread.sleep(1000); //sleep for a second
                    current += Math.random() * 100; //make some progress
                    if (current >= lengthOfTask) {
                        done = true;
                        current = lengthOfTask;
                    }
                    statMessage = "Completed " + current +
                                  " out of " + lengthOfTask + ".";
                } catch (InterruptedException e) {
                    System.out.println("ActualTask interrupted");
                }
            }
        }
    }
0
 
LVL 25

Accepted Solution

by:
Tomas Helgi Johannsson earned 250 total points
ID: 17773560
    Hi!

Here you have several JProgressBar demos : http://www.java2s.com/Code/Java/Swing-JFC/ProgressBar.htm

Take a look at this example explaining how you can update the progressbar
when fireing an ActionEvent : http://www.java2s.com/Code/Java/Swing-JFC/AdemonstrationoftheProgressMonitortoolbar.htm 
Your solution should be similar to that where you fire an ActionEvent after each update.

Regards,
  Tomas Helgi
0
 

Author Comment

by:blarouche
ID: 17774304
Thank you Tomas

I am looking at it and trying to solve my problem
0
 

Author Comment

by:blarouche
ID: 17791852
I still don't know how to make this thing work.


CLASS STEADFASTFRONTOFFICE from SteadFrontOffice.java


private void initActions() {
updateItem.addActionListener( new MyActionListener( this ) );
 }// end initActions method


     */
       
       private static void createAndShowGUI() {
           //Create and set up the window.
           JFrame frame = new JFrame("ProgressBarDemo");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

           //Create and set up the content pane.
           JComponent newContentPane = new ProgressBarDemo();
           newContentPane.setOpaque(true); //content panes must be opaque
           frame.setContentPane(newContentPane);

           //Display the window.
           frame.pack();
           frame.setVisible(true);
       }

          // anonymous inner class to handle update item event      
             class MyActionListener implements ActionListener{
                                 
             SteadfastFrontOffice frontOffice ;
             MyActionListener( SteadfastFrontOffice sfo ){
             frontOffice = sfo ;
             }             
                   
                    public void actionPerformed( ActionEvent event )
                    {  
                          
                          
             javax.swing.SwingUtilities.invokeLater(new Runnable() {
                         public void run() {
                             createAndShowGUI();
                         }
                     });

                 }// end action performed
                     
                      }// My ActionListener



CONSTRUCTOR FOR CLASS CSVImport from CSVImport.java

     public CsvImport(String csvFile,String xmlFile,String symbol, DBQuotes quotes, SteadfastFrontOffice sfo){    
            this.csvFile    = csvFile;
            this.xmlFile    = xmlFile;
            this.symbol     = symbol;
            this.quotes     = quotes;
            this.app        = sfo;
           
            this.skip_firstline = false;
            this.exit_on_error  = true;
            this.debug  = false;
            this.update_quotes = false;
            loadConfiguration();
            startImport();
        }  




0
 

Author Comment

by:blarouche
ID: 17791881
Sorry we're missing some code here

WHERE DO I EXECUTE THE TASK CSVIMPORT SO THAT MY PROGESS BAR CAN SHOW ME THE PROGRESS


public class ProgressBarDemo extends JPanel
                             implements ActionListener {
    public final static int ONE_SECOND = 1000;

    private JProgressBar progressBar;
    private Timer timer;
    private JButton startButton;
    private LongTask task;
    private JTextArea taskOutput;
    private String newline = "\n";

    public ProgressBarDemo() {
        super(new BorderLayout());
        task = new LongTask();

        //Create the demo's UI.
        startButton = new JButton("Start");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        progressBar = new JProgressBar(0, task.getLengthOfTask());
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5,5,5,5));
        taskOutput.setEditable(false);
        taskOutput.setCursor(null); //inherit the panel's cursor
                                    //see bug 4851758

        JPanel panel = new JPanel();
        panel.add(startButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        //Create a timer.
        timer = new Timer(ONE_SECOND, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                progressBar.setValue(task.getCurrent());
                String s = task.getMessage();
                if (s != null) {
                    taskOutput.append(s + newline);
                    taskOutput.setCaretPosition(
                            taskOutput.getDocument().getLength());
                }
                if (task.isDone()) {
                    Toolkit.getDefaultToolkit().beep();
                    timer.stop();
                    startButton.setEnabled(true);
                    setCursor(null); //turn off the wait cursor
                    progressBar.setValue(progressBar.getMinimum());
                }
            }
        });
    }

    /**
     * Called when the user presses the start button.
     */
    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        task.go();
        timer.start();
    }



   * Called from ProgressBarDemo to start the task.
     */
    public void go() {
        final SwingWorker worker = new SwingWorker() {
            public Object construct() {
                current = 0;
                done = false;
                canceled = false;
                statMessage = null;
                return new ActualTask();
            }
        };
        worker.start();
    }


  class ActualTask {
        ActualTask() {
            //Fake a long task,
            //making a random amount of progress every second.
            while (!canceled && !done) {
                try {
                    Thread.sleep(1000); //sleep for a second
                    current += Math.random() * 100; //make some progress
                    if (current >= lengthOfTask) {
                        done = true;
                        current = lengthOfTask;
                    }
                    statMessage = "Completed " + current +
                                  " out of " + lengthOfTask + ".";
                } catch (InterruptedException e) {
                    System.out.println("ActualTask interrupted");
                }
            }
        }
    }






0

Featured Post

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
The viewer will learn how to implement Singleton Design Pattern in Java.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

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