Swing 中进度指示器的使用主要涉及三个类的使用:
JProgressBar:用于指示进度的构件
ProgressMonitor:一个包含进度条的对话框
ProgressMonitorInputStream:在读取流的时候用于进度监视
下面几个例子依次介绍三个类的使用,首先是JProgressBar,建议先在Eclipse跑一下,在去看源码,我已加上详细的注释,相信很容易看懂。
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import javax.swing.Timer;
- public class ProgressBarTest
- {
- public static void main(String[] args)
- {
- JFrame frame = new ProgressBarFrame();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
- }
- class ProgressBarFrame extends JFrame
- {
- public ProgressBarFrame()
- {
- setTitle("ProgressBarTest");
- setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
- // 显示事件的输出
- textArea = new JTextArea();
- JPanel panel = new JPanel();
- startButton = new JButton("Start");
- progressBar = new JProgressBar();
- progressBar.setStringPainted(true);//用来显示 "n%"
- panel.add(startButton);
- panel.add(progressBar);
- checkBox = new JCheckBox("indeterminate");
- checkBox.addActionListener(new
- ActionListener()
- {
- public void actionPerformed(ActionEvent event)
- { //设置成进度不确定模式
- progressBar.setIndeterminate(checkBox.isSelected());
- }
- });
- panel.add(checkBox);
- add(new JScrollPane(textArea), BorderLayout.CENTER);
- add(panel, BorderLayout.SOUTH);
- //点击start按钮事件
- startButton.addActionListener(new
- ActionListener()
- {
- public void actionPerformed(ActionEvent event)
- {
- progressBar.setMaximum(1000);
- activity = new SimulatedActivity(1000);
- new Thread(activity).start();
- activityMonitor.start();
- startButton.setEnabled(false);
- }
- });
- //没500毫秒更新一次进度条和进度输出
- activityMonitor = new Timer(500, new
- ActionListener()
- {
- public void actionPerformed(ActionEvent event)
- {
- int current = activity.getCurrent();
- // show progress
- textArea.append(current + "/n");
- progressBar.setStringPainted(!progressBar.isIndeterminate());
- progressBar.setValue(current);
- // check if task is completed
- if (current == activity.getTarget())
- {
- progressBar.setString("complete!");//当完成是把n%替换成“complete!”
- activityMonitor.stop();
- startButton.setEnabled(true);
- }
- }
- });
- }
- private Timer activityMonitor;
- private JButton startButton;
- private JProgressBar progressBar;
- private JCheckBox checkBox;
- private JTextArea textArea;
- private SimulatedActivity activity;
- public static final int DEFAULT_WIDTH = 400;
- public static final int DEFAULT_HEIGHT = 200;
- }
- /**
- A similated activity runnable.
- */
- class SimulatedActivity implements Runnable
- {
- public SimulatedActivity(int t)
- {
- current = 0;
- target = t;
- }
- public int getTarget()
- {
- return target;
- }
- public int getCurrent()
- {
- return current;
- }
- public void run()
- {
- try
- {
- while (current < target)
- {
- Thread.sleep(100);
- current++;
- }
- }
- catch(InterruptedException e)
- {
- }
- }
- private volatile int current;//可以同步访问current
- private int target;
- }