我正在学习本教程:
http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
这样我就可以学习如何在我正在构建的GUI中使用文件选择器,但是我下载的源文件与教程不匹配,每当我按GUI中的按钮时,我就会收到错误消息。
if (e.getSource() == saveButton) {
FileSaveService fss = null;
FileContents fileContents = null;
ByteArrayInputStream is = new ByteArrayInputStream(
(new String("Saved by JWSFileChooserDemo").getBytes()));
//XXX YIKES! If they select an
//XXX existing file, this will
//XXX overwrite that file.
try {
fss = (FileSaveService)ServiceManager.
lookup("javax.jnlp.FileSaveService");
} catch (UnavailableServiceException exc) { }
if (fss != null) {
try {
fileContents = fss.saveFileDialog(null,
null,
is,
"JWSFileChooserDemo.txt");
} catch (Exception exc) {
log.append("Save command failed: "
+ exc.getLocalizedMessage()
+ newline);
log.setCaretPosition(log.getDocument().getLength());
}
}
if (fileContents != null) {
try {
log.append("Saved file: " + fileContents.getName()
+ "." + newline);
} catch (IOException exc) {
log.append("Problem saving file: "
+ exc.getLocalizedMessage()
+ newline);
}
} else {
log.append("User canceled save request." + newline);
}
log.setCaretPosition(log.getDocument().getLength());
}
}我正在取消用户的保存请求。
发布于 2014-12-19 14:24:34
您的主要问题是,您的fileContents可能是null,而不是您所知道的。造成这种情况的原因有两个:
saveFileDialog返回null。这是你实际得到的信息,但是错误的来源可能是不同的;saveFileDialog的扩展参数null.。如果引发了异常,那么很高兴知道它,所以我建议您向日志中添加一条消息(参见下面的代码)。解决方案:--您应该记录UnavailableServiceException以跟踪异常,并且应该尊重saveFileDialog方法原型(以避免任何歧义),如下所述:FileSaveService接口。
这是您的代码的一部分,其中应用了前面的建议:
try {
fss = (FileSaveService)ServiceManager.lookup("javax.jnlp.FileSaveService");
} catch (UnavailableServiceException exc) {
log.append("A problem occurred while accessing the service manager." + newline);
}
if (fss != null) {
try {
fileContents = fss.saveFileDialog(null, { "txt" }, is, "JWSFileChooserDemo");
}
/* Your previous code */
}
/* Your previous code */如果这不能解决你的问题,这至少会给你更多的信息,它的来源。
https://stackoverflow.com/questions/27565458
复制相似问题