package com.D;
/*
- 用图形界面做一个查找文件并在可以打开该文件的软件 */ import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader;
import javax.swing.*;
public class FileAndFrame {
JButton button;
JTextField filePathText;
JTextArea fileContentArea;
JFileChooser fileChooser;
BufferedReader reader;
//创建一个窗口 上面含有一个文本框 和一个按钮,文本框用来获取要查找的文件名,按钮时用来打开文件的,下面是文本域用来显示文件的内容
public JPanel createPanel()
{
JPanel mainPanel=new JPanel(new BorderLayout());
JPanel top=new JPanel();
button =new JButton("打开文件");
button.addActionListener(new Mo());
filePathText=new JTextField(20);
top.add(filePathText);
top.add(button);
mainPanel.add(top,BorderLayout.NORTH);
fileContentArea=new JTextArea();
fileContentArea.setWrapStyleWord(true);
fileContentArea.setLineWrap(true);
mainPanel.add(fileContentArea);
mainPanel.setVisible(true);
return mainPanel;
}
private class Mo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
File openFile=new File(" ");
if(openFile!=null)
{
fileChooser=new JFileChooser(openFile.getParentFile());
}
else
{
fileChooser=new JFileChooser();
}
int state =fileChooser.showOpenDialog(null);
if(state==JFileChooser.APPROVE_OPTION)
{
File openFile1=fileChooser.getSelectedFile();
filePathText.setText(openFile1.getPath());
showFileContent(openFile1);
}
}
private void showFileContent(File openFile)
{
reader=new BufferedReader(new FileReader(openFile));
String temp=null;
while(temp=reader.readLine()!=null)//该行报错!!
{
fileContentArea.append(temp);
}
}
}
public static void main(String[] args)
{
JFrame f=new JFrame("文件寻找窗口");
f.setSize(300,250);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con=f.getContentPane();
con.add(new FileAndFrame().createPanel());
f.setVisible(true);
}
}
请各位指点!