编程语言
首页 > 编程语言> > 进度条Java

进度条Java

作者:互联网

我正在使用JProgressBar来显示进度.但是,如何将progressBar显示为从0加载到100?我从互联网及其工作中获得了代码,但progressBar没有加载.

progressFrame = new JFrame(); // frame to display progress bar
progressBar = new JProgressBar(0,100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
progressFrame.add(progressBar);

new SwingWorker<Void,Void>()
    {
        protected Void doInBackground() throws SQLException, ClassNotFoundException
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            progressBar.setValue(0);
            frame.setEnabled(false); // frame = main frame

            //tableclass creates a JTable with data from database
            tableclass = new TheDatabaseTable(deptName);//it takes time to create
            progressBar.setValue(50);
            frame.getContentPane().removeAll();
            frame.setContentPane(tableclass);

            frame.validate();
            frame.repaint();

            progressBar.setValue(100);
            //progressFrame.dispose();
            return null;
        }; 
        protected void done()
        {
            //progressFrame.setVisible(false);
            frame.setVisible(true);
            progressFrame.dispose();
            frame.setEnabled(true);
        }

    }.execute();

如果有人编辑上述代码,我将不胜感激.谢谢.

解决方法:

你必须使用线程.设计一个实现Runnable接口的类,它将更新这样的值.

class ProgressBarUpdator implements java.lang.Runnable {

    /**
     * Progress bar that shows the current status
     */
    private javax.swing.JProgressBar jpb = null;
    /**
     * Progress bar value
     */
    private java.lang.Integer value = null;

    /**
     * Constructor
     * @param jpb The progress bar this has to update
     */
    public ProgressBarUpdator(javax.swing.JProgressBar jpb) {
        this.jpb = jpb;
        jpb.setMaximum(100);
    }

    /**
     * Sets the value to the progress bar
     * @param value Value to set
     */
    public void setValue(java.lang.Integer value) {
        this.value = value;
    }

    /**
     * Action of the thread will be executed here. The value of the progress bar will be set here.
     */
    public void run() {
        do {
            if (value != null) {
                jpb.setValue((int)java.lang.Math.round(java.lang.Math.floor(value.intValue() * 100 / maximum)));
            }
            try {
                java.lang.Thread.sleep(100L);
            } catch (java.lang.InterruptedException ex) {
                ex.printStackTrace();
            }
        } while (value == null || value.intValue() < jpb.getMaximum());
    }
}

并且在你的frame类中使用progressBar和这样的新类

ProgressBarUpdator ju = new ProgressBarUpdator(progressBar);
new java.lang.Thread(ju).start();

每当您想要更改值时,只需使用该语句即可

ju.setValue([Value to set]);

标签:jprogressbar,java,swing,jtable,tablecelleditor
来源: https://codeday.me/bug/20190916/1806489.html