Progress bar of a threaded task

hi
i have this class:
public class ProfileHandler extends Thread{...}
which perform some task.
the time-run of this task is unknown, so an indeterminate progress bar shoud be used.
i tried to use the swingworker, but the approach they suggest is with a not-thread task (LongTask is not a thread).
does anyone can help me to integrate my class with swingworker ?
thanks
Valerio

after some googling around, and some irc-ing on #java, i decided to change a bit the architecture, because it seems to be cleaner.
so now I have:
public class ProfileHandler implements Runnable {
//some default constructors...
//and this compulsory method
public void run(){
//where my task is accomplished.
}Now, out of this class, i can to smt like:
Thread profileHandlerThread = new Thread(ProfileHandler).start();
that will invoke the run() method.
What i want is to separate the thread process from the gui (the jprogress bar in question), having those 2 components into 2 different classes.
I don't know if your suggestion was about this way.
was it?

Similar Messages

  • Threaded Progress bar wont restart

    I know that if i have a progress bar on a form and i wont it to increment on a button click, i must thread it so i did this
    the Main class is "class Form" with variables
    public static JProgressBar progress;
    ThreadedProgress threadbar = new ThreadedProgress();
    public void actionPerformed(ActionEvent e)
    if (e.getActionCommand() == "Submit")
    threadbar.start();
    in the same file i made the a theard to increment the progress bar
    class ThreadedProgress extends Thread
         int num = 0;
         ThreadedProgress()
              //setDaemon(true);
    public void run ()
    num = 0;
    Form.progress.setValue(0); // progress bar in "class Form"
    while (num <1001)
    Form.progress.setValue(num);
    try
    Thread.sleep(10);
    catch (InterruptedException e)
         JOptionPane.showMessageDialog(null,e);
    num += 10;
    if(num > 1001)
    JOptionPane.showMessageDialog(null,"MessageSent");           
    When i click the "Submit" button once to increment the progress bar with the thread it works fine but when i click it a 2nd time, nothing happens...

    Probably the easiest thing to do is to make an anonymous inner Thread class that is within your actionPerformed(ActionEvent e) method. This was a new Thread class could be made each time the button is clicked.
    I gather that from your code, after a message has been sent, you want to show progress for a second. With Java 1.4 - it is possible to put the progress bar in indeterminate mode:
    progressBar.setIndeterminate(true);  // starts progress bar animation
    progressBar.setIndeterminate(false); // stops progress bar animationhttp://java.sun.com/docs/books/tutorial/uiswing/components/progress.html
    When you start sending your message, you could start the animation, and stop animation when the message is sent. You can reuse this method numerous time, as Java makes the required threads, etc. internally.
    Good Luck!

  • Progress bar squashed

    whenever there is a task I am displaying a progress bar of all the tasks that is going on. It shows the prgress and a scroll pane when it needs to scroll. The strange thing is in 1.4 it appears squashy but in 1.5 it works fine.
    I am just wondering who has knowledge about the differences between 1.4 and 1.5 when it comes to using jscrollpane and progress bars.
    Cheers,
    kirku

    It is not narrow. It works fine under 1.5 but in 1.4 the text appears on top of each other and not clear at all. It is strange that it shows correctly in Java 1.5 but not Java 1.4.

  • PROGRESS BAR ERRRR

    I am trying to get a progress bar working along side a large process that take a while. I first tried to make the progress bar its own thread but when I ran the large process (which spawns off the progress bar thread) the progress bar froze and waited until the larger process was done...then it should the processbar and completion....ANY suggestions?
    It looks as though the JFrame is transparent...as well if that helps.
    static void main (String[] args) {
    //stuff
    Progress p = new Progress(0,100);
    new Thread(p).start();
    //DO STUFF
    p.setValue(1);
    //DO MORE STUFF
    p.setValue(2);
    //DONE
    p.done();
    }ProgressBar Class
    package misc;
    import java.lang.*;
    import javax.swing.*;
    import java.awt.*;
    public class Progress extends Runnable{
          JFrame pFrame;
          JLabel progressInfo;
          JProgressBar progressBar;
          public int currentValue = 1;
          String currentProcess = "";
          boolean done = false;
          public Progress(int min, int max) {
             pFrame.setSize(250, 50);
             pFrame.setLocation(200,200);
             progressBar = new JProgressBar(min, max);
             setTitle("Loading something...");
             pFrame.getContentPane().setLayout(new BorderLayout());
            progressBar.setVisible(true);
             progressInfo = new JLabel();
             pFrame.getContentPane().add(progressInfo, BorderLayout.NORTH);
             pFrame.getContentPane().add(progressBar, BorderLayout.CENTER);
             show();
           }//end constructor
           public void done() {
               done = true;       
           }//end stop
           public void setScale(int newMax) {
             progressBar.setMaximum(newMax);
            }//end setScale
           public void setValue(int value) {
               currentValue = value;
           }//end setProgress
           public void setLabel(String label) {
               currentProcess = label;
           }//end setLabel
           public int getValue() {
             return progressBar.getValue();
           }//end getValue
            public void run() {
                  while (!done) {
                           processBar.setValue(currentValue);
                           processInfo.setText(currentProcess);
                          sleep(200);
                   }//end loop
              }//end run
    }//end Progress

    damn i feel stupid. how can i apply to my source:
    my app looks like GIMP. one window to control them all :) but when i'm doing something in subwindow i would like to update progressbar in main window. you have given some code but i'm to little to implement it in proper places. please give me some tips.
    I have placed observable subclass in mainframe class.
    1. Where to put update method implementaion with reference to jProgressBar1 which i use?
    1a. in mainframe class?
        public void update(Observable o, Object args)
            ProgressState ps = (ProgressState)o;
            jProgressBar1.setMaximum(ps.getTarget());
            jProgressBar1.setValue(ps.getCurrent());
            jProgressBar1.repaint();
        }    2. In other class which do some operation i'm changing progressbar values how to update them in mainframe?
            if (operation.equalsIgnoreCase("ced")) {
                EdgeDetector ed = new EdgeDetector();
                mainframe.update(?, ?); // set start values
                bix = null;
                for (int i=0;i<sekwencja.getSeqCount();i++) {
                    ed.setSourceImage(img_filters.toImage((BufferedImage)sekwencja.getImg(i)));
                    try {
                    ed.process();
                    bix = img_filters.toBufferedImage(ed.getEdgeImage());
                    sekwencja.replaceImg(i, bix);
                   mainframe.update(?, ?); // set incremented values (?) is supposed to be what?
                    } catch (EdgeDetectorException ede) {}
                logframe.wpis("SUKCES: Wykonanie operacji: "+operation+" na sekwencji "+sekwencja.getSeqCount()+" obraz?w");
                refresh();
            }3. How to update progressbar in mainframe?

  • Need help with Threading GUI progress bar

    Anyone able to help? I'm sure you've seen this a million times. I've google'd around and tried examples but still can't get a progress bar to work properly under the following situation:
    1. Created a panel with several components to select directory, display directory in tree etc.
    2. When a specific button (Search) is clicked, I want a secondary window to popup and report progress of searching down the directory.
    As you'll probably guess, the progress window isn't being updated until the end. I'm using Threads and using InvokeLater but nothing happens. Is there any good example that does the above? I can't seem to find one to figure this out.
    Thanks
    Speedy.
    Sample code:
    main.java:
    ========
    public class Main {
    public static void main(String[] args) {
    MainPanel mainPanel = new MainPanel();
    mainPanel.show();
    MainPanel.java:
    ============
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class MainPanel extends JFrame implements ActionListener {
    public MainPanel() {
    this.setSize(100,100);
    JButton startButton = new JButton("Start");
    this.getContentPane().add(startButton);
    startButton.addActionListener(this);
    public void actionPerformed(ActionEvent event) {
    ProgressPanel pp = new ProgressPanel();
    pp.show();
    SimpleTask st = new SimpleTask(pp);
    st.start();
    while (st.isAlive()) {
    System.err.println("waiting..");
    try {
    Thread.sleep(100);
    } catch (Exception e) {};
    System.err.println("finished!");
    SimpleTask.java:
    =============
    import javax.swing.SwingUtilities;
    public class SimpleTask extends Thread {
    ProgressPanel pp = null;
    public SimpleTask(ProgressPanel _pp) {
    pp = _pp;
    this.setDaemon(true);
    int i = 0;
    String position = "";
    public void run() {
    Runnable updateGUI = new Runnable() {
    public void run() {
    pp.setText(position);
    try {
    for (i=0; i<50; i++) {
    position = "Now on = " + new Integer(i).toString();
    System.err.println(position);
    SwingUtilities.invokeLater(updateGUI);
    sleep(100);
    } catch (Exception e) {}
    ProgressPanel.java:
    ===============
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class ProgressPanel extends JFrame {
    private JLabel label = new JLabel();
    public ProgressPanel() {
    this.setSize(200,200);
    this.setLocation(100,100);
    this.getContentPane().add(label);
    setText("Start");
    public void setText(String text) {
    label.setText(text);
    }

    Ok, I'll look down that road. I should have said the Thread is being used because the current while loop will be changed to perform real work. Just an example at the moment to show what I'm trying to do. Does this make a difference? The real task will be to drill down directories, counting file types/dirs etc...

  • Changing task sequence progress bar name

    Hi
    How i can rename the task sequence progress bar name.Let me know if we can add company logo as well.
    Regards, Shishir Kushawaha "If this thread answered your question, please click on "Mark as Answer"

    To edit the Icon 
    Crack open %deploymentshare%\Tools\%arch%\00000409\tsres.dll with your favorite icon editor or resource hacker and replace the first icon (321).
    My icon editor of choice is IcoFX, it's free if you can find the old version (1.6)
    The result looks like this:
    Now if we could only find a way to change the color of the gradient background, or add a custom background....
    Be sure to vote this response as helpful!
    Microsoft Certified Technology Specialist Configuring Windows 7

  • How to start and stop a progress-bar thread before/after the main thread

    hi. I would appreciate any kind of help on my request.
    I have this as my main() function
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable(){
                   public void run(){                              
                        Options op = new Options();
                        OdessaClient oc = new OdessaClient(op);     
                        oc.setVisible(true);                    
         }Whenever I try to start a simple JFrame with an indeterminate progress bar on it just before the main function and stop it somewhere after I get a StackOverFlow error
    Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
         at java.awt.Component.show(Component.java:1302)
         at java.awt.Component.setVisible(Component.java:1253)
         at com.client.CylonBar.hide(CylonBar.java:25)
         at java.awt.Component.show(Component.java:1302)
         at java.awt.Component.setVisible(Component.java:1253)
    ...and so on...How must I implement something like it?

    Not precisely that way, but just off the top of my head, you would have to have a handle to the proccess (server) in the first window, then have a monitor program that allows you take this handle and end it. I would make this monitor program be the gateway to starting and stopping your server. To run a .bat file you can use runtime.exec().

  • How to use thread only for progress bar.....

    Hello,
    I am working on an application which is taking time to load. Now I want to use a progress bar to tell the user of the application that It is taking time to load. How to do it... I read the Java swing tutorial and went through the example. Please tell me what to do. Because I am unfamiliar with Threads and I am not using thread anywhere in my application.

    You are using threads. All Java execution occurs on threads. Write a Java GUI and you're in a multithreaded environment - there's no way out of that.
    If your "application is a complex one" then you would be better advised to understand threads than to try and pretend that they don't exist. For a start, if you don't think you're using threads then you're destined to run in to all sorts of problems as regards an unresponsive GUI, as you're probably now finding out.

  • Progress bars and threads...

    Hey...
    I've had many replies on my previous questions about progress bars. I thank everybody who was concerned. But i still don't know if i have to use a seperate thread to run the progress of my bar... Can i have a progress bar in a Frame updating the progress of some file loading without having it in a seperate thread ?? I mean if i have an application that runs a Frame, this frame has buttons, textfields and other stuff, one of the buttons uploads a file chosen to a server. Now i also have a progress bar, can it keep progress of the upload without having it in a seperate thread ?? If yes, then how. Cause i can't seem to make it move unless the upload is done... I also want to know that, if i have to use a seperate thread, do i have to use something called a SwingWorker ???

    Here's the deal....
    If you don't use a separate thread, then your file upload process will block the main ("dispatch") thread until it has finished. This means that the GUI will not be updated to show your ever-growing progress bar. You'll see the bar start at zero, and then nothing will happen until the file finishes uploading, and then the bar will show 100%.
    Even if you are updating the bar in a loop, changes will still not be displayed, because repaint requests get put on a queue, and they are executed only when the VM decides it has time to do them (ie when it's finished doing your file upload!)
    So, yes you do need to use a thread to load your file and change your progress bar. and if that thread will update any GUI elements directly, start it by calling SwingUtilities.invokeLater(myThread). Also, make sure you do "myThread.setPriority(3);" (or thereabouts - make sure it's less than 5) on the thread before invoking it. This way, the main thread that updates the gui will have priority, so will update regularly.

  • Odd "progress bar"-like window opens occasionally, Windows Task Manager associates it with AcroRd32.

    We've had a few users report an odd grey "progress bar" style window open up when Adobe Reader is open.  The box has no title bar and no activity is displayed. 
    There is no close gadget or other buttons, just a blank space that looks like a progress meter.
    It doesn't happen all the time, but it does only seem to happen on the computers that are running DisplayLink.  These would be Windows 8 (32-bit or 64-bit) or 8.1 (64-bit) installs running on Microsoft Surface tablets or Dell Latitude E-series laptops.  We have a number of Win8x machines out there, but the box only appears on those running DisplayLink.
    If the box appears, opening Task Manager typically shows multiple (more than 2) instances of AcroRd32.exe running, and closing them all (one by one) through Task Manager will make the box go away.
    We don't see anything get recorded in the Windows logs.
    I know of two instances where this has occurred that were on Surface tablets where the user was just coming in for the day, waking their tablet from sleep (not a cold-start), and one of the first things they did was open a PDF file.  I cannot say whether the wake-from sleep is also a commonality or not as this "progress bar" box appears randomly and infrequently.
    It has been observed on machines running Adobe Reader XI and X.  It occurred this morning on a tablet that is running the latest XI 11.0.06.  It has been observed on machines running various versions of DisplayLink, including the latest public release.
    Any ideas as to what might be causing this box to appear?

    Hi,
    You can consider the [https://support.mozilla.org/en-US/kb/reset-firefox-easily-fix-most-problems Reset Firefox] feature via '''Help''' ('''Alt''' + '''H''') > '''Troubleshooting Information'''. If the problem persists, please also try to '''Disable''' the Yahoo Browser Plus '''Plugin''' in '''Tools''' ('''Alt''' + '''T''') > Add-ons''' and possibly other related plugins.
    (To revert to the previous profile you were using, close the new profile (i.e. exit Firefox), start Firefox and choose the '''Default User''' profile. While the [https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles Profile Manager] is open, you can also delete the newly reset profile (the one containing random numbers), or the former profile, as the case may be).
    [https://support.mozilla.org/en-US/kb/Managing-profiles Managing profiles]
    [https://support.mozilla.org/en-US/kb/Profiles?s=profile&r=2&e=sph&as=s Profiles Howto]

  • Progress bar and threads

    I have made a web browser, when you load a web-page a progress bar is displayed showing the current progress of the page loading. However if you try and load a new page before the previous page has finished loading the progress bar goes crazy. I have included a short example of what is happening below:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    //import javax.swing.event.*;
    public class ProgressBarTest extends JFrame implements ActionListener,Runnable{
        private JProgressBar myprogressBar;
        private boolean stopProgressBar = false;
        public Thread thread;
        public ProgressBarTest(){
            createGui();
        }//end of constructor
        public void createGui(){
            this.setLayout(new BorderLayout());
            this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
            this.setSize(300,150);
            JPanel ButtonPanel = new JPanel(new FlowLayout());
            JButton new_Page = new JButton("new Page");
            JButton Page_Loaded = new JButton("Page Loaded");
            new_Page.addActionListener(this);
            Page_Loaded.addActionListener(this);
            ButtonPanel.add(new_Page);
            ButtonPanel.add(Page_Loaded);
            myprogressBar = new JProgressBar(0,100);
            this.add(ButtonPanel,BorderLayout.NORTH);
            this.add(myprogressBar,BorderLayout.CENTER);
            this.setVisible(true);
        }//end of method
        public void actionPerformed(ActionEvent e) {
            if(e.getActionCommand().equals("new Page")){
                createNewandRun();
            }else if(e.getActionCommand().equals("Page Loaded")){
                stopProgressBar = true;
        }//end of method
        public void run(){
                myprogressBar.setVisible(true);
                stopProgressBar = false;
                myprogressBar.setValue(0);
                System.out.println("Page Loading...");
                try{
                    for(int i = 0;i<100;i++){
                        Thread.sleep(70);
                        myprogressBar.setValue(i);
                        if(stopProgressBar){
                            System.out.println("progress was stopeed at "+i+ " %");
                            break;
                  myprogressBar.setValue(100);
                  System.out.println("Page Loaded");
                  thread.sleep(1000); //Show complete progress bar for one second
                }catch (Exception e){
                    System.out.println("thread error "+e);
               myprogressBar.setVisible(false);
        }//end of run method
        public void createNewandRun(){
          thread = new Thread(this);
          thread.start();
        public static void main(String args[]){
             SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
              new ProgressBarTest();
        }//end of main
    }//end of classThanks in advance
    Calypso

    Using Swing Worker.... Just like your code intended, the progress bar will wait one second upon completion before being made invisible. If the "New Page" button is pressed then the old SwingWorker exits gracefully and a new one starts up. All modification of the JProgressBar is done on the Event Dispatching Thread.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeEvent;
    public class ProgressBarTest implements ActionListener,
            PropertyChangeListener{
        JButton newPage;
        JButton pageLoaded;
        JProgressBar progressBar;
        PageLoader currentWorker;
        public ProgressBarTest() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            newPage = new JButton("New Page");
            newPage.addActionListener(this);
            pageLoaded = new JButton("Page Loaded");
            pageLoaded.addActionListener(this);
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(newPage);
            buttonPanel.add(pageLoaded);
            progressBar = new JProgressBar();
            JPanel contentPane = new JPanel();
            contentPane.setLayout(new java.awt.BorderLayout());
            contentPane.add(buttonPanel,java.awt.BorderLayout.NORTH);
            contentPane.add(progressBar,java.awt.BorderLayout.CENTER);
            frame.setContentPane(contentPane);
            frame.pack();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == newPage) {
                if(currentWorker != null) {
                    currentWorker.removePropertyChangeListener(this);
                    currentWorker.cancel(true);
                progressBar.setValue(0);
                progressBar.setVisible(true);
                currentWorker = new PageLoader();
                currentWorker.addPropertyChangeListener(this);
                currentWorker.execute();
            }else if(e.getSource() == pageLoaded) {
                if(currentWorker != null) {
                    currentWorker.pageLoaded = true;
        public void propertyChange(PropertyChangeEvent evt) {
            if(evt.getPropertyName().equals("progress")) {
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
            }else if(evt.getPropertyName().equals("pageLoaded")) {
                progressBar.setVisible(false);
                currentWorker.removePropertyChangeListener(this);
                currentWorker = null;
        private class PageLoader extends SwingWorker<Void,Void> {
            private int progress;
            private boolean pageLoaded;
            public Void doInBackground() {
                for (progress = 0; progress < 100; progress++) {
                    if(pageLoaded) break;
                    try {
                        Thread.sleep(70);
                    } catch (InterruptedException e) {
                        //return gracefully since "New Page" button was pressed
                        return null;
                    setProgress(progress);
                /**The progress might have reached 100 naturally. In which case
                 * pageLoaded is false and needs to be set to true.*/
                pageLoaded = true;
                /**The Page Loaded button might have been pressed, in which case
                 * the progress is not 100 and needs to be set to 100.*/
                progress = 100;
                setProgress(100);
                try{
                    //show completed progress bar for 1 second.
                    Thread.sleep(1000);
                }catch(InterruptedException e) {
                    pageLoaded = false;
                    return null;
                return null;
            //executed on EDT when doInBackground() method is done
            public void done() {
                System.out.println("Progress reached: " + progress + "% " +
                        "upon termination.");
                if(pageLoaded) {
                   firePropertyChange("pageLoaded",null,null);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                   new ProgressBarTest();
    }

  • How do I move the page-load progress meter from the bottom task bar to the top menu bar, or inside the top/header toolbar? I am currently using Firefox Version 3.6.19

    How do I move the page-load progress meter from the bottom task bar to the top menu bar, or inside the top/header toolbar? I am currently using Firefox Version 3.6.19.
    URL Eaddress: [email protected]

    You see the orange (on Linux gray) Firefox button if the Menu Bar is hidden, so you need to hide the Menu bar to get the new appearance.<br />
    If you need to access the hidden Menu bar then press F10 or hold down the Alt key to make the Menu Bar appear temporarily.<br />
    You can place the Tab Bar on top.
    * View > Toolbars : [ ] Menu Bar
    * View > Toolbars : [X] Tabs on Top
    The Tab bar only appears on the title bar if the Firefox window is maximized.

  • Progress bar with background task

    Hi, I am using background agent to upload files. Its taking about 30 min to upload a single image or audio file. Is there any method to reduce the time to launch the background agent in production. I'm using the following line for debug process and its
    working fine and the files are getting uploaded as soon as possible. But when the application is in windows phone store im not able to use this line of code. Please help if there is any solution to reduce the time for background agent launch. Also is there
    any UI changes I can make while the background process is running, so that the user can identify that the file is uploading. Can I use progress bar indicator or anything when the background file is uploading. Thanks.
    ScheduledActionService.LaunchForTest("My periodic task", TimeSpan.FromSeconds(3));
    Nikitha

    Assuming this is a Windows Phone 8.1 XAML Application:
    https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh452975(v=win.10).aspx
    The following sample illustrates how to do all of this with progress etc...
    https://code.msdn.microsoft.com/windowsapps/Background-Transfer-Sample-d7833f61
    Bret Bentzinger (MSFT) @awehellyeah

  • How to get multiline text on progress bar

    Hi there,
    I have to use Progress Bar and need to show text in multiline.
    can anyone please suggest me how to achieve that.
    Thanks,
    Prashant

    can u guys figure out what really i am missing here?A spoon-fed solution, I suppose. So enjoy:
    // A JProgressBar with two lines of text.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.beans.*;
    public class PB2Lines extends JPanel implements
                             ActionListener, PropertyChangeListener {
        private TwoLinesProgressBar progressBar;
        private JButton startButton;
        private Task task;
        class Task extends SwingWorker<Void, Void> {
            public Void doInBackground() {
                int progress = 0;
                //Initialize progress property.
                setProgress(0);
                while (progress < 100) {
                    progress += 25;
                    setProgress(progress);
              if (progress==25)
                progressBar.setString("Eggs|added");
              else if (progress==50)
                progressBar.setString("Sugar|added");
              else if (progress==75)
                progressBar.setString("Milk|added");
              else
                progressBar.setString("Everything|done");
                    try {
                      Thread.sleep(500);
                    } catch (InterruptedException ignore) {}
                return null;
            public void done() {
                Toolkit.getDefaultToolkit().beep();
                startButton.setEnabled(true);
                setCursor(null); //turn off the wait cursor
        public PB2Lines() {
            super(new BorderLayout());
            //Create the demo's UI.
            startButton = new JButton("Start");
    //        startButton.setActionCommand("start");
            startButton.addActionListener(this);
            progressBar = new TwoLinesProgressBar(0, 100);
            progressBar.setPreferredSize(new Dimension(200,40));
            progressBar.setValue(0);
    //        progressBar.setStringPainted(true);
            progressBar.setString("Progress|Bar");
            JPanel panel = new JPanel();
            panel.add(startButton);
            panel.add(progressBar);
            add(panel, BorderLayout.PAGE_START);
            setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
         * Invoked when the user presses the start button.
        public void actionPerformed(ActionEvent evt) {
            startButton.setEnabled(false);
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            task = new Task();
            task.addPropertyChangeListener(this);
            task.execute();
         * Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                   JFrame frame = new JFrame("ProgressBar with 2 lines");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   JComponent newContentPane = new PB2Lines();
                   newContentPane.setOpaque(true); //content panes must be opaque
                   frame.setContentPane(newContentPane);
                   frame.pack();
                   frame.setVisible(true);
      class TwoLinesProgressBar extends JProgressBar {
        public TwoLinesProgressBar(int min, int max) {
          super(min, max);
        private int getXofCenteredString(String s) {
          int ix= getFontMetrics(getFont()).stringWidth(s);
          return (getWidth()-ix)/2;
        protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          int i= getString().indexOf('|');
          String s= getString().substring(0,i);
          int ix= getXofCenteredString(s);
          g.setColor(Color.BLACK);
          g.drawString(s, ix,15);
          s= getString().substring(i+1);
          ix= getXofCenteredString(s);
          g.drawString(s, ix,35);
    }

  • Need simple progress bar

    Hi...
    I have a GUI which calls methods in different classes.
    There are three long running tasks, which I want to be able to display the progress of.
    Each task MUST finish before the other proceeds, so I don't think it is necessary for more than one thread.
    I want to have a simple "progress bar" pop-up when each task starts, and then disappear when it is finished. Or, have a "progress indicator" on the GUI, which can be reset and started again.
    I have played around with JProgressBars and JProgressMonitors (from this site), but haven't been able to adapt them to the simple needs.
    Is there any hope for what I want to achieve?
    You would have thought this was an easy task, but I'm a broken man!
    Thanks for any help.

    Maybe this example will help.
    If it does may I claim the duke dollars please
    * ProgressDLG.java
    * Created on 23 April 2004, 13:38
    package com.starjar.tests.progress;
    * @author  Peter Henderson
    public class ProgressDLG extends javax.swing.JDialog {
        /** Creates new form ProgressDLG */
        public ProgressDLG(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            java.awt.GridBagConstraints gridBagConstraints;
            jButton1 = new javax.swing.JButton();
            jProgressBar1 = new javax.swing.JProgressBar();
            jLabel1 = new javax.swing.JLabel();
            getContentPane().setLayout(new java.awt.GridBagLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            jButton1.setText("Start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridy = 5;
            getContentPane().add(jButton1, gridBagConstraints);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridy = 2;
            getContentPane().add(jProgressBar1, gridBagConstraints);
            jLabel1.setText("jLabel1");
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridy = 1;
            getContentPane().add(jLabel1, gridBagConstraints);
            pack();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            jButton1.setEnabled(false);
            Worker w = new Worker();
            w.start();
        class Worker extends Thread {
            public void run() {
                task1();
                task2();
                task3();
                workerComplete();
            private void workerComplete() {
                try {
                    javax.swing.SwingUtilities.invokeAndWait( new Runnable() {
                        public void run() {
                            jButton1.setEnabled(true);
                } catch(Exception e ) {
                    // oh well.
            private void setTaskNameFromWorker(final String taskName) {
                try {
                    javax.swing.SwingUtilities.invokeAndWait( new Runnable() {
                        public void run() {
                            jLabel1.setText( taskName );
                } catch(Exception e ) {
                    // oh well.
            private void setProgressFromWorker(final int progress) {
                try {
                    javax.swing.SwingUtilities.invokeAndWait( new Runnable() {
                        public void run() {
                            jProgressBar1.setValue(progress);
                } catch(Exception e ) {
                    // oh well.
            private void task1() {
                setTaskNameFromWorker("Running Task ONE");
                for(int i=0; i<100; i++) {
                    setProgressFromWorker(i);
                    try{ Thread.currentThread().sleep(25); } catch(Exception e) {}
            private void task2() {
                setTaskNameFromWorker("Running Task TWO");
                for(int i=0; i<100; i++) {
                    setProgressFromWorker(i);
                    try{ Thread.currentThread().sleep(25); } catch(Exception e) {}
            private void task3() {
                setTaskNameFromWorker("Running Task THREE");
                for(int i=0; i<100; i++) {
                    setProgressFromWorker(i);
                    try{ Thread.currentThread().sleep(25); } catch(Exception e) {}
         * @param args the command line arguments
        public static void main(String args[]) {
            new ProgressDLG(new javax.swing.JFrame(), true).show();
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JProgressBar jProgressBar1;
        // End of variables declaration
    }Peter Henderson
    Sales Manager
    Starjar Ltd
    http://www.starjar.com

Maybe you are looking for

  • Show and hide events in a dashboard widget

    These two functions never seem to fire off. If the widget is hidden the hide function doesnt run and the show function only runs on the insitial load. My problem here is that i am running a setinterval to perform a task every 30 seconds while visible

  • Why won't the 10.6.8 update install?

    I am doing a free install on a large hard drive. I previously ran Leopard o my old mac, bought snow leopard, then upgraded to mountain lion. That worked fine. Now i have put a 640gb hard drive in my mac, installed 10.6.3, works fine. Now i want to up

  • PERFORMANCE BAD WHEN CURSORS ARE USED WITHIN PL/SQL BLOCKS

    There are poor database performance at Oracle 10g For some cursor selects, the performance is under Oracle 10g significant slower than under Oracle 9i.On a test system (Oracle 9) the problem does not reproduce, on the 10g system however always. The s

  • How to design an iPhone app that uses both Portrait and Landscape in Flash CS6

    So I have created an App that has a different menu when it is held portrait, but changes when held landscape. I can get the navigation to work, However I am unsure how to design landscape pages inside Flash? My stage is set to the standard 640x960 ai

  • URGENT : Migrate ODI or Change / Recreate Repositories?

    Hi there; I'm using ODI 10.1.3.6.0 and Oracle 10g db server (which keeps both master and work repositories) installed on the same machine. For some reason, our db guys are decided to move Oracle db to another machine but we don't want to migrate ODI.