Results 1 to 20 of 20
  1. #1
    IYIaster is offline Member
    Join Date
    Jul 2009
    Posts
    46
    Rep Power
    0

    Default trying to use progress bar for the first time.

    I'm not sure how I need to use this progress bar. I have a bunch of threads that are doing different things like extracting files. I would like a progress bar to show up. I've been working on this for days now.......... Anyway, My main class has all of my GUI and I have another class called "extractjboss" that handles all of my threads. I have a progress bar in the main GUI class called "private javax.swing.JProgressBar jProgressBar1;" It shows up on the last page where I calling "final extractjboss t = new extractjboss();" "new Thread(t).start();" to start the threads. Now here is the code that I have in extractjboss. Everything build fine but when I run the program I get this error.
    "Exception in thread "Thread-2" java.lang.NullPointerException"
    "at setup.extractjboss.run(extractjboss.java:41)"
    "at java.lang.Thread.run(Thread.java:595)"
    "Java Result: 1"
    Just so you know I've only been working with java for two weeks so I'm still learning how everything works. Thanks for your help.

    Java Code:
    import javax.swing.filechooser.FileSystemView;
    import java.io.*;
    import Shared.*;
    import java.util.zip.*;
    import java.util.*; //import java.util.jar.*;
    import java.lang.String.*;
    import javax.swing.*;
    public class extractjboss implements Runnable {
    static JProgressBar jpb;
    static extractjboss _this;
    
    public extractjboss (){
    _this = this;
    }
        private final Object threadLock = new Object();
    
        protected final void waitForSignal() throws InterruptedException {
            synchronized (threadLock) {
                threadLock.wait();
            }
        }
        SharedInstall install = new SharedInstall();
        String curDir = System.getProperty("user.dir");
    
    
    
    // worker thread
    public void run(){
    while(true){
    for (int i = 0; i <= 100; i++){
    jpb.setValue(i);
    jpb.updateUI();
    System.out.println("actionPerformed sets jpb value to: "+i);
    try{Thread.sleep(50);} // make the process last a while
    catch (InterruptedException e){}
    }
    
    
    
            try {
                String prop = install.ReadProps("jboss");
                File[] rootDirs = File.listRoots();
                System.out.println(rootDirs.length);
                File rootDir = null;
                int compare = 0;
                for (int i = 0; i < rootDirs.length; i++) {
                    compare = rootDirs[i].compareTo(FileSystemView.getFileSystemView().getHomeDirectory());
                    if (compare < 0) {
                        rootDir = rootDirs[i];
                    }
                }
                System.out.println(rootDir);
                String command = curDir + "\\" + prop;
                System.out.println(command);
                install.runUnZip(command, rootDir);
            } catch (Throwable e) {
                e.printStackTrace();
            }
    }
    }
        protected final void signalEndWait() {
            synchronized (threadLock) {
                threadLock.notify();
            }
    
        }
    }
    Thanks for all the help

  2. #2
    RamyaSivakanth's Avatar
    RamyaSivakanth is offline Senior Member
    Join Date
    Apr 2009
    Location
    Chennai
    Posts
    841
    Rep Power
    6

    Default

    Hi,
    Without giving the complete code it is impossible to find out the errors.

    "Exception in thread "Thread-2" java.lang.NullPointerException"
    "at setup.extractjboss.run(extractjboss.java:41)"
    "at java.lang.Thread.run(Thread.java:595)"
    error says 41 line.So ,u are trying to call String prop = install.ReadProps("jboss");

    Attach the SharedInstall code also and other related code
    Ramya:cool:

  3. #3
    IYIaster is offline Member
    Join Date
    Jul 2009
    Posts
    46
    Rep Power
    0

    Default

    All of my threads and everything works fine. It wasn't until I added the progress bar code to extractjboss that I started getting errors.

  4. #4
    IYIaster is offline Member
    Join Date
    Jul 2009
    Posts
    46
    Rep Power
    0

    Default

    here is the shared install file hope this helps.
    Java Code:
    package Shared;
    
    import java.io.*;
    import java.util.*; //import java.util.jar.*;
    import java.util.zip.*;
    
    import java.text.*;
     
    public class SharedInstall {
    	public int spaceTotal(String space) {
    		space = space.replaceAll("\\s+", " ");
    		String[] string = space.split(" ");
    		int counter = 0;
    		String Output = null;
    		String[] split = null;
    		int total = 0;
    		int[] size = new int[50];
    		int Size = 0;
    
    		for (int val = 0; val < string.length; val++) {
    			if (string[val] != null) {
    				counter += 1;
    
    				if (counter == 4) {
    					Output = string[val];
    
    					if (Output.indexOf("G") > -1) {
    						split = Output.split("G");
    						size[Size] = Integer.parseInt(split[0]);
    						Size += 1;
    					}
    
    				}
    
    				if (counter == 7)
    					counter = 0;
    
    			}
    
    		}
    
    		for (int i = 0; i < size.length; i++)
    			total = total + size[i];
    
    		return total;
    	}
    
    	public double getcpu(String command) throws IOException {
    		String line = null;
    		String output = null;
    		String numcpu = null;
    		DecimalFormat oneDigit = new DecimalFormat("#,##0.0");//
    
    		try {
    			Process process = Runtime.getRuntime().exec(command);
    			InputStream is = process.getInputStream();
    			InputStreamReader isr = new InputStreamReader(is);
    			BufferedReader br = new BufferedReader(isr);
    			while ((line = br.readLine()) != null) {
    				if (line.indexOf("Mhz..") > -1) {
    					output = line;
    				} else if (line.indexOf("Total CPUs..") > -1) {
    					numcpu = line;
    				}
    
    			}
    			br.close();
    			isr.close();
    			is.close();
    
    		} catch (Throwable e) {
    			e.printStackTrace();
    		}
    
    		// return output;
    		String[] cpuinfo = output.split("");
    		String[] cputimes = numcpu.split("");
    		int gotcpu = 0;
    		int gotone = 0;
    		ArrayList<String> array = new ArrayList<String>();
    		ArrayList<String> cpunum = new ArrayList<String>();
    
    		for (int i = 0; i < cpuinfo.length; i++) {
    			if (cpuinfo[i].indexOf(".") > -1) {
    				gotone = 1;
    			} else if (gotone > 0) {
    				array.add(cpuinfo[i]);
    			}
    		}
    		for (int i = 0; i < cputimes.length; i++) {
    			if (cputimes[i].indexOf(".") > -1) {
    				gotcpu = 1;
    			} else if (gotcpu > 0) {
    				cpunum.add(cputimes[i]);
    			}
    		}
    		String cpu = "";
    		String cpus = "";
    		String[] cpuholder = (String[]) array.toArray(new String[array.size()]);
    		String[] cpunumholder = (String[]) cpunum.toArray(new String[cpunum
    				.size()]);
    		for (int i = 0; i < cpuholder.length; i++) {
    			cpu = cpu + cpuholder[i];
    		}
    		for (int i = 0; i < cpunumholder.length; i++) {
    			cpus = cpus + cpunumholder[i];
    		}
    		double CPU = Integer.parseInt(cpu);
    		double CPUS = Integer.parseInt(cpus);
    		double CPUSpeed = Double.parseDouble(oneDigit.format(CPU / 1000));
    		CPUSpeed = CPUSpeed * CPUS;
    		return CPUSpeed;
    	}
    
    	public int ramSize(String command) throws IOException {
    
    		String line = null;
    		ArrayList<String> array = new ArrayList<String>();
    
    		try {
    			Process process = Runtime.getRuntime().exec(command);
    			InputStream is = process.getInputStream();
    			InputStreamReader isr = new InputStreamReader(is);
    			BufferedReader br = new BufferedReader(isr);
    			int i = 0;
    			while ((line = br.readLine()) != null) {
    				if (line.indexOf("RAM") > -1) {
    					array.add(line);
    					i++;
    				}
    			}
    			br.close();
    			isr.close();
    			is.close();
    		} catch (Throwable e) {
    			e.printStackTrace();
    		}
    		String output = "";
    		output = array.toString();
    
    		String space = output;
    		space = space.replaceAll("\\s+", " ");
    		String[] string = space.split(" ");
    		String Output = null;
    		String[] split = null;
    		int total = 0;
    		int[] size = new int[50];
    		Output = string[string.length - 1];
    		split = Output.split("M");
    		size[0] = Integer.parseInt(split[0]);
    		total = total + size[0];
    
    		return total;
    	}
    
    	public void runCommand(String command) throws IOException {
    
    		try {
    			Process process = Runtime.getRuntime().exec(command);
    			process.waitFor();
    		} catch (Throwable e) {
    			e.printStackTrace();
    		}
    	}
    
    	@SuppressWarnings("unchecked")
    	public void runUnZip(String command, File rootDir) throws IOException {
    		try {
    			int BUFFER = 2048;
    			File file = new File(command);
    			BufferedOutputStream dest = null;
    			BufferedInputStream is = null;
    			ZipEntry entry;
    			ZipFile zipfile = new ZipFile(file);
    			Enumeration e = zipfile.entries();
    			while (e.hasMoreElements()) {
    				entry = (ZipEntry) e.nextElement();
    				System.out.println("Extracting: " + entry);
    				is = new BufferedInputStream(zipfile.getInputStream(entry));
    				int count;
    				byte data[] = new byte[BUFFER];
    				String fileName = rootDir + entry.getName();
    				File outFile = new File(fileName);
    				if (entry.isDirectory()) {
    					outFile.mkdirs();
    					System.out.println("Create Folder " + outFile);
    				} else {
    					FileOutputStream fos = new FileOutputStream(outFile);
    					dest = new BufferedOutputStream(fos, BUFFER);
    					while ((count = is.read(data, 0, BUFFER)) != -1) {
    						dest.write(data, 0, count);
    					}
    					dest.flush();
    					dest.close();
    					is.close();
    				}
    			}
    		} catch (Throwable e) {
    			e.printStackTrace();
    		}
    	}
    
        public String ReadProps(String property) {
            String prop = null;
            try {
                Properties p = new Properties();
                p.load(new FileInputStream("filelist.props"));
                prop = p.getProperty(property);
            } catch (Exception e) {
                e.printStackTrace();
            }
                return prop;
        }
    }

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Have you gone through the Sun tutorial on How To Use Progress Bars? If not, I highly suggest that you give it a look as it likely has a decent solution for you.

  6. #6
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    I agree with Fubarable -- The java tutorials are both easy and the best way to see how implementation was intended.

  7. #7
    IYIaster is offline Member
    Join Date
    Jul 2009
    Posts
    46
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Have you gone through the Sun tutorial on How To Use Progress Bars[/URL]? If not, I highly suggest that you give it a look as it likely has a decent solution for you.
    Yes I've tried using that tutorial and for some reason when I try and load the example I get alot of errors. I don't know if it's because I'm using netbeans or what but it's not working.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    when I try and load the example I get alot of errors.
    Often that's because of either having the wrong package name or not downloading another file that the sample code depends on. If you'd like you could tell us what errors you're having and perhaps we can help you to get it to work.

  9. #9
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    I tried to write a very simple example. Please let me know if it helps -- I use netbeans, its great :)

    Java Code:
    import javax.swing.JFrame;
    import javax.swing.JProgressBar;
    
    public class Main {
        public static void main(String[] args) {
            new Main();
        }
    
        private JProgressBar progressBar;
        private int progress = 0;
    
        public Main(){
            //Make a progress bar, and set the maximum value
            progressBar = new JProgressBar();
            progressBar.setMaximum(100);
    
            //Make a window, add the progressbar, make visible
            JFrame window = new JFrame();
            window.add(progressBar);
            window.setSize(300, 100);
            window.setVisible(true);
    
            //create a new thread running a ProgressMonitor and start it
            new Thread(new ProgressMonitor()).start();
        }
    
        /**
         * A class that implements Runnable can be run as a separate
         * thread. It must have a method called run()
         */
        class ProgressMonitor implements Runnable{
            public void run() {
                //run untill 100% complete
                while(progress < 100){
                    //update the progressbar
                    progressBar.setValue(++progress);
                    try {
                        //Sleep for .25 second
                        Thread.sleep(250);
                    } catch (InterruptedException ex) {}
                }
                System.out.println("We're done!");
            }
        }
    }
    Please play with this, and if you still don't understand, just ask! :D

  10. #10
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Oh yeah, one more thing. Your code is MESSY! Not to worry -- in netbeans, go to the 'Source' menu and select 'Format'.
    Ctril Shift F works too -- It will make things much easier :)

  11. #11
    IYIaster is offline Member
    Join Date
    Jul 2009
    Posts
    46
    Rep Power
    0

    Default

    Thank you so much for breaking it down. I'm now able to get my progress bar to move. But, How do I get it to monitor the progress of my thread that is extracting the files?

  12. #12
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Very good question. It depends a lot on how you 'want' to do it, as there are many ways, but here is my idea:

    Lets say you are going to do something to 75 files. If you know that in advance, then simply initialize the progress bar with a max of 75. After each file is complete, increment an integer (called 'progress' in my example) by 1. If the monitor runs every second or so, it simply needs to set the progress bar to the value of 'progress'.

    If you are doing something to one big file, then you could do it by file size. Lets say the file is 230 megabytes. Set the prog. bar max to 230, then increment the 'progress' variable every megabyte or so.

    I suggest you only update the progress bar every second or so, because more than that isn't really needed.

    You can also set progressbar text if desired -- look at the java api for JProgressBar to see a list of all the neat stuff you can do with it (i.e. display a percent, make it vertical, etc...

    When you want to reset it for another pass, just call:
    Java Code:
    myProgressBar.setValue(0);

  13. #13
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Also -- it depends on where your thread is written -- if its written in the same class as your main code (like my example) then you can do as I did and simply look at class-wide variables. Notice how 'progress' was declared in the class Main, but it was used in the class ProgressMonitor which was (inside) Main. If your code is similar, you can do it in this way. If your thread is a totally different file (a different document), then you can use global variables or pass a reference to the thread class upon instantiation.

  14. #14
    IYIaster is offline Member
    Join Date
    Jul 2009
    Posts
    46
    Rep Power
    0

    Default

    Well, really the only thing I know for sure it that during the install there are 11,480 lines of system.out (most are files being extracted) is there a way to monitor the progress this way?

  15. #15
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Sure! Why not init the progress bar wit 11480, then after each print increment the progress? That would be a quick and dirty way to make it work :D Progress bars are not an exact science -- as long as they convey the general idea, they have done their job. Some processes cannot be easily represented via progress bar, and thats why someone invented the pulsing or swirling progbar -- in situations where you cannot assign some numeric value to progress, this is often your only option.

  16. #16
    IYIaster is offline Member
    Join Date
    Jul 2009
    Posts
    46
    Rep Power
    0

    Default

    Ok thanks so much for your help. I've been working on this for a long time and finally starting to understand. I wish everyone here was as nice as you. Well I set the line count by doing this.

    Java Code:
    int linecount = jTextArea1.getLineCount();
    Since I'm already sending all output to a text area I figured it would be easy just to use this code. Now what would I use to tell the progress bar one line is worth what and what line its on?

  17. #17
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Ok, so heres the deal. The key things you need for a progress bar to work:
    - Minimum (usually 0)
    - Maximum (if you don't know, then you cannot give exact progress)
    - Current (how far along)
    So if the output is always going to be apporx. 12000 lines, then using getLineCount() should be just fine. Simple make a monitor that keeps looking at your linecount variable. Something like this:
    Java Code:
    class ProgressMonitor implements Runnable {
    
            public void run() {
                while (true) {
                    progressBar.setValue(linecount);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                    if (linecount > 11400) {
                        progressBar.setValue(11400);
                        break;
                    }
                }
            }
    }
    When it hits the predetermined end, the thread terminates automatically. If you need to run it again, just run this line again:
    Java Code:
    new Thread(new ProgressMonitor()).start();
    which will make a brand new thread for you.
    Last edited by quad64bit; 07-23-2009 at 09:25 PM.

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    One concern with the code above is that it's not thread-safe. The Thread.sleep is done in a background thread, as it should be, but setting the progress monitor's value needs to be done on the EDT, the main Swing thread else you're liable to have one of those tricky errors that occur 3-4 times out of 100 that are almost impossible to debug. To fix this, simply queue the method call on the EDT with SwingUtilities.invokeLater and a Runnable object:

    Java Code:
          while (progress < 100) {
            SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                progressBar.setValue(++progress);
              }
            });
            try {
              Thread.sleep(250);
            } catch (InterruptedException ex) {

  19. #19
    IYIaster is offline Member
    Join Date
    Jul 2009
    Posts
    46
    Rep Power
    0

    Default

    Thanks for the help finally was able to get this working.

  20. #20
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

Similar Threads

  1. How to use Progress bar
    By LankanSniper in forum AWT / Swing
    Replies: 3
    Last Post: 03-25-2009, 10:44 AM
  2. Updating a progress bar from the UI thread
    By Java Tip in forum SWT Tips
    Replies: 0
    Last Post: 07-11-2008, 04:52 PM
  3. how to implement progress bar .....
    By roshithmca in forum AWT / Swing
    Replies: 1
    Last Post: 03-06-2008, 04:18 PM
  4. Console Progress Bar
    By new_2_java in forum New To Java
    Replies: 1
    Last Post: 02-16-2008, 02:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •