JProgressBar Demo

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class PgbDemo extends JFrame {

    private JProgressBar pgb;
    private JButton but;
    private JPanel pan;

    public PgbDemo() {
        super("JProgressBar Demo");
        initComponents();
    }

    private void initComponents() {
        pan = new JPanel();
        pan.setLayout(new BorderLayout());
        pgb = new JProgressBar();
        pgb.setMinimum(0);
        pgb.setMaximum(100);
        pgb.setValue(0);
        pgb.setStringPainted(true);
        pgb.setBorderPainted(true);
        pgb.setBackground(Color.yellow);
        pan.add(pgb, BorderLayout.CENTER);

        but = new JButton("Start");
        but.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //run task
                but.setEnabled(false);
                new ATask().start();
            }
        });
        pan.add(but, BorderLayout.EAST);

        this.getContentPane().add(pan);
        this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                PgbDemo frame = new PgbDemo();
                frame.setLocationRelativeTo(null);
                frame.setSize(500, 100);
                frame.setVisible(true);
            }
        });
    }

    class ATask extends Thread {
        public void run() {
            System.out.println(SwingUtilities.isEventDispatchThread());
            for (int i = 0; i < 130; i++) {
                final int percents = (int) ((float) i / 130.0 * 100.0) + 1;
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        PgbDemo.this.pgb.setValue(percents);
                    }
                });
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(PgbDemo.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    PgbDemo.this.but.setEnabled(true);
                }
            });
        }
    }
}
posted @ 2012-10-26 10:03  Leo Forest  阅读(206)  评论(0编辑  收藏  举报