核心在于线程操作
//source code import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JProgressBar; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener ; class ProcessBar extends Thread { private int DELAY = 100 ; private JProgressBar bar ; private JButton button ; private boolean flag = true ; public ProcessBar(JProgressBar bar,JButton button) { this.bar = bar ; this.button = button ; } public void run() { button.setEnabled(false); int max = bar.getMaximum() ; while(flag) { try { Thread.sleep(DELAY); //休眠100毫秒 } catch(InterruptedException ignoreException) { } bar.setValue(bar.getValue()+1); if(bar.getValue() >= max) { flag = false ; } } button.setEnabled(true); } } ; class Tester { public static void main(String args[]) { final JProgressBar pbar = new JProgressBar(0,100) ; pbar.setStringPainted(true); final JButton bstart = new JButton("开始") ; bstart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (pbar.getValue() >= pbar.getMaximum()) { pbar.setValue(0) ; } Thread stepper = new ProcessBar(pbar, bstart) ; stepper.start() ; } }); JFrame frame = new JFrame("安装进度") ; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(pbar,BorderLayout.NORTH) ; frame.add(bstart,BorderLayout.SOUTH) ; frame.setSize(300,100); frame.setVisible(true) ; } }