[英]NullPointerException when trying to access a file from a JFileBrowser
每次打开文件浏览器然后关闭它而不选择文件时,我会收到NullPointerException
。
@Override
public void actionPerformed(ActionEvent e) {
if(!(dndfolder.exists())) {
new File(homefolder + "DND").mkdir();
}
browse = new JFileChooser(homefolder+"DND");
returnVal = browse.showOpenDialog(loadchar);
browse.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(browse.getSelectedFile().exists()) {
sheet = browse.getSelectedFile();
}
if(sheet.exists() && sheet.getName().endsWith(".txt")) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().edit(sheet);
} catch (IOException ex) {
Logger.getLogger(panel.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
error = "*I don't really know what to put here";
repaint();
}
} else {
error = "*File type not supported";
repaint();
}
}
我可以打开文本文件但是当选择的项目不存在时它会失败。 我试着围绕它编码,但我无法让它工作。 有任何想法吗?
if(browse.getSelectedFile().exists())
如果您尚未选择文件,则browse.getSelectedFile()
可能返回null
,但您继续并在其上调用exists()
。
你应该做的事情如下:
if (browse.getSelectedFile != null && browse.getSelectedFile().exists())
您没有正确使用JFileChooser
。 返回值告诉您用户是否取消,您需要检查...
if(returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = browse.getSelectedFile();
// Do file stuff here, and nowhere else.
}
另外, returnVal = browse.showOpenDialog(loadchar);
,阻塞直到用户做某事,所以当你调用时, browse.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
之后,它什么也没做。 这是因为它只是关闭并消失的窗口之后改变选择模式。
也许你会从教程中受益: http : //docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.