java读取TXT文件并且显示打开进度,最后要逐行显示
要求1.用Swing的进度条显示文件打开的进度2.逐行/字(词)显示打开的文件内容分不多求大神急用...
要求1.用Swing的进度条显示文件打开的进度
2.逐行/字(词)显示打开的文件内容
分不多求大神 急用 展开
2.逐行/字(词)显示打开的文件内容
分不多求大神 急用 展开
展开全部
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.List;
/**
* @author Hardneedl
*/
final class ProgressDemo extends JFrame {
public String getTitle() {return "ProgressDemo";}
static private final Dimension size = new Dimension(600,400);
public Dimension getPreferredSize() {return size;}
public Dimension getMaximumSize() {return size;}
public Dimension getMinimumSize() {return size;}
public Dimension getSize(){return size;}
private JTextArea textArea;
private JProgressBar bar;
private class ReadSwingWork extends SwingWorker<String,String>{
private File file;
private JTextArea area;
private int pro=0;
private ReadSwingWork(File f, JTextArea area) {
file=f;
this.area=area;
}
protected String doInBackground() throws Exception {
FileInputStream fileReader=new FileInputStream(file);
int maxLen = fileReader.available();
byte buf[]=new byte[1];
String s = null;
while (fileReader.read(buf)!=-1) {
s = new String(buf);
publish(s);
setProgress( 100*(pro++)/maxLen );
}
fileReader.close();
return s;
}
protected void process(List<String> chunks) {
for (String s:chunks)
area.append(s);
}
}
private class OpenFileAction extends AbstractAction{
private JFileChooser chooser;
private OpenFileAction() {
super("Open...");
}
public void actionPerformed(ActionEvent e) {
textArea.setText(null);
if(chooser==null){
chooser=new JFileChooser(".");
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setMultiSelectionEnabled(false);
chooser.setDialogTitle("open file");
}
if(chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){
File file=chooser.getSelectedFile();
if (file!=null){
SwingWorker work=new ReadSwingWork(file,textArea);
work.addPropertyChangeListener(new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
if("progress".equals(evt.getPropertyName())){
bar.setValue((Integer) evt.getNewValue());
}
}
});
work.execute();
}
}
}
}
ProgressDemo() throws HeadlessException {
init();
attachListeners();
doLay();
}
private void init(){
textArea=new JTextArea();
bar=new JProgressBar(0,100);
}
private void attachListeners(){
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private void doLay(){
final Container container = getContentPane();
container.add(new JButton(new OpenFileAction()),BorderLayout.NORTH);
container.add(new JScrollPane(textArea),BorderLayout.CENTER);
container.add(bar,BorderLayout.SOUTH);
pack();
setVisible(true);
}
public static void main(String...args) {
System.setProperty("swing.defaultlaf","com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(
new Runnable(){
public void run() {
new ProgressDemo();
}
}
);
}
}
2013-07-13
展开全部
为你加油~~~~
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询