我的问题是,当我出现showopendialog
时,我按取消或右上角的X而不是在文本区域中加载某些文本,控制台在我的nullpointexception
行上显示了String filename=f.getAbsolutePath();
的错误
我打开的动作在菜单栏上。
谢谢。
JFileChooser flcFile = new JFileChooser("c:\\");
flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
String filename=f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
txtPersonal.read(br, null);
br.close();
txtPersonal.requestFocus();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
如果关闭但未选择文件,则无法获取文件的绝对路径。始终通过检查showOpenDialog()
方法返回的值来检查用户是否选择了文件。进行此检查后,才获取绝对路径。
有用的阅读:The JFileChooser docs。
JFileChooser flcFile = new JFileChooser("c:\\");
int result = flcFile.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File f = flcFile.getSelectedFile();
String filename = f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
txtPersonal.read(br, null);
br.close();
txtPersonal.requestFocus();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
您好,我修改了您的代码,请检查以下示例:
public class Main {
public static void main(String[] args) {
JFileChooser flcFile = new JFileChooser("c:\\");
int result = flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
if (JFileChooser.CANCEL_OPTION == result) {
System.out.println("canceled");
} else if (JFileChooser.APPROVE_OPTION== result) {
String filename = f.getAbsolutePath();
System.out.println(filename);
}else{
System.out.println(result);
}
}
}
您需要检查showOpenDialog
方法的返回值才能知道所选的选项,希望对您有所帮助
欢呼。
谢谢你的小鸭
PS .......
快速快速的母亲滑板声,OLOLOLOLOLOLOLOLOLOL