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);
}
}
结果,程序报错:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at sun.awt.shell.Win32ShellFolder2$7.call(Unknown Source)
at sun.awt.shell.Win32ShellFolder2$7.call(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2$ComInvoker.invoke(Unknown Source)
at sun.awt.shell.ShellFolder.invoke(Unknown Source)
at sun.awt.shell.ShellFolder.invoke(Unknown Source)
at sun.awt.shell.Win32ShellFolder2.getFileSystemPath(Unknown Source)
at sun.awt.shell.Win32ShellFolder2.access$300(Unknown Source)
at sun.awt.shell.Win32ShellFolder2$11.call(Unknown Source)
at sun.awt.shell.Win32ShellFolder2$11.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
求各位赐教,谢谢啊。
------解决方案--------------------
跑了下,没有错呀~~~可以正常选择,正常显示,没有报任何错误,囧
建议:
1.找到空指针地方吧
2.类名大写
3. jc = new JFileChooser();这个可以放外面,否则每次点都new 一个
------解决方案--------------------
看错了。。。
你直接把你的类继承jframe试试,代码跑的没问题。。。