?
Solved

JProgressBar

Posted on 2006-10-20
5
Medium Priority
?
453 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
[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
  • 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 500 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month11 days, 12 hours left to enroll

752 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