JProgressBar 在阅读过程中不可见 [英] JProgressBar not visible during reading

查看:24
本文介绍了JProgressBar 在阅读过程中不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完美加载的 java 进度条,但我看不到过程,只能看到结果.(当酒吧完成加载时)我想看到进度的每一个百分比.当我运行代码时,框架出现但进度条没有,只有当它处于 100% 时.问题出在哪里?

I got a java progressbar which loads perfectly, but I can't see the process, only the result. (when the bar finished loading) I want to see every percentage of the progress. When I run the code, the frame appears but the progressbar doesn't, only when it's on 100%. Where's the problem?

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         

       JFrame f = new JFrame("JProgressBar Sample");
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       Container content = f.getContentPane();
       progressBar = new JProgressBar();
       progressBar.setStringPainted(true);
       Border border = BorderFactory.createTitledBorder("Reading...");
       progressBar.setBorder(border);
       content.add(progressBar, BorderLayout.CENTER);
       f.setSize(300, 100);
       f.setVisible(true);

       progressBar.setValue(0);
       inc(); //fill the bar
       //It fills, but I can't se the whole loading...

    }                                        
        //Here's the filling path
    public static void inc(){

        int i=0;
       try{
            while (i<=100){    
            progressBar.setValue(i+10);

            Thread.sleep(1000);
            i+=20;
            }
        }catch(Exception ex){
            //nothing
        }
    }

推荐答案

当您在 GUI 线程中运行一个长进程时,您的 GUI 不会更新,例如填充进度条和休眠几秒钟.

Your GUI is not updated while you are running a long process in the GUI's thread, like filling a progress bar and sleeping some seconds.

只需出现一个线程,它将处理长时间的操作.在此线程中,将进度条设置为 SwingUtilities.invokeLater(new Runnable() {...}.

Just emerge a thread, which will handle the long operation. Within this thread set the progress bar to the desired value within a SwingUtilities.invokeLater(new Runnable() {...}.

Runnable r = new Runnable() {
    public void run() {
        int i=0;
        try{
            while (i<=100){    
                final int tmpI = i+10;
                SwingUtilities.invokeLater(new Runnable(){ 
                    public void run() {
                        progressBar.setValue(tmpI);
                    }
                });
                Thread.sleep(1000);
                i += 20;
            }
        } catch(Exception ex){
             //nothing
        }
    }
};
Thread t = new Thread(r);
t.start();

这篇关于JProgressBar 在阅读过程中不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆