初识 进度条JProgressBar
ProgressBarTest类:
实现接口:ActionListener,PropertiesChangeListener
覆盖方法:actionPerformed(),propertyChange()
Task类:
继承SwingWorker<Void,Void>
覆盖方法doInBackground()
Important Code:
66~86
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.slh.swing; 2 3 import java.awt.*; 4 import java.awt.event.ActionEvent; 5 import java.awt.event.ActionListener; 6 import java.beans.PropertyChangeEvent; 7 import java.beans.PropertyChangeListener; 8 import java.util.concurrent.TimeUnit; 9 10 import javax.swing.*; 11 12 public class ProgressBarTest extends JPanel implements ActionListener, 13 PropertyChangeListener { 14 private JButton startButton; 15 private JProgressBar progressBar; 16 private JTextArea taskOutput; 17 private Task task; 18 19 class Task extends SwingWorker<Void, Void> { 20 21 @Override 22 protected Void doInBackground() throws Exception { 23 int progress=0; 24 while(progress<100){ 25 Thread.sleep(1000); 26 progress+=10; 27 setProgress(Math.min(progress,100)); 28 } 29 return null; 30 } 31 protected void done(){ 32 startButton.setEnabled(true); 33 setCursor(null); 34 taskOutput.append("Done!\n"); 35 } 36 37 } 38 39 public ProgressBarTest() { 40 super(new BorderLayout()); 41 initComponent(); 42 } 43 44 private void initComponent() { 45 startButton = new JButton("start"); 46 //startButton.setActionCommand("start");// 47 startButton.addActionListener(this); 48 49 progressBar=new JProgressBar(); 50 progressBar.setValue(0); 51 progressBar.setStringPainted(true);// 52 53 taskOutput=new JTextArea(5,20); 54 taskOutput.setMargin(new Insets(5,5,5,5)); 55 taskOutput.setEditable(false); 56 57 JPanel jPanel=new JPanel(); 58 jPanel.add(startButton); 59 jPanel.add(progressBar); 60 61 add(jPanel,BorderLayout.PAGE_START); 62 add(new JScrollPane(taskOutput),BorderLayout.CENTER); 63 setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); 64 } 65 66 @Override 67 public void propertyChange(PropertyChangeEvent evt) { 68 // TODO Auto-generated method stub 69 if("progress"==evt.getPropertyName()){ 70 int progress=(Integer) evt.getNewValue(); 71 progressBar.setValue(progress); 72 taskOutput.append("当前进度"+progress+"%\n"); 73 } 74 75 } 76 77 @Override 78 public void actionPerformed(ActionEvent e) { 79 startButton.setEnabled(false); 80 setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 81 task=new Task(); 82 task.addPropertyChangeListener(this); 83 task.execute(); 84 } 85 86 private static void createAndShowGUI() { 87 JFrame jFrame = new JFrame(); 88 jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 89 90 JComponent pbt = new ProgressBarTest(); 91 pbt.setOpaque(true); 92 jFrame.setContentPane(pbt); 93 94 jFrame.pack(); 95 jFrame.setVisible(true); 96 } 97 98 public static void main(String[] args) { 99 SwingUtilities.invokeLater(new Runnable() { 100 public void run() { 101 createAndShowGUI(); 102 } 103 }); 104 } 105 106 }