📅  最后修改于: 2020-09-30 09:22:43             🧑  作者: Mango
JFileChooser类的对象表示一个对话框,用户可以从中选择文件。它继承了JComponent类。
让我们看一下javax.swing.JFileChooser类的声明。
public class JFileChooser extends JComponent implements Accessible
Constructor | Description |
---|---|
JFileChooser() | Constructs a JFileChooser pointing to the user’s default directory. |
JFileChooser(File currentDirectory) | Constructs a JFileChooser using the given File as the path. |
JFileChooser(String currentDirectoryPath) | Constructs a JFileChooser using the given path. |
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class FileChooserExample extends JFrame implements ActionListener{
JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
FileChooserExample(){
open=new JMenuItem("Open File");
open.addActionListener(this);
file=new JMenu("File");
file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
try{
BufferedReader br=new BufferedReader(new FileReader(filepath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception ex) {ex.printStackTrace(); }
}
}
}
public static void main(String[] args) {
FileChooserExample om=new FileChooserExample();
om.setSize(500,500);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
输出: