这个程序的作用是选择文件 ,然后在JTextArea中显示文件的内容~一般是选择TXT文件,过滤器还没写~
我现在是把OpenAction写成了myFrame1的内部类,所以可以用外面的JTextArea~但现在我想把类的分开,不想放在内部,不知道怎么改。
另外 这个JTextArea没有滚动条~麻烦大家帮我改下~谢谢了
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class OpenFile {
public static void main(String[] args)
{
myFrame1 frame =new myFrame1("文件选择器");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class myFrame1 extends JFrame{
private myPanel1 p1;
private JTextArea text;
//private JScrollPane jScrollPane1;
//private JLabel lab1;
public myFrame1(String str)
{
super(str);
p1=new myPanel1();
text = new JTextArea();
this.add(p1,"North");
this.add(text);
setSize(400,400);
setLocation(200, 200);
}
public class OpenAction implements ActionListener{
public void actionPerformed(ActionEvent event)
{
BufferedReader inFile=null;
JFileChooser chooser = new JFileChooser(",");
int result = chooser.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION)
{
try{
String path = chooser.getSelectedFile().getAbsolutePath();
inFile=new BufferedReader(new FileReader(path));
text.setText("");
String line;
while((line=inFile.readLine())!=null)
{
text.append(line+"\n");
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
finally{
try{
inFile.close();
}
catch(IOException e){
System.out.println(e.toString());
}
}
}
else
{
System.out.println("你已取消并关闭了窗口!");
}
}
}
class myPanel1 extends JPanel{
private JButton b1;
private JLabel lab1;
public myPanel1(){
b1=new JButton("选择文件");
b1.setToolTipText("选择你要打开的文件");
b1.addActionListener(new OpenAction());
lab1=new JLabel("显示信息");
setLayout(new FlowLayout(FlowLayout.LEFT));
add(b1);
add(lab1);
}
}
}