Solved

JProgressBar

Posted on 2006-10-20
5
445 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
Comment Utility
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 24

Accepted Solution

by:
Tomas Helgi Johannsson earned 250 total points
Comment Utility
    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
Comment Utility
Thank you Tomas

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

Author Comment

by:blarouche
Comment Utility
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
Comment Utility
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

728 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now