用JFileChooser实现打开文件功能,总是报错
RT,在做界面时,希望点击“浏览...”按钮,可以实现在电脑中选择文件,选定一个文件后,该文件的路径将出现在按钮前的文本框内。
代码如下:
package tfidf;
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
public class openFile {
private JFrame frame;
private JTextField textField;
private JFileChooser jc ;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
openFile window = new openFile();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public openFile() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(34, 58, 193, 21);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton button = new JButton("浏览...");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
jc = new JFileChooser();
int result = 0;
result = jc.showOpenDialog(frame);
File f = null;
if(result==JFileChooser.APPROVE_OPTION){
f = jc.getSelectedFile();
textField.setText(f.getAbsolutePath());
}
}
});
button.setBounds(266, 57, 93, 23);
frame.getContentPane().add(button);
}
}