开发者

How to Display a working but dummy progress bar in java

I want to show a progress bar in my java program but I dont want it to actually work on a real task but i want it to just show that some process is being completed and it should loo开发者_StackOverflow社区k as if some process is going on. I tried to do this with the following code but it isn't helping me, so please if u can help....

Code:

       try 
       {
           for(int i=0;i<=100;i++){
              prog.setValue(i); // this would set the progressbar
             Thread.sleep(300); // this should pause the program or the loop
           }
       }

       catch(Exception e){

       }


Assuming Swing...

Put the progress bar in indeterminate mode
A progress bar in indeterminate mode displays animation to indicate that work is occurring

http://download.oracle.com/javase/tutorial/uiswing/components/progress.html#indeterminate


Here is an example that shows a progress bar going from 0 to 100. It is important to update the progress bar on the event dispatching thread using SwingUtilities.invokeLater or SwingUtilities.invokeAndWait.

public static void main(String[] args){
        JFrame f = new JFrame();
        f.setLayout(new BorderLayout());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JProgressBar bar = new JProgressBar(0,100);
        f.add(bar, BorderLayout.SOUTH);
        f.setSize(64, 64);
        f.pack();
        f.setVisible(true);

        for(int i = bar.getMinimum(); i <= bar.getMaximum(); i++){
            final int percent = i ;
            SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run() {
                    bar.setValue(percent);
                }
            });
            try {
                Thread.sleep(25);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
}


int progressCounter=0;

    new Thread(new Runnable() {
        public void run() {
            while (progressCounter <= 100) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        jProgressBar1.setValue(jProgressBar1.getValue()+1);
                        System.err.println("hello");
                    }
                });
                try { Thread.sleep(500); } catch (InterruptedException e) {}
            }
        }
    }).start();

Try this, it will definitely work. In java components are updated using EDT and invokeLater(Runnable) is used to call a task when every other task in the block has been completed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜