ProgressMonitorInputStream

ProgressMonitorInputStream

Swing类包中有一个很有用的流过滤器,ProgressMonitorInputStream,它可以自动弹出一个对话框,监视已经读取了多少流。

进度监视器流使用InputStream类的available方法来确定流中的总字节数。不过available方法只报告流中可访问的、未中断的字节数。
进度监视器适用于文件以及HTTP URL,因为它们的长度都是事先可知道的,但它不适用于所有的流。
ProgressMonitorInputStream-LMLPHP

package swing.progress;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner; import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker; /*2015-7-6*/
public class ProgressMonitorInputStreamTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { @Override
public void run() {
JFrame frame = new TextFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
});
} } class TextFrame extends JFrame {
private static final long serialVersionUID = 1L; private JMenuItem openItem;
private JMenuItem exitItem;
private JTextArea textArea;
private JFileChooser chooser;
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200; public TextFrame() {
setTitle("ProgressMonitorInputStreamTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); textArea = new JTextArea();
add(new JScrollPane(textArea)); chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(".")); JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
openItem = new JMenuItem("Open");
openItem.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent e) {
try {
openFile();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} }
}); fileMenu.add(openItem);
exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
fileMenu.add(exitItem); } protected void openFile() throws FileNotFoundException {
int r = chooser.showOpenDialog(this);
if (r != JFileChooser.APPROVE_OPTION) {
return;
} File f = chooser.getSelectedFile(); FileInputStream fileIn = new FileInputStream(f);
ProgressMonitorInputStream progressIn = new ProgressMonitorInputStream(this, "Reading " + f.getName(), fileIn);
final Scanner in = new Scanner(progressIn);
textArea.setText("");
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override
protected Void doInBackground() throws Exception {
while (in.hasNextLine()) {
String line = in.nextLine();
textArea.append(line);
textArea.append("\n");
}
in.close();
return null;
} };
worker.execute();
} }
05-08 15:44