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();
}

Similar Messages

  • 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.

  • Splash screen with progress bar and multiple jar files to load

    Hello,
    I have been looking to the new features in java 6 for splash screens. I haven't implemented this never before and i was wondering how i could do the following with java 1.5 or 6:
    I would like to see a splash screen with a progress bar that "grows" when every jar file has been read.
    At this time i call my application like this from a shell script:
    exec "$JAVA_BIN" -Djava.library.path=$LIBRARIES_J3D -classpath xxxx.jar yyyy.jar zzzz.jar ...
    where xxx.jar, yyy.jar and zzz.jar are very heavy jars.
    So i would like to see in the progress bar 33% 66% and 100% when they are loaded.
    I do not know if this is the right forum to ask for this. If no, please point me which would be the ideal one.
    Any help will be very useful. Thanks to all!

    Am 10.07.2015 um 07:17 schrieb Lalit Solanki:
    > Hi friend,
    >
    > I am create pure eclipse E4 application and trying to splash screen with progress bar and message.
    >
    >
    >
    >
    > but above image in only support eclipse E3 application so pleas help me how to add progress bar and message in eclipse E4 application
    >
    Hi Lalit,
    there's a Bug entry: https://bugs.eclipse.org/bugs/show_bug.cgi?id=382224
    Meanwhile you can use this solution:
    https://www.eclipse.org/forums/index.php/t/328812/5ceed4bcaa683a94d65efb161bffd217/
    Regards,
    Ralf.

  • How to change the color of the progress bar and string

    Is their anyway to change the color of the progress bar and the string which shows the progress of the bar. The current color of the bar is purple and i would like it to be red or blue so that it stands out against the background of the JFrame i am using. I dont want to change the color of the JFrame
    Thanks in advance

    import java.awt.*;
    import javax.swing.*;
    public class ProgressEx {
        public static void main(String[] args) {
            UIManager.put("ProgressBar.background", Color.WHITE);
            UIManager.put("ProgressBar.foreground", Color.BLACK);
            UIManager.put("ProgressBar.selectionBackground", Color.YELLOW);
            UIManager.put("ProgressBar.selectionForeground", Color.RED);
            UIManager.put("ProgressBar.shadow", Color.GREEN);
            UIManager.put("ProgressBar.highlight", Color.BLUE);
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JProgressBar pb1 = new JProgressBar();
            pb1.setStringPainted(true);
            pb1.setValue(50);
            JProgressBar pb2 = new JProgressBar();
            pb2.setIndeterminate(true);
            Container cp = f.getContentPane();
            cp.add(pb1, BorderLayout.NORTH);
            cp.add(pb2, BorderLayout.SOUTH);
            f.pack();
            f.setVisible(true);
    }

  • Show progress bar and percents when packaging a native installer with adt packager

    Hello,
    Below is a simple example using the AIR's NativeProcess for compiling an air application into a native installer... Everything works fine, so at the end of the NativeProcess, the native installer (*.exe) is created... In this case, the application which I'm trying to compile is small (approx. 600KB)... However, if I have to package into native installer a bigger file (several MBs), I would like also to monitor the progress by using a progress bar and percents... How?
    private var file:File
    private var nativeProcessStartupInfo:NativeProcessStartupInfo;
    private var nativeProcess:NativeProcess;
    private function compile():void{
      file = new File("C:\\Program Files\\Java\\jre7\\bin\\java.exe");
      nativeProcessStartupInfo = new NativeProcessStartupInfo();
      var args:Vector.<String> = new Vector.<String>();
      args.push("-jar");
      args.push(adtPath);
      args.push("-package");
      args.push("-storetype");
      args.push("pkcs12");
      args.push("-keystore");
      args.push(certPath);
      args.push("-storepass");
      args.push("mypass");
      args.push("-target");
      args.push("native");
      args.push(exePath);
      args.push(xmlPath);
      args.push("-C");
      args.push(swfPath);
      args.push("testApp.swf");
      args.push("icons");
      nativeProcessStartupInfo.arguments = args;
      nativeProcessStartupInfo.executable = file;
      nativeProcess = new NativeProcess();
      nativeProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
      nativeProcess.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
      nativeProcess.start(nativeProcessStartupInfo);
    private function onOutputData(event:ProgressEvent):void{
       var op:String =  nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable);
       trace("output = " + op);
    private function onErrorData(event:ProgressEvent):void{
       var er:String = nativeProcess.standardError.readUTFBytes(nativeProcess.standardError.bytesAvailable);
       trace("error = " + er);
    Thanks in advance,
    Nikola

    Someone to offer a solution to this problem (if exists)?

  • When i try to restore my iPad it gets stuck a quarter along the progress bar and won't restore.

    Ok so i downloaded the 4.3.3 update and tried updating but it got stuck about a quarter of the way along the progress bar and won't move. I unplugged it and plugged it in again then tried a restore, it did the same thing, i've done it about 5 times now and it still gets stuck in the same spot each time. I put it into DFU mode and tried a restore but it still won't. Help?

    Hi Tulips 14,
    If you are having reoccuring Error 21 notices when trying to restore your iPhone, you may find the following article helpful, in particular the "Check for Hardware Issues" portion:
    Apple Support: Resolve specific iTunes update and restore errors
    http://support.apple.com/kb/TS3694
    Regards,
    - Brenden

  • I am installing the latest update on Mountain lion. ( Itunes) . Screen went light gray, no progress bar, and is been running for about two hours. Help!

    I am installing the latest update for Mountain lion (the iTunes update) . The screen went light gray, with no progress bars, and has remained that way for several hours. Help!

    In this case, hold the Power button until your computer turns off, and then, turn your Mac on again. It looks like your computer got stuck during its restart, so it shouldn't harm anything on your computer

  • Macbook Pro get grey progress bar and shuts down

    Hello All,
    I have a macbook pro and I faced this issue out of nowhere. After shutting down the system last time, when I started the system, I could hear the apple chime, apple logo appeared with grey progress bar below it. The bar will progress to 1/3 or so and it will disappear and after few seconds laptop will shut down. I tried few times but same things was happening again and again.
    After going through few support forums, I booted by pressing D to run the Apple hardware test. It wouldn't do anything at all. Apple hardware test was stuck at pass number: 1 with elapsed time of 7 seconds. All retry were the same as the first one.
    I rebooted the laptop and pressed command + R and entered in  recovery mode/recovery disk. I clicked on Disk utility and select Macintosh HDD and started disk verification. I got hundreds of errors/warning, saying Missing thread recode (id = XXXXXXX) and it suggested to repair the disk. I tried to repair the disk but after similar message, pop window appeared with message that disk cant be repaired. I exited out of it and went back to recovery menu.
    I selected Reinstall OS X Mountain Lion and went through steps and at the point where I have to select my HDD, there was just one option and I couldn't select it. It gave message that This HDD is locked. I can't start in safe mode, and can't reinstall OS X
    I believe this is because of my hard drive might have crashed. can anyone help?
    Thank you,

    It does sound like your having mechanical or other issues with your boot drive.
    If your machine is under AppleCare or warranty you can take it to them.
    If you can user service your machine, you can opt to try to see if a new drive will work and install it yourself, or have a local geek do it for you.

  • 6i Template.fmb Progress Bar and Inv Org LOV

    I am building a custom form for use with Oracle Apps.
    I have two problems:
    1. The progress indicator canvas appears after the window is closed. I do not know what is calling it or how to prevent it from poping up.
    2. I would like to use the INVSTAND parameters for org_id and I would like to set those parameters by mimicing the behavior of other windows. (If the user has not selected an inv org, they are prompted with an LOV.) Can anyone tell me how to implement this?
    I have created the form using the template.fmb file using 6i and Apps 11.5.?
    Dan

    This is kind of an old thread. But, I'm having the same problem now. When I use the windows MDI close button on a child window (called by the initial form window), the progress bar canvas is launched. I'm not even using the progress bar anywhere. Also using the TEMPLATE.fmb.
    What is the cause of this?

  • Progress bar and sql query

    Hi, first of all excuse my English.
    I have a problem that I can not solve, i implement a indeterminate progress bar for a sql query but not shown until you have completed method. I tested threads and swingworker but can't make it work.
    The pseudocode would be:
    @Action
    public void Find() {
        progressbar.setVisible(true);
        ... query ...
    }If anyone has a solution would be very grateful.

    The Find() method is automatically created by NetBeans when I select "Set Action" from the context menu of a JButton.
    NetBeans generated code is as follows:
    public MyClass { // Constructor
        initComponents();
    private void initComponents() {
        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(administration.AdministrationApp.class).getContext().getActionMap(MyClass.class, this);
        button_find.setAction(actionMap.get("Find")); // NOI18N
    @Action
    public void Find() {
    }don't exist a method actionPerformed()

  • MacBook Pro frozen on startup screen with progress bar and then it turns off

    Hello, I have a MacBook Pro 15" of early 2012 with a i5 Intel, 4GB of RAM  and a  500 GB HD.
    I was installing the new suit of Adobe, when suddenly my Mac got frozen, vertical coloured lines appeared and the image on screen went distorted. I had to reboot the Mac by holding the power button until the screen turned off and when I turned it on, the lines appeared again and it itself automatically rebooted. Then the screen (now with no vertical lines) got frozen on the startup grey screen with the apple logo and the spinning wheel for hours with no response.
    I tried to follow the steps of the official mac forums like verifying the HD with CMD+R and then Disk Utility, it says everything's fine; the same happens with CMD+S, no errors. I reinstalled Mavericks with the same CMD+R. I already reset the PRAM, SMC  and performed a Safe Boot staring up in Single user mode and Verbose Mode and nothing, the same startup screen. I made too thins thing of holding shift until the progress bar appeared.  Three days later (Today) I repeated the steps again and finally the verbose mode. Now, when I turn it on, the startup screen appears again (Apple Log and spinning wheel) with a progress bar. When it completes, the Mac turn itself off.
    if you can help me, please. I don't know what else to do. The last thing is technical service.

    Hi again ggt15,
    You can find some more information about the Recovery Partition of your hard drive here:
    OS X: About OS X Recovery
    http://support.apple.com/kb/HT4718
    It sounds like you might be trying to reinstall your copy of the operating system. If that's the case, you may also find some helpful information here:
    OS X Lion: Reinstall Mac OS X
    http://support.apple.com/kb/PH3878
    Thank you for using the Apple Support Community. Due to the nature of your issue or question you may find more information by using another one of Apple's support resources - https://expresslane.apple.com/GetproductgroupList.action.
    Cheers,
    Braden

  • HT4623 My iPhone 4 has become unresponsive during the update. It's showing a progress bar and has not moved for over half an hour can anyone help ?

    My iPhone 4 has become unresponsive during the latest update I have a progress bar about half way through the update and it hasn't moved for about an hour can anyone help???

    Hey Ali.M27,
    Thanks for the question. I understand you are experiencing issues with your iPhone during an iOS update. If your issues persist, you may need to restore your device in recovery mode:
    iOS: Unable to update or restore
    http://support.apple.com/kb/HT1808
    Thanks,
    Matt M.

  • Safari 4.0 progress bar and Top Sites bugs (?)

    Hi there,
    I am having a problem with my Safari 4 and been searching for a fix since a few days but could not find a solution, so I hope there is someone who can help me out.
    There are basically two problems, I have with Safari.
    The first one is, that since Safari 4.0 there is a new kind of a "progress bar" which changes its color and is actually at first dark and then gets more light while loading a page. My progress bar is not chaning colors at all. It just stays dark all the time.
    And the second one, is that if you have a site on you "Top Sites" and click that, it fades in, so it comes nearer and gets larger until it fits the window. So, if you go back from that site to you "Top Sites" again, it actually should fade out and move back to its old position on the "Top Sites". And again, my Safari does not do that either.
    I don't know, if that is improtant or not, but I played around with the Safari 4 beta tweaks and changed the progress bar so I have the blue one in the background of my adress bar.
    I already tried to restore my old Safari from my Programs folder with Time Machine and installed the 4.0 again but still, it does not work for me.
    I know that these are not somehow critical bugs but it would be great, if Safari would just work, as it actually should.
    So, is there a way to fix that or reset Safari?
    Thank you in advance!

    Hi
    Latest v of Glims (17) is Safari 4 compatible. Cooliris is functional, although a soon to be released upgrade will correct certain S4 related bugs. Tab Expose is not S4 compatible.
    There is no blue progress bar in Safari 4. In S4 Beta, Terminal code was used to bring that S3 feature back, however, S4 final has removed the related code. Hence, no blue progress bar. Instead, there's a spinning gear to the right of the Address Bar indicating the page is loading.
    Let Apple hear your sentiments about S4. Send feedback to Apple via the Safari Menu>Report bugs to Apple.

  • I have an iphone 4 and I have just upgraded to iOS 5. I have lost my progress bar and song repeat function, how can I get them back?

    I have an iphone 4 and I have just upgraded to iOS 5. Unlike some people, I have not really had any problems but I am really annoyed with the new music feature. I have lost my progress bar abd song repeat function. Does anyone know how I can get them back?

    Glad to hear it all works for you.
    For future reference, if your iPhone misbehaves, always try a Reset. It's painless and often solves the problem.
       Press and hold both the Sleep/Wake button and the Home button for at least ten seconds, until the Apple logo appears (ignore the Slide to Power Off option that shows up first).
    Enjoy.

  • IDS 9.0.4.2, Progress bar and frm-13008

    Hello All,
    I downloaded and installed the 10g (9.0.4.2) demos as detailed in the installguide.html.
    When trying to open a canvas (layout editor) that contains my bean for the progress bar, I receive the frm-13008 error.
    I've searched OTN and Metalink, and tried to make the changes I found on these sites, but I continue to receive the error.
    Implementation class is: oracle.forms.demos.ProgressBarPJC
    Current contents of forms90_builder_classpath: d:\oracle\10g\forms90\java\frmwebutil.jar;d:\oracle10g\forms90\java\f90all.jar;d:\oracle10g\forms90\java\jacob.jar;d:\oracle\10g\jlib\importer.jar;d:\oracle\10g\jlib\debugger.jar;d:\oracle\10g\jlib\utj90.jar;d:\oracle\10g\jlib\dfc90.jar;d:\oracle\10g\jlib\help4.jar;d:\oracle\10g\jlib\oracle_ice.jar;d:\oracle\10g\jlib\jewt4.jar;d:\oracle\10g\jlib\ewt3.jar;d:\oracle\10g\jlib\share.jar;D:\Oracle\10g\forms90\demos\progressbar\classes\progressbar.jar;d:\oracle\10g\forms90\java;
    Classpath is: d:\oracle\9i\jlib\bigraphbean.jar;d:\oracle\9i\jlib\LW_PfjBean.jar;d:\oracle\9i\jlib\bigraphbean-nls.zip
    What is the difference between progressar.jar and progressbarpjc.class?
    The bean is visibile at runtime, but no visible changes (color changes etc) appear. Any ides as to the cause for this behavior?
    Oracle must have (I hope) better documentation that what I've seen so far. Not all Forms developers have been able to jump on the Java bandwagon.
    -Chris

    Francois,
    In regards to the progress bar moving, I am supply percentages and color changes but see no effect at runtime. This includes no error messages.
    .java vs. jar, I then assume that forms would look for the .jar file then. As such the implementation class reading: oracle.forms.demos.ProgressBarPJC tells me what? That forms is expecting to see progressbar.jar, or progressbarpjc.jar, and where?
    The 10g demos are installed to D:\Oracle\10g\forms90\demos and there I have a folder named progressbar not progressbarpjc. Is this part of the issues?
    I'm glad Oracle has made using there demos so easy to setup and use.
    Thanks for your help.
    -chris

Maybe you are looking for

  • Photoshop CC really bad lagging on new rMBP

    I resently bought a new Retina MacBook Pro 13" with a nice fast 2,8 i7 proccesor and a big chunk of 16 Gb ram. After using it on my older iMac I was exited to use it on my new MacBook. But its lagging really bad. It makes it unusable for me. I don't

  • Performance problems on multi processor machine

    Hi, we are using a software written in Java (as Servlets using Tomcat 4.1.29) 1.4, which has a very poor performance. Sadly we don't have the source-codes for the application, but from the log-files we can figure out, that there is a very strong over

  • Changing service account leads to FS Repository error

    We are having a FS repository on the portal which was available in KM content. Now I have made changes in the service account for the portal ie I have changed the domain in domain/username to a new one. Now the repository in not available in KM conte

  • Can anyone help with uploading photos from iPad to Facebook.  Thanks

    Can anyone help with uploading photos fom iPad to Facebook?  Thanks

  • ACS 5.0 NFR-version ?

    Hi all, I've seen the ACS 5.0 evaluation version, so I wonder if it is also available in the NFR package ? If it hasn't already be released there, is there any date when to expect it ? How often are these NFR packages re-bundled anyway ? Thanks in ad