[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

JProgressBar

Posted on 2006-10-20
5
Medium Priority
?
456 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 26

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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

In this post we will learn different types of Android Layout and some basics of an Android App.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses
Course of the Month18 days, 9 hours left to enroll

825 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