3

我正在使用 JProgressBar 来显示进度。但是,如何将进度条显示为从 0 加载到 100?我从互联网上得到了代码,它的工作除了没有加载进度条。

代码

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();

如果有人编辑上述代码以使其工作,我将不胜感激。谢谢你。

4

4 回答 4

12

必须喜欢来自互联网的代码......哦......

您的代码违反了 Swing 的单线程规则,因此是一个不好的例子。

您有多种选择SwingWorker。您可以publish使用进度并使用该process方法来更新进度条,或者您可以使用PropertyChangeListener并监视通过调用该setProgress方法创建的进度更改事件SwingWorker

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class SwingWorkerProgress {

    public static void main(String[] args) {
        new SwingWorkerProgress();
    }

    public SwingWorkerProgress() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JProgressBar pbProgress;
        private JButton start;

        public TestPane() {

            setBorder(new EmptyBorder(10, 10, 10, 10));
            pbProgress = new JProgressBar();
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(4, 4, 4, 4);
            gbc.gridx = 0;
            gbc.gridy = 0;
            add(pbProgress, gbc);

            start = new JButton("Start");
            gbc.gridy++;
            add(start, gbc);

            start.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    start.setEnabled(false);
                    ProgressWorker pw = new ProgressWorker();
                    pw.addPropertyChangeListener(new PropertyChangeListener() {

                        @Override
                        public void propertyChange(PropertyChangeEvent evt) {
                            String name = evt.getPropertyName();
                            if (name.equals("progress")) {
                                int progress = (int) evt.getNewValue();
                                pbProgress.setValue(progress);
                                repaint();
                            } else if (name.equals("state")) {
                                SwingWorker.StateValue state = (SwingWorker.StateValue) evt.getNewValue();
                                switch (state) {
                                    case DONE:
                                        start.setEnabled(true);
                                        break;
                                }
                            }
                        }

                    });
                    pw.execute();
                }
            });

        }
    }

    public class ProgressWorker extends SwingWorker<Object, Object> {

        @Override
        protected Object doInBackground() throws Exception {
            int i = 0;
            int max = 2000;

            while (i < max) {
                i += 10;
                int progress = Math.round(((float)i / (float)max) * 100f);
                setProgress(progress);
                try {
                    Thread.sleep(25);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
    }
}
于 2013-03-04T10:19:03.047 回答
5

你必须为此使用线程。设计一个实现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());
    }
}

并在您的框架类中progressBar与这样的新类一起使用

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

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

ju.setValue([Value to set]);
于 2013-03-04T10:20:35.577 回答
-1
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class ProgressBar {
    /**
     * JProgressBar
     * 
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        JFrame frame = new JFrame("New Window");
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new GridBagLayout());
        frame.setVisible(true);

        //JLabel textLoad = new JLabel();
        //textLoad.setText("Loading ....");

        JProgressBar progressBar = new JProgressBar();        
        progressBar.setMinimum(0);
        progressBar.setMaximum(100);
        progressBar.setStringPainted(true);
        progressBar.setIndeterminate(true);
        frame.add(progressBar);                               

        for (int i = progressBar.getMinimum(); i <= progressBar.getMaximum(); i++) {
            Thread.sleep(500);
            progressBar.setValue(i);
        }

        textLoad.setText("Done !");
    }

}
于 2015-09-01T20:56:09.940 回答
-3
/*
By
Dr. Amit Kumar Kapoor
Assistant Professor, Maharaja Agrasen Institute of Management & Technology, Jagadhri
E-mail ID: akbrightfuture@gmail.com
*/
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class progressbardemo extends JFrame implements ActionListener
       {
          JProgressBar pb;
          JButton b1;
              progressbardemo()
              {
                 super("Progressbar");
                 setLayout(null);
                 b1=new JButton("Click");
                 b1.setBackground(Color.yellow);             
                 pb=new JProgressBar(1,100);
                 pb.setValue(0);
                 pb.setStringPainted(true);
                 pb.setForeground(Color.red);   
                 pb.setBackground(Color.white); 
                 b1.setBounds(20,20,80,25);pb.setBounds(110,20,200,25);
                 pb.setVisible(false);
                 add(b1);
                 add(pb);             
                 b1.addActionListener(this);
                 setResizable(false);
                 setDefaultCloseOperation(EXIT_ON_CLOSE);
              }
               public void actionPerformed(ActionEvent e)
               {
                  int i=0;
                  if(e.getSource()==b1)
                     {
                       pb.setVisible(true);
                    try
                    {
                       while(i<=100)
                       {
                        Thread.sleep(50);
        pb.paintImmediately(0, 0, 200, 25);
            pb.setValue(i);
                         i++;
        }
                     }
                     catch(Exception e1)
                     {
        System.out.print("Caughted exception is ="+e1);
                     }
                    }
               }
              public static void main(String arg[])
              {
              progressbardemo m=new progressbardemo();
              m.setSize(330,100);
              m.setVisible(true);
              Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
              int x = (int) ((dimension.getWidth() - m.getWidth()) / 2);
              int y = (int) ((dimension.getHeight() - m.getHeight()) / 2);
              m.setLocation(x, y); 
              }
       }
于 2013-08-05T08:56:44.800 回答