About JProgressBar

Hi,
If my application has a process which has unknown execution time which depends on the file chosen by the user. If i want to add a progress bar to reflect the progress of the process, how can i do that since i don't know the length of the process?
thx

excerpt from the API docs at http://java.sun.com/j2se/1.4.1/docs/api/javax/swing/JProgressBar.html
quote
To indicate that a task of unknown length is executing, you can put a progress bar into indeterminate mode. While the bar is in indeterminate mode, it animates constantly to show that work is occurring. As soon as you can determine the task's length and amount of progress, you should update the progress bar's value and switch it back to determinate mode.
unquote
and quote
Here is an example of putting a progress bar into indeterminate mode, and then switching back to determinate mode once the length of the task is known:
progressBar = new JProgressBar();
...//when the task of (initially) unknown length begins:
progressBar.setIndeterminate(true);
...//do some work; get length of task...
progressBar.setMaximum(newLength);
progressBar.setValue(newValue);
progressBar.setIndeterminate(false);
For complete examples and further documentation see How to Monitor Progress, a section in The Java Tutorial.
unquote
Ulrich

Similar Messages

  • Quick question about JProgressBar...

    Hi all,
    i have a little problem with the JProgressBar-object.The thing is that I would like to show the progress of the loading of my program, so that the user is not bored :) What I would like to do is to watch how the contructor initializes and to display this progress in a JProgressBar. I would like to show percentage of finished download instead of just having the thing moving left-right in progress bar. I have read a tutorial on java�s homepage, but it is not helping. I am not using any threads for initializing the constructor. Any help would be very appriciated.
    Thank you

    If you are using java 1.4, you should look at "indeterminate" progress bars - they are for situations where you want to show progress but you don't have any real solid mathematical way you can calculate your percentage done.

  • JProgressBar inside JDialogBox doesn't show up.

    Hi,
    I have a problem and kind of stuck.
    Here is the scenario.....
    Inside my actionPerformed method I create an instance of a class that extends java.lang.Thread and inside this class run method I create an instance of another class that extends JDialog that contains a JProgressBar. Now when a user clicks a button on the main application window the actionPerformed gets executed and it shows a JProgressBar and then continues the execution of the actionPerformed method while the JProgressBar keeps on updating the status. But the problem is that the JDialog shows up but the JProgressBar inside it doesn't even show. here is the code snippet I am using
    public void actionPerformed(ActionEvent e)
    //some code here
    //class extends Thread and creates JDialog with JProgressBar in it
    //JDialogBox with JProgressBar in it shows here
    t = new ProgressThread();
    t.start();
    //some other code I do some other processing
    //here I am hidding and destroying the JProgressBar
    //inside the reset method I hide the JDialog and set it to null
    t.reset();
    //some more code
    } //end of actionPerform
    Now my problem is that JDialogBox does pop-up but the JProgressBar in it doesn't show. Any ideas what I am doing wrong. I even tried to create the instance of JDialog directly instead of using a separate Thread but it didn't work either.
    Thanks for any help

    The point being, AWT and Swing are, in general, not thread-safe.
    You must not do anything that modifies the appearance of any visible Swing component, such as JProgressBar, from your thread. This must be done in the AWT Event Dispatch Thread. But when the components are not visible, like when you are building your GUI and haven't set it to visible yet, this doesn't apply.
    What I do, when my threads need to update the GUI, is to create a Runnable to do it, then queue that to the AWT Event Dispatch Thread for execution by calling SwingUtilities.invokeLater(). Other people use this SwingWorker class.
    Note that event listener methods are called in the AWT Event Dispatch Thread, so you need to worry about this only in your own thread.
    It is said there are some Swing components that are thread-safe. Given the typical use of JProgressBar, too bad it isn't one of them.

  • Prob with JProgressBar and JButton

    Hi, hopefully someone can help me. I have an applet that does some stuff and when it starts the work, it creates a new JFrame with 2 progress bars (JProgressBar), an ok Jbutton and a cancel JButton. The progress bars update properly, thats not an issue, my problem is that when you click either of the buttons, they don't create an actionEvent until the work is completed, which is ok for the OK button but makes the cancel button pretty useless. I have tried suggested work arounds using SwingWorker and the event dispatching thread for similar probs other people have posted on here but with no success. I don't really know a lot about threads which doesn't really help!! Is it likely to be a thread problem or something to do with event queue which has also been suggested to me. Any help would be greatly appreciated.

    public class ProgressDialog extends JDialog implements Runnable
    private JProgressBar progressBar, totalBar;
    private JButton ok, cancel;
    public ProgressDialog()
    setTitle(dialogTitle);
    setBounds(350,300,300,120);
    //setSize(300,100);
    Container contentPane = getContentPane();
    FlowLayout flow = new FlowLayout();
    contentPane.setLayout(flow);
    JLabel label1 = new JLabel(" Upload progress: ");
    contentPane.add(label1);
    progressBar = new JProgressBar(0,100);
    progressBar.setValue(0);
    progressBar.setStringPainted(true);
    contentPane.add(progressBar);
    JLabel label2 = new JLabel(" Total progress: ");
    contentPane.add(label2);
    totalBar = new JProgressBar();
    totalBar.setValue(0);
    totalBar.setStringPainted(true);
    contentPane.add(totalBar);
    ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    contentPane.add(ok);
    cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    contentPane.add(cancel);
    setVisible(true);
    setResizable(false);
    Thats near enough the whole class now. Thanks

  • How refresh JProgressBar display ?

    I use a JProgressBar in my program but the display of it is never refresh even if I use updateUI method.
    Do you know a way to have a real refresh of my display ?

    you need to implement a model and associate it to the GUI:
    take a look in the BoundedRangeModel class....
    http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html
    the code bellow is a large one I used in a class about Model-View-Controller paradigm.. It is big, but I hope it help you...
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import javax.swing.event.*;
    * This test class demonstrates the control-model-view programing paradigm
    * @version 1.0 beta
    * @author Felipe Gaucho
    * @date september 2000
    public class CMV
         Model model = null;
         static public void main(String[] args)
              try
                   new CMV(Integer.parseInt(args[0]));
              catch(Exception error)
                   new CMV(1000); // Default test value
         CMV(int limit)
              // Creates a data model
              model = new Model(limit);
              // Set the model observers
              model.addObserver(new SwingView(model));
              model.addObserver(new AwtView());
              // Set a controller to the model
              Control controller = new Control(model);
    // VIEW
    class SwingView extends JFrame implements Observer
         JProgressBar progress = null;
         JSlider slider = null;
         SwingView(Model model)
              super("Swing Viewer");
              try
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                   //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch(Exception error)
              // Creates a new progress bar indicating the model status
              progress = new JProgressBar(model);
              progress.setStringPainted(true);
              // Creates a new slider providing an interactive way of model data modifying
              slider = new JSlider(model);
              slider.setVisible(false);
              // Swing layout mounting
              getContentPane().setLayout(new BorderLayout(2,2));
              getContentPane().add(new JLabel("Swing do it better!", JLabel.CENTER), BorderLayout.CENTER);
              getContentPane().add(progress, BorderLayout.SOUTH);
              getContentPane().add(slider, BorderLayout.NORTH);
              setSize(250,100);
              setLocation(50,50);
              setVisible(true);
         public void update(Observable model, Object component)
              if( ! slider.isVisible() && ((Model)model).getValue() == ((Model)model).getMaximum())
                   slider.setVisible(true);
              progress.repaint();
    // VIEW
    class AwtView extends Frame implements Observer
         Label valueInfo = new Label("", Label.CENTER);
         AwtView()
              // Set title and layout type
              super("Awt Viewer");
              setLayout(new BorderLayout());
              // Set the layout components
              add(new Label("Awt use light weight components!", Label.CENTER), BorderLayout.CENTER);
              valueInfo.setFont(new Font("Serif",Font.BOLD+Font.ITALIC,32));
              add(valueInfo, BorderLayout.SOUTH);
              // Display it
              setSize(250,100);
              setLocation(350,50);
              setVisible(true);
         public void update(Observable model, Object component)
              valueInfo.setText(((Model)model).getValue() + " / " + ((Model)model).getMaximum());
    // MODEL
    class Model extends Observable implements BoundedRangeModel
         private int value = 0;
         private int minimum = 0;
         private int maximum = 0;
         Model(int maximum)
              this(0, maximum, 0);
         Model(int minimum, int maximum, int initialValue)
              this.minimum = minimum;
              this.maximum = maximum;
              this.value = initialValue;
         public void addChangeListener(ChangeListener x) {}
         public int getExtent() {return 1;}
         public int getMaximum() {return maximum;}
         public int getMinimum() {return minimum;}
         public int getValue() {return value;}
         public boolean getValueIsAdjusting (){return true;}
         public void removeChangeListener(ChangeListener x){}
         public void setExtent(int newExtent) {}
         public void setMaximum(int newMaximum) {}
         public void setMinimum(int newMinimum) {}
         public void setRangeProperties(int value, int extent, int min, int max, boolean adjusting) {}
         public void setValue(int value)
              this.value = value;
              setChanged();
              notifyObservers();  // <== Notify the observers about the model data changing
         public void setValueIsAdjusting(boolean b) {}
    // CONTROL
    class Control
         private Model model = null;
         Control(Model model)
              this.model = model;
              int limit = model.getMaximum();
              for(int i=0; i<limit; i++)
                   model.setValue((model.getValue())+1);
    }

  • JProgressBar in JTable overwrites cell bounds

    Problem: When the user resizes the table (during a update) so that the entire JProgressBar will no longer fit in the cell, the text of the JProgressBar will overwrite its surrounding controls.
    Sample code:
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    public class Main extends JFrame {
    public Main() {
    super("TableModel JProgressBar Demonstration");
    // create our own custom TableModel
    DownloadTableModel downloadModel = new DownloadTableModel();
    JTable table = new JTable(downloadModel);
    // add rows to our TableModel, each row is represented as a Download object
    downloadModel.addDownload(new Download("linuxmandrake.zip", 1234567));
    downloadModel.addDownload(new Download("flash5.exe", 56450000));
    downloadModel.addDownload(new Download("jdk1.2.2-007.zip", 20000000));
    // render the columns with class JProgressBar as such
    ProgressBarRenderer pbr = new ProgressBarRenderer(0, 100);
    pbr.setStringPainted(true);
    table.setDefaultRenderer(JProgressBar.class, pbr);
    // increase the height of the rows a bit
    table.setRowHeight((int) pbr.getPreferredSize().getHeight());
    // create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    // add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(new JButton("Spacer"), BorderLayout.SOUTH);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public static void main(String[] args) {
    Main main = new Main();
    main.pack();
    main.setVisible(true);
    // a simple object that holds data about a particular download
    // it starts a thread and increases the progress of "downloading"
    // in a random manner
    class Download extends Observable implements Runnable {
    private Thread thisThread;
    private String filename;
    private int filesize;
    private float progress;
    public Download(String filename, int filesize) {
    this.filename = filename;
    this.filesize = filesize;
    progress = 0.0f;
    thisThread = new Thread(this);
    thisThread.start();
    public String getFilename() { return filename; }
    public int getFilesize() { return filesize; }
    public float getProgress() { return progress; }
    public String toString() {
    return "[" + filename + ", " + filesize + ", " + progress + "]"; }
    public void run() {
    Random r = new Random();
    int count = 0;
    while (count < filesize) {
    int random = Math.abs(r.nextInt() % 100000);
    count += random;
    if (count > filesize) count = filesize;
    progress = ((float) count / filesize) * 100;
    // notify table model (and all other observers)
    setChanged();
    notifyObservers(this);
    try { thisThread.sleep(500); } catch(InterruptedException e) { }
    class DownloadTableModel extends AbstractTableModel implements Observer {
    // holds the strings to be displayed in the column headers of our table
    final String[] columnNames = {"Filename", "Filesize", "Progress"};
    // holds the data types for all our columns
    final Class[] columnClasses = {String.class, Integer.class, JProgressBar.class};
    // holds our data
    final Vector data = new Vector();
    // adds a row
    public void addDownload(Download d) {
    data.addElement(d);
    // the table model is interested in changes of the rows
    d.addObserver(this);
    fireTableRowsInserted(data.size()-1, data.size()-1);
    // is called by a download object when its state changes
    public void update(Observable observable, Object o) {
    int index = data.indexOf(o);
    if (index != -1)
    fireTableRowsUpdated(index, index);
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.size();
    public String getColumnName(int col) {
    return columnNames[col];
    public Class getColumnClass(int c) {
    return columnClasses[c];
    public Object getValueAt(int row, int col) {
    Download download = (Download) data.elementAt(row);
    if (col == 0) return download.getFilename();
    else if (col == 1) return new Integer(download.getFilesize());
    else if (col == 2) return new Float(download.getProgress());
    else return null;
    public boolean isCellEditable(int row, int col) {
    return false;
    // a table cell renderer that displays a JProgressBar
    class ProgressBarRenderer extends JProgressBar implements TableCellRenderer {
    public ProgressBarRenderer() {
    super();
    public ProgressBarRenderer(BoundedRangeModel newModel) {
    super(newModel);
    public ProgressBarRenderer(int orient) {
    super(orient);
    public ProgressBarRenderer(int min, int max) {
    super(min, max);
    public ProgressBarRenderer(int orient, int min, int max) {
    super(orient, min, max);
    public Component getTableCellRendererComponent(
    JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    setValue((int) ((Float) value).floatValue());
    return this;
    }

    I do not have an answer for you.
    However, I did skim through a solution to your problem. Since it didn't solve my problem at the time, I didn't try out the code.
    In the book "Core Web Programming", Second Edition, Marty Hall and Larry Brown, Sun Microsystems Press, they do discuss making a progress bar synchronize with a file download and why you have to make it multi-threaded.
    If you can head over to your bookstore, it's Chapter 15.6 and consists of about two and a half pages. Even better, the example's source code is available for free on their web site at:
    http://www.corewebprogramming.com
    Click on the hypertext link to Chapter 15, then scroll down and grab FileTransfer.java near the bottom of the page.
    Hope this at least points you in the right direction, but I admit I wouldn't even allow the user to resize the table containing the progress bar to begin with. If I absolutely had to, I'd force the progress bar thread to reset itself each time it received a window-resizing event.

  • Assistance in programming a splash screen with a JProgressbar?

    I want to implement a Splash screen with a JProgress Bar showing that its loading. Anyone can provide any hints and ideas on how to do it.
    I manage to do a splash screen with just a simple image and using timer to control it but now i want to add in the progress bar. And now i'm stuck. had a look through the JProgressBar and it looks hard.
    cheers

    >
    I felt my question was specific enough. >Live and (hopefully) learn.
    >
    ..Surely software developers have heard of splash screen and know what it is. It is a start up screen that pops up before any application starts.>JWS can provide the same basic 'download with progress' functionality as a 'start up splash' might do, for functionalities that are not even supplied before the app. is on-screen, which is why I was asking for clarification about whether you meant 'before start-up' or ..something else.
    BTW - did you actually notice the two methods I pointed to, that provide splash/loading progress for an application start-up?
    >
    Ever used Eclipse IDE or Netbeans? If you have you would of know what i meaning. >Sure I've seen them. It was some time ago though, and all I recall was a splash image, no progress bar.
    Had you ever deployed application resources lazily? Seen an app. that does a long running process such as DB interrogation or report generation with a progress dialog? There are many purposes that might fit the general description of providing something for the user to look at, during a long-running process.
    The world is not as small as you seem to think.
    >
    What my questions is how do you code that splash screen, combining a progress bar onto the splash.>Well CB gave you the 'google' for the term, and you seemed to think that was helpful, so see how you go with it..

  • Question about the EDT

    Hi everybody,
    Here my issue: I have to write a little something about EDT and the use of SwingUtilities to avoid common issues with the use of Swing. Sure of my knowledge I wrote a little exemple using a progressBar to show how it doesn't work when you don't use SwingUtilities :
    import javax.swing.JDialog;
    import javax.swing.JProgressBar;
    public class UITesting{
        public static void          main                                            ( String[] args ) {
            JProgressBar    jProgressBar    =   new JProgressBar(0, 100) ;
            jProgressBar.setValue(0);
            jProgressBar.setStringPainted(true);
            JDialog         dialog          =   new JDialog() ;
            dialog.setSize(400, 70) ;
            dialog.setContentPane(jProgressBar) ;
            dialog.setLocationRelativeTo(null) ;
            dialog.setVisible(true);
            int flag = 0 ;
            for (int i = 0 ; i < 100000 ; i++) {
                System.out.println(i);
                if ( i%1000 == 0 ) {
                    jProgressBar.setValue(++flag);
                    System.out.println("Increase ProgressBar " + flag);
    }And surprise (at least for me)... it's working... means that my ProgressBar increase well...
    So I write an exemple closer to reality
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    public class UITesting{
        public static void          main                                            ( String[] args ){
            final JProgressBar    jProgressBar    =   new JProgressBar(0, 100) ;
            jProgressBar.setValue(0);
            jProgressBar.setStringPainted(true);
            JButton         start           =   new JButton("Start") ;
            start.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int flag = 0 ;
                    for (int i = 0 ; i < 100000 ; i++) {
                        System.out.println(i);
                        if ( i%1000 == 0 ) {
                            jProgressBar.setValue(++flag);
                            System.out.println("Increase ProgressBar " + flag);
            JPanel          panel           =   new JPanel() ;
            panel.add(start) ;
            panel.add(jProgressBar) ;
            JDialog         dialog          =   new JDialog() ;
            dialog.setSize(400, 70) ;
            dialog.setContentPane(panel) ;
            dialog.setLocationRelativeTo(null) ;
            dialog.setVisible(true);
    }That time it's perfect, the ProgressBar doesn't work, it going from 0 to 100% at the end of my for loop and the button freeze during the process, I can illustrate my point and introduce the use of SwingUtilities... But why it's working in my first exemple?
    I know that a call to an ActionListener in a Swing composant insure that the code specified is executed in EDT, but I still can't get it? Someone can help me to understand that ?
    thx in advance,
    yannig
    Edited by: yannig on 24 mars 2011 10:57

    Hi,
    [url http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html]Worker Threads and SwingWorker
    When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.swing.SwingWorker.
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import javax.swing.*;
    public class UITesting2 {
      private SwingWorker<Void, Void> worker;
      public JComponent makeUI() {
        final JProgressBar jProgressBar = new JProgressBar(0, 100);
        jProgressBar.setValue(0);
        jProgressBar.setStringPainted(true);
        final JButton start = new JButton("Start") ;
        start.addActionListener( new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            start.setEnabled(false);
            worker = new SwingWorker<Void, Void>() {
              @Override
              public Void doInBackground() throws InterruptedException {
                int current = 0;
                int lengthOfTask = 1024;
                while (current<=lengthOfTask && !isCancelled()) {
                  Thread.sleep(5);
                  setProgress(100 * current / lengthOfTask);
                  current++;
                return null;
              @Override public void done() {
                start.setEnabled(true);
            worker.addPropertyChangeListener(
                new ProgressListener(jProgressBar));
            worker.execute();
        JPanel panel = new JPanel();
        panel.add(start);
        panel.add(jProgressBar);
        return panel;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new UITesting2().makeUI());
        f.setSize(400, 70);
        f.setVisible(true);
    class ProgressListener implements PropertyChangeListener {
      private final JProgressBar progressBar;
      ProgressListener(JProgressBar progressBar) {
        this.progressBar = progressBar;
        this.progressBar.setValue(0);
      @Override public void propertyChange(PropertyChangeEvent evt) {
        String strPropertyName = evt.getPropertyName();
        if ("progress".equals(strPropertyName)) {
          progressBar.setIndeterminate(false);
          int progress = (Integer)evt.getNewValue();
          progressBar.setValue(progress);
    }

  • JProgressBar - monitoring progress of a method in another Object.

    Hi all,
    I've been three days trying to make a JProgressBar work. I know how to use them but not in this case. I'll try to explain the code instead of making you read it.
    -I have a JProgressBar in a JDialog.
    -In the constructor of this class I create a new instance of a Object, call it Processor for example, and i run a method start() on it.
    -This method execute a number of SQL statment and i want to monitor them in the JProgressBar.
    I've followed the official tutorial but it doesnt work for me, I have no idea how to do it beacause i don't know how to refresh the Task process property from outside the doInBackgroundMethod. I also tried to create 2 SwingWorker, run the Processor.run() in one of them, an in run() update a "satic int progress" in each iteration, then from the other SwingWorker i check the Procesor.progress to invoke the setProgress() method.
    I have realised that when debugging sometime it works, so i supposed is something about concurrency, I don't know, please help.
    Thank you in advanced.

    the processor is a runnable, right? then:
    MyDialog extends JDialog{
    private final JProgressBar progressBar= new JProgressBar()
    MyDialog(){...}
    private void init(){
    new SwingWorker<Void,Object>(){
    public Void doInBackground(){
    String sql1=...
    Object o = execute sql1
    publish(o);
    ... do the same with other sql queries
    return null;
    public void process(List<Object> chunks){
    //update progressbar
    //this method will be called using coalescence, so maybe you execute 3 queries, and this method gets called just once, and in this case 'chunks.size()==3'
    public void done(){
    //make sure that the progress is complete, the last chunks may have not been processed through process() method
    progressBar.setValue(100%) // I dont remember the syntax for this
    Edited by: thrawnkb on Jun 3, 2009 3:36 PM

  • JProgressBar pb

    why this code doesn't work ???
    //initialise button ...
    JButton action = new JButton("go");
    JProgressBar progressBar = new JProgressBar();
    action.addActionListener(this);
    public void actionPerformed(ActionEvent arg0)
              if(arg0.getSource() == action)
    showProgressBar(true);
    try
                        Thread.currentThread().sleep(3500);
              } catch (InterruptedException e1)
                        e1.printStackTrace();
                   //showProgressBar(false);
    public void showProgressBar(boolean state)
              progressBar.setString("Working ...");
              progressBar.setIndeterminate(state);
              progressBar.setStringPainted(state);
    in fact , the problem is the JProgressBar only start after the sleep ( if i put showProgressBar(false) in comment ) and not while .
    regards,vashuu

    In swing, the rule is that you may only update a gui via the event dispatch thread. You put it to sleep in your code with 'Thread.currentThread().sleep(3500);' so no updates are possible until the event queue clears down to the update request. To be able to update the gui start and run your process in another thread. This will leave the edt free to process your update requests as they are received. Torgil has given a pointer to the entry-point resource to learn about this.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ProgressBarTest extends JPanel
        JProgressBar progressBar;
        JButton start;
        boolean continueTask;
        public ProgressBarTest()
            initComponents();
            continueTask = false;
            setLayout(new BorderLayout());
            JPanel panel = new JPanel();
            panel.add(start);
            add(panel, "North");
            panel = new JPanel();
            panel.add(progressBar);
            add(panel, "South");
        private void initComponents()
            progressBar = new JProgressBar(JProgressBar.HORIZONTAL,0,100);
            progressBar.setStringPainted(true);
            Dimension d = progressBar.getPreferredSize();
            d.height = 20;
            progressBar.setPreferredSize(d);
            start = new JButton("start");
            start.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    System.out.println("in listener: isEventDispatchThread = " +
                                       SwingUtilities.isEventDispatchThread());
                    startProcess();
        private void startProcess()
            if(continueTask)
                return;
            new Thread(new Runnable()  // not the event dispatch thread
                public void run()
                    System.out.println("in process : isEventDispatchThread = " +
                                       SwingUtilities.isEventDispatchThread());
                    int count = 0;
                    continueTask = true;
                    while(continueTask)
                        int max = progressBar.getMaximum();
                        int value = (int)((++count * 100.0) / max);
                        progressBar.setValue(value);
                        try
                            Thread.sleep(250);
                        catch(InterruptedException ie)
                            System.err.println("interruption: " + ie.getMessage());
                            continueTask = false;
                        if(value >= max)
                            continueTask = false;
                            progressBar.setValue(0);
            }).start();
        public static void main(String[] args)
            // JFrame code can go here
            f.getContentPane().add(new ProgressBarTest());
    }

  • How to solve a latency problem in JProgressBar

    Hello fellas,
    I am new on this forum and in the world of Java, but in programming is the only world that i like is java :P
    So i have a problem:
    I am making an application which i need to capture audio and shows the volume and I am using the JProgressBar to show the current volume from the capture, but i have a problem here which is, the progress bar have latency and seems slow when is capturing the audio.
    I would love to fix this and making this process more faster.
    Any idea?
    My best regards,
    David Henriques

    my method updateLabel() is for showing the value of the volume right side of the progress bar.
    I know that my code is so noob, but i want to put it right.
    So you advice to put the integer cnt inside of the method calculateRMSLevel() ?
    updateLabel() :
    public void updateLabel(){
           String msg ="";
           if(volume!= -1)
               msg = Integer.toString(volume);
           LBVol1.setText(msg);
       }calculateRMSLevel() :
    public int calculateRMSLevel(byte[] audioData){
         // audioData might be buffered data read from a data line
            long lSum = 0;
            for(int i=0; i<audioData.length; i++)
                lSum = lSum + audioData;
    double dAvg = lSum / audioData.length;
    double sumMeanSquare = 0d;
    for(int j=0; j<audioData.length; j++)
    sumMeanSquare = sumMeanSquare + Math.pow(audioData[j] - dAvg, 2d);
    double averageMeanSquare = sumMeanSquare / audioData.length;
    return (int)(Math.pow(averageMeanSquare,0.5d) + 0.5);
    captureAudio method :public void captureAudio(Mixer mixer){
    //Show the available mixers
    Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
    try{
    System.out.println("Available mixers:");
    for(int cnt = 0; cnt < mixerInfo.length;cnt++){
    System.out.println(mixerInfo[cnt].getName());
    }//end for loop
    format = getFormat();
    //DataLine.info get the information about the line.
    DataLine.Info info = new DataLine.Info(TargetDataLine.class,format);
    // get the info from the desired line.
    line = (TargetDataLine)AudioSystem.getLine(info);
    //Get a TargetDataLine on the selected mixer.
    line = (TargetDataLine) mixer.getLine(info);
    line.open(format);
    line.start();
    Thread captureThread = new Thread(this);
    captureThread.start();
    } catch (Exception e) {
    System.out.println(e);
    System.exit(0);
    }//end catch
    }//end captureAudio method*/
    In this moment i am confuse :/
    I declare the variable volume in the begin of the class because i made a getVolume() and than i send this getVolume to:public void volumeProgressBar1(){
    volume1.setValue(getVolume());

  • JProgressBar Shows Up Too Late--How Do I Update the Display Immediately?

    My application has a split pane, the bottom page of which is a panel containing an image that takes a long time to load. For that reason, I want the bottom pane to be a panel with a progress bar until the image is ready.
    Here's a simple version of my code:
    JPanel progressBarPanel = new JPanel();
    JProgressBar progressBar = new JProgressBar(0, 1);
    progressBar.setIndeterminate(true);
    progressBarPanel.add(progressBar);
    splitPane.setBottomComponent(progressBarPanel);  // line A
    splitPane.invalidate();
    JPanel imagePanel = createImagePanelSlowly();  // line B
    splitPane.setBottomComponent(imagePanel);
    splitPane.invalidate();However, this doesn't work; the display isn't updated until the image is ready. What do I need to put in between lines A and B so that the progress bar shows up before line B starts executing? I've tried validate(), repaint(), using threads and setting the size of the frame to zero and back again, but none of those seem to work. If I pop up a dialog after I add the progress bar to the split pane, the progress bar shows up as soon as the dialog shows up.
    This code is inside a ListSelectionListener on a table elsewhere on the GUI, in case that's relevant.
    I think I don't understand some basic principle about how to get the GUI to be updated immediately after I make some change.

    As suggested, I have prepared a compilable demonstration. I figured out that the
    problem I was having before was that I was trying to join the background and
    event-processing threads (I had been using threads, but I didn't show that code in the
    version I posted since it didn't seem to matter). After I eliminated the join, the progress
    bar is displayed, but the user can do other things while the image is loading. I want to
    prevent the user from doing that. I switched the cursor to a wait cursor, but that doesn't
    seem to prevent it.
    In particular, while it is loading, the user should be able to:
    * resize the window
    * minimize the window and bring it back up
    * ideally, adjust the split pane, but that isn't critical
    but NOT:
    * select a different row in the table
    * sort the table
    * use the menus
    Any attempt by the user to perform the disallowed actions should have no effect either
    while the image is loading or after it has finished.
    (That is, the disallowed events should not simply be queued for later.)
    I wonder if there is a simple way to accomplish that.
    Here is a demo (3 classes):
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Cursor;
    import java.awt.Font;
    import java.awt.GraphicsEnvironment;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.Enumeration;
    import java.util.Vector;
    import javax.swing.Box;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.border.Border;
    import javax.swing.border.EtchedBorder;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    * <p>Copyright (C) 2006
    * <p>All rights reserved.
    public class DisableGUIDemo extends JFrame {
         static final Rectangle SCREEN_SIZE = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
         static final Color HYACINTH = new Color(160, 96, 192);
         static final Color LAVENDER = new Color(224, 208, 232);
         Vector<Vector<String>> demoTableData = new Vector<Vector<String>>();
         Vector<String> demoColumnNames = new Vector<String>();
         protected JTable dataTable;
         protected JScrollPane tablePane;
         protected JSplitPane mainPane;
         protected JPanel imageArea;
         private DefaultTableModel dataModel;
          * This creates a new <code>DisableGUIDemo</code> instance, builds the UI
          * components and displays them.
         private DisableGUIDemo(){
              super();
              setTitle("Demo");
              // Ugly:  Initialize the table with demo data.
              Vector<String> demoTableFirstRow = new Vector<String>();
              demoTableFirstRow.add("18");
              demoTableFirstRow.add("13");
              demoTableFirstRow.add("11");
              demoTableFirstRow.add("19");
              demoTableFirstRow.add("19");
              demoTableData.add(demoTableFirstRow);
              Vector<String> demoTableSecondRow = new Vector<String>();
              demoTableSecondRow.add("5");
              demoTableSecondRow.add("3");
              demoTableSecondRow.add("4");
              demoTableSecondRow.add("1");
              demoTableSecondRow.add("3");
              demoTableData.add(demoTableSecondRow);
              Vector<String> demoTableThirdRow = new Vector<String>();
              demoTableThirdRow.add("11");
              demoTableThirdRow.add("12");
              demoTableThirdRow.add("10");
              demoTableThirdRow.add("18");
              demoTableThirdRow.add("18");
              demoTableData.add(demoTableThirdRow);
              demoColumnNames.add("Column 0");
              demoColumnNames.add("Column 1");
              demoColumnNames.add("Column 2");
              demoColumnNames.add("Column 3");
              demoColumnNames.add("Column 4");
              dataModel = new DefaultTableModel(demoTableData, demoColumnNames);
              initialize(); 
          * The <code>initialize</code> method builds and displays up the GUI.
         private void initialize() {
              addWindowListener(new WindowAdapter()  {
                        public void windowClosing(WindowEvent e)  {
                             System.exit(0);
              // Build the GUI panels.
              setJMenuBar(menuBar());
              createSplitPane(true);
              setLocation(SCREEN_SIZE.x, SCREEN_SIZE.y);
              setSize(SCREEN_SIZE.width, SCREEN_SIZE.height - 20);
              setVisible(true); 
          * This creates and returns the menu bar.  The actions to take in response to menu-option selections are
          * specified here.
          * @return the menu bar
         private JMenuBar menuBar(){
              JMenuBar menuBar = new JMenuBar();
              JMenu fileMenu = new JMenu("File");
              fileMenu.setFont(fileMenu.getFont().deriveFont(10.0f));
              JMenuItem reset = new JMenuItem("Reset");
              reset.setFont(reset.getFont().deriveFont(10.0f));
              reset.addActionListener(new ActionListener(){
                        // When the user resets the display, the configuration panel is recreated.
                        public void actionPerformed(ActionEvent e){
                             dataModel = new DefaultTableModel(demoTableData, demoColumnNames);
                             createSplitPane(true);
                             int oldWidth = getWidth();
                             int oldHeight = getHeight();
                             setSize(0, 0);
                             setSize(oldWidth, oldHeight);
                             repaint();
                             JOptionPane.showMessageDialog(DisableGUIDemo.this,
                                                                                                        "The display should be reset.",
                                                                                                        "Reset",
                                                                                                        JOptionPane.PLAIN_MESSAGE);
              fileMenu.add(reset);
              fileMenu.addSeparator();
              JMenuItem saveTable = new JMenuItem("Save Table");
              saveTable.setFont(saveTable.getFont().deriveFont(10.0f));
              saveTable.setEnabled(false);
              fileMenu.add(saveTable);
              menuBar.add(fileMenu);
              menuBar.add(Box.createHorizontalGlue());
              JMenu helpMenu = new JMenu("Help");
              helpMenu.setFont(helpMenu.getFont().deriveFont(10.0f));
              JMenuItem help = new JMenuItem("Documentation");
              help.setFont(help.getFont().deriveFont(10.0f));
              help.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             JOptionPane.showMessageDialog(DisableGUIDemo.this, "There is no documentation available for the demo.");
              helpMenu.add(help);
              menuBar.add(helpMenu);
              return menuBar;
          * The <code>createSplitPane</code> method creates the table and image area and displays them in a split pane.
          * @param createNewTable whether to create a new table (should be false if the table has already been created)
         private void createSplitPane(boolean createNewTable){
              if (createNewTable){
                   dataTable = dataTable();
                   tablePane = new JScrollPane(dataTable);
                   Border etchedBorder = new EtchedBorder(EtchedBorder.RAISED, LAVENDER, HYACINTH);
                   tablePane.setBorder(etchedBorder);
              int tablePaneWidth = tablePane.getPreferredSize().width;
              int selectedRow = dataTable.getSelectedRow();
              imageArea
                   = (selectedRow == -1)
                   ? new JPanel()
                   : imageArea((String) dataTable.getValueAt(selectedRow, 0),
                                                 (String) dataTable.getValueAt(selectedRow, 2));
              imageArea.setMinimumSize(imageArea.getPreferredSize());
              mainPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tablePane, imageArea);
              getContentPane().removeAll();
              getContentPane().add(mainPane);
          * The <code>dataTable</code> method returns the data table.
          * @return the data table
         private JTable dataTable(){
              JTable table = new JTable(dataModel);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              ListSelectionModel rowSM = table.getSelectionModel();
              rowSM.addListSelectionListener(new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent e) {
                             if (e.getValueIsAdjusting()){
                                  return;  // Ignore extra events.
                             ListSelectionModel lsm =
                (ListSelectionModel) e.getSource();
                             if (! lsm.isSelectionEmpty()){
                                  final int selectedRow = dataTable.getSelectedRow();
                                  setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                                  JPanel progressBarPanel = new JPanel();  // This should have a border layout.
                                  JProgressBar progressBar = new JProgressBar(0, 1);
                                  progressBar.setIndeterminate(true);
                                  progressBarPanel.add(progressBar);
                                  mainPane.setBottomComponent(progressBarPanel);
                                  mainPane.invalidate();
                                  mainPane.validate();
                                  Thread backgroundThread = new Thread(){
                                            public void run(){
                                                 JPanel imageDisplay = imageArea((String) dataTable.getValueAt(selectedRow, 0),
                                                                                                                                 (String) dataTable.getValueAt(selectedRow, 2));
                                                 mainPane.setBottomComponent(imageDisplay);
                                                 mainPane.invalidate();
                                                 setCursor(null);
                                  backgroundThread.start();
                                  // The following code, before being commented out, caused the GUI to be unresponsive while the image was
                                  // being loaded.  However, without it, the user can do other things while the image is loading, which is
                                  // not desired.
    //                               try{
    //                                    backgroundThread.join();
    //                               catch (InterruptedException ie){
    //                                    // N/A
              if (dataModel != null){
                   table.sizeColumnsToFit(-1);
                   table.getTableHeader().setReorderingAllowed(false);
                   SpecialHeaderRenderer headerRenderer = new SpecialHeaderRenderer(this);
                   SpecialCellRenderer bodyCellRenderer = new SpecialCellRenderer();
                   int i = 0;
                   for (Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); columns.hasMoreElements(); /** */){
                        int columnWidth = 0;
                        TableColumn nextColumn = columns.nextElement();
                        nextColumn.setHeaderRenderer(headerRenderer);
                        nextColumn.setCellRenderer(bodyCellRenderer);
                        nextColumn.sizeWidthToFit();
                        Component comp = headerRenderer.getTableCellRendererComponent(table, nextColumn.getHeaderValue(),
                                                                                                                                                                                   false, false, 0, 0);
                        columnWidth = comp.getPreferredSize().width;
                        for (int j = 0; j < dataModel.getRowCount(); j++){
                             comp = table.getCellRenderer(j, i).getTableCellRendererComponent(table, dataModel.getValueAt(j, i),
                                                                                                                                                                                              false, false, j, i);
                             columnWidth = Math.max(comp.getPreferredSize().width, columnWidth);
                        nextColumn.setPreferredWidth(columnWidth);
                        nextColumn.setMinWidth(columnWidth);
                        i++;
              return table;
          * The <code>imageArea</code> method returns a panel in which an image is shown in the real application.
          * In the demo application, it is replaced by a text label; an artificial delay is used to simulate the
          * delay that would occur during image loading.  The image is loaded when the user selects a row in the table.
          * @param parameter1 a parameter to image creation
          * @param parameter2 a parameter to image creation
          * @return a panel in which a text label stands in for an image
         private JPanel imageArea(String parameter1, String parameter2){
              try{
                   Thread.sleep(3000);
              catch (InterruptedException ie){
                   // N/A
              JPanel imagePanel = new JPanel();
              JLabel substituteLabel = new JLabel("Image for " + parameter1 + ", " + parameter2);
              imagePanel.add(substituteLabel);
              return imagePanel;
          * @param args
         public static void main (String[] args) {
              UIManager.put("Table.font", new Font("DialogInput", Font.PLAIN, 10));
              UIManager.put("Label.font", new Font("Dialog", Font.BOLD, 10));
              UIManager.put("TextField.font", new Font("DialogInput", Font.PLAIN, 10));
              UIManager.put("ComboBox.font", new Font("Dialog", Font.BOLD, 10));
              UIManager.put("Button.font", new Font("Dialog", Font.BOLD, 10));
              UIManager.put("List.font", new Font("Dialog", Font.BOLD, 10));
              try {           
                   new DisableGUIDemo();
              catch (Throwable e) {
                   e.printStackTrace();
                   System.exit(0);
         } // end of main ()
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Comparator;
    import java.util.TreeSet;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.UIManager;
    import javax.swing.border.EmptyBorder;
    import javax.swing.table.TableCellRenderer;
    * <p>Copyright (C) 2006
    * <p>All rights reserved.
    public class SpecialHeaderRenderer extends JPanel implements TableCellRenderer {
         static final Color MAUVE = new Color(192, 160, 208);
         static final Insets ZERO_INSETS = new Insets(0, 0, 0, 0);
         static final EmptyBorder EMPTY_BORDER = new EmptyBorder(ZERO_INSETS);
         private GridBagConstraints constraints = new GridBagConstraints();
         final TreeSet<MouseEvent> processedEvents = new TreeSet<MouseEvent>(new Comparator<MouseEvent>(){
              public int compare(MouseEvent o1, MouseEvent o2){
                   return o1.hashCode() - o2.hashCode();
         final private JFrame owner;
      public SpecialHeaderRenderer(JFrame ownerWindow) {
        setOpaque(true);
        setForeground(Color.BLACK);
              setBackground(MAUVE);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
              setLayout(new GridBagLayout());
              constraints.fill = GridBagConstraints.NONE;
              constraints.gridx = 0;
              setAlignmentY(Component.CENTER_ALIGNMENT);
              owner = ownerWindow;
      public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected,
                                                                                                                             boolean hasFocus, int row, final int column){
              if (table != null){
                   removeAll();
                   String valueString = (value == null) ? "" : value.toString();
                   JLabel title = new JLabel(valueString);
                   title.setHorizontalAlignment(SwingConstants.CENTER);
                   title.setFont(title.getFont().deriveFont(12.0f));
                   constraints.gridy = 0;
                   constraints.insets = ZERO_INSETS;
                   add(title, constraints);
                   final JPanel buttonPanel = new JPanel();
                   buttonPanel.setLayout(new GridLayout(1, 2));
                   buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
                   buttonPanel.setBackground(MAUVE);
                   final JButton sortAscendingButton = new JButton("V");
                   sortAscendingButton.setMargin(ZERO_INSETS);
                   sortAscendingButton.setBorder(EMPTY_BORDER);
                   constraints.gridy = 1;
                   constraints.insets = new Insets(5, 0, 0, 0);
                   buttonPanel.add(sortAscendingButton);
                   final JButton sortDescendingButton = new JButton("^");
                   sortDescendingButton.setMargin(ZERO_INSETS);
                   sortDescendingButton.setBorder(EMPTY_BORDER);
                   buttonPanel.add(sortDescendingButton);
                   add(buttonPanel, constraints);
                   table.getTableHeader().addMouseListener(new MouseAdapter(){
                             public void mouseClicked(MouseEvent e) {
                                  Rectangle panelBounds = table.getTableHeader().getHeaderRect(column);
                                  Rectangle buttonPanelBounds = buttonPanel.getBounds();
                                  Rectangle buttonBounds = sortAscendingButton.getBounds();
                                  buttonBounds.translate(buttonPanelBounds.x, buttonPanelBounds.y);
                                  buttonBounds.translate(panelBounds.x, panelBounds.y);
                                  if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){
                                       // The click was on this button and has not yet been processed.
                                       JOptionPane.showMessageDialog(owner,
                                                                                                                  "The table would be sorted in ascending order of column " + column + ".",
                                                                                                                  "Sorted Ascending",
                                                                                                                  JOptionPane.PLAIN_MESSAGE);
                                       table.invalidate();
                                       table.revalidate();
                                       table.repaint();
                                  buttonBounds = sortDescendingButton.getBounds();
                                  buttonBounds.translate(buttonPanelBounds.x, buttonPanelBounds.y);
                                  buttonBounds.translate(panelBounds.x, panelBounds.y);
                                  if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){
                                       // The click was on this button and has not yet been processed.
                                       JOptionPane.showMessageDialog(owner,
                                                                                                                  "The table would be sorted in descending order of column " + column + ".",
                                                                                                                  "Sorted Descending",
                                                                                                                  JOptionPane.PLAIN_MESSAGE);
                                       table.invalidate();
                                       table.revalidate();
                                       table.repaint();
              return this;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.util.HashMap;
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.LineBorder;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    * <code>SpecialCellRenderer</code> is the custom renderer for all
    * rows except the header row.
    * <p>Copyright (C) 2006
    * <p>All rights reserved.
    public class SpecialCellRenderer extends JPanel implements TableCellRenderer {
         protected Color backgroundColor = Color.PINK; // This means the rows for the first row will be white.
         protected HashMap<Object, Color> rowColors = new HashMap<Object, Color>();
      public SpecialCellRenderer(){
        setOpaque(true);
        setForeground(Color.BLACK);
              setBackground(Color.WHITE);
              setFont(new Font("Monospaced", Font.PLAIN, 10));
              setAlignmentX(Component.RIGHT_ALIGNMENT);
              setBorder(new EmptyBorder(0, 2, 0, 2));
      public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected,
                                                                                                                             boolean hasFocus, final int row, final int column){
              String columnName = table.getColumnName(column);
              JLabel text = new JLabel();
              text.setOpaque(true);
              if (table != null){
                   DefaultTableModel model = (DefaultTableModel) table.getModel();
                   if (model == null){
                        System.out.println("The model is null!!");
                        System.exit(1);
                   if (table.isCellSelected(row, column)){
                        setBorder(BorderFactory.createMatteBorder((column < 2) ? 0 : 1,
                                                                                                                                 (column == 2) ? 1 : 0,
                                                                                                                                 (column < 2) ? 0 : 1,
                                                                                                                                 (column == table.getColumnCount() - 1) ? 1 : 0,
                                                                                                                                 Color.BLUE));
                   else{
                        setBorder(BorderFactory.createEmptyBorder());
                   final String rowIdentifier = (String) model.getValueAt(row, 0);
                   if (! rowColors.containsKey(rowIdentifier)){
                        rowColors.put(rowIdentifier, nextBackgroundColor());
                   text.setBackground(rowColors.get(rowIdentifier));
                   text.setFont(getFont().deriveFont(Font.PLAIN));
                   String valueString = (value == null) ? "" : value.toString();
                   text.setText(valueString);
                   try{
                        Double.parseDouble(valueString);
                        text.setHorizontalAlignment(SwingConstants.TRAILING);
                   catch (NumberFormatException nfe){
                        text.setHorizontalAlignment(SwingConstants.LEADING);
                   setLayout(new GridLayout(1, 1));
                   removeAll();
                   add(text);
                   setBackground(text.getBackground());
                   if (table.getRowHeight() < getMinimumSize().height){
                        table.setRowHeight(getMinimumSize().height);
              return this;
         protected Color nextBackgroundColor(){
              backgroundColor = backgroundColor.equals(Color.WHITE) ? Color.PINK : Color.WHITE;
              return backgroundColor;
    }

  • JProgressBar - NetBeans

    I just started working with NetBeans IDE and making GUI's, and have a question about the jProgressBar: When I use a Thread.Sleep(int) to delay for a time, it will do something like this:
    for(int j = 0; j<=100;j++)
    Thread.sleep(300);                //this makes it wait for 30000 miliseconds
    jProgressBar1.setValue(j);       //then does all of the setValue()'s at once
    }I want it to wait for 300 miliseconds, then set the value one more then it was, etc. so it fills up gradually. How do I do this?

    Something like this:import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JProgressBar;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    public class TimedProgressBar  implements ActionListener {
       JProgressBar progressBar = new JProgressBar (0, 100);
       Timer timer = new Timer (300, this);
       void makeUI () {
          JFrame frame = new JFrame ("");
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (300, 50);
          frame.add (progressBar);
          frame.setLocationRelativeTo (null);
          frame.setVisible (true);
          timer.start ();
       public void actionPerformed (ActionEvent e) {
          int i = progressBar.getValue ();
          if (i == progressBar.getMaximum ()) {
             timer.stop ();
          progressBar.setValue (progressBar.getValue () + 1);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                new TimedProgressBar ().makeUI ();
    Darryl is right, as usual.Nah, I've contributed my share of bloopers to the forum :-).
    But do you know why Thread.sleep(300) doesn't have the desired effect?
    Are you interested?Lets hope...
    How's the weekend going, Keith?
    Darryl
    edit Removed one remark after scrolling right and reading the oh-sso-spaced-out comments in the OP.
    Edited by: Darryl.Burke

  • JProgressBar within the progress of a JProgressBar

    Hello,
    I'm looking to make a progress bar within the progress of another progress bar, is this possible? That is to say, I want to have a container that fills up to some level, then the "stuff" that filled it up itself fills with something else to another level. Right now I'm just drawing a box, then a somewhat shorter box within the first box, but I thought it might be neater with a JProgressBar or something like it. How would I go about using or extending JProgressBar to accomplish this effect.
    Thank you.

    Here's sort of a proof of concept. JProgressBar is a container, so you can add any component you want to it including another JProgressBar. Using GridBagLayout I made the smaller JProgressBar centered within the larger one. The smaller one also occupies 40% the width and 20% the height of the larger one. So if the larger one gets bigger (or smaller), the smaller progress bar will scale accordingly. The SwingWorker does my long task.
    import javax.swing.*;
    import java.util.List;
    import java.util.Random;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    public class ProgressBarTest {
        public static void main(String[] args) {
           SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                   createAndShowGUI();
        private static void createAndShowGUI() {
            final JProgressBar outer = new JProgressBar();
            final JProgressBar inner = new JProgressBar();
            GridBagLayout layout = new GridBagLayout();
            outer.setLayout(layout);
            outer.add(new JLabel(),createConstraints(0, 0, 3, 1, 1.0, .4));
            outer.add(new JLabel(),createConstraints(0, 1, 1, 1, .30, .2));
            inner.setBorder(null);
            inner.setPreferredSize(new java.awt.Dimension());
            outer.add(inner, createConstraints(1, 1, 1, 1, .4, .2));
            outer.add(new JLabel(),createConstraints(2, 1, 1, 1, .30, .2));
            outer.add(new JLabel(),createConstraints(0, 2, 3, 1, 1.0, .4));
            SwingWorker worker = new SwingWorker<Void,Object>() {
                Random rn = new Random();
                @Override
                protected Void doInBackground() throws Exception {
                    for(int i = 0; i < 100; i++) {
                        publish(outer,i);
                        for(int j = 0; j < 100; j += rn.nextInt(12)) {
                            publish(inner,j);
                            try{
                                Thread.sleep(10);
                            }catch(InterruptedException e) {
                                return null;
                    return null;
                @Override
                protected void process(List<Object> chunks) {
                    JProgressBar progressBar = (JProgressBar) chunks.get(0);
                    int value = (Integer) chunks.get(1);
                    progressBar.setValue(value);
                @Override
                protected void done() {
                    outer.setValue(100);
                    outer.removeAll();
            JFrame frame = new JFrame();
            frame.setContentPane(outer);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            worker.execute();
        private static GridBagConstraints createConstraints(
                int gridX, int gridY, int gridW, int gridH,
                double weightX, double weightY) {
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = gridX; gbc.gridy = gridY;
            gbc.gridwidth = gridW; gbc.gridheight = gridH;
            gbc.weightx = weightX; gbc.weighty = weightY;
            gbc.fill = GridBagConstraints.BOTH;
            return gbc;
    }

  • Swing Gurus Help! Problem updating a JProgressBar from within a listener.

    Hello all,
    I have a static JProgressBar attached to the Main JFrame of my application. One of the screens of my app has a JTable on it. I have a ListSelectionListener attached to the table. When an item is selected on the JTable, I pull some information out of it (Using the ListSelectionModel) and kick off a pretty lengthy process. This of course all happens inside the ListSelectionListener. My problem is that when I call into my JFrame (MainFrame.java) to update the ProgressBar, nothing happens.
    The first line of my valueChanged(ListSelecteEvent e) method is
    if (e.getValueIsAdjusting()) return; The next line is call to the progress bar:
    MainFrame.setExecutionProgress(10, "Opening...");When the code is like this, the progress bar isn't updated until after the method valueChanged() method returns. However, if I put the call to setExecutionProgress() before the if (e.getValueIsAdjusting()) check, the progress bar actually changes.
    The second scenario I mentioned above doesn't really help me because subsequent calls to MainFrame.setExecutionProgress() don't work from within the body of the valueChanged() method until it has returned.
    Is this a threading issue? I've tried wrapping calls with SwingUtilitilies.invokeLater(), but I can't get anythin to work. Any ideas?
    Thanks much in advance.
    -Toby

    Where do you kick off this 'lengthy process'? The process is kicked off within the listener. What makes it long is that some of the objects created in this process have to reach out to a web-service for initialization.
    Also, how do you know how far the lengthy process is?Well I create a few projects and just bump the progress meter by 10 or so with each object. I'm not really worried about the accuracy of the progress meter (a la Microsoft =), because I just want to give the user some visual indication something is happening behind the scenes (besides the hour-glass).
    I think I understand how you'd kick this process off in a thread, but how would you create another thread that's capable of monitoring the first? I mean how do you accomplish the inter-thread communication?
    ddinks much for the help!
    -Toby

Maybe you are looking for