我对文件过滤器有疑问。我实际上只是按照Oracle的教程,但它似乎没有用。所以我寻找其他问题。应用它仍然过滤器不会工作。我怎么也得不到文件的文件名。我得到空指针。为什么是这样?谢谢你的帮助!
以下是代码:
StringBuilder sb = new StringBuilder();
if (e.getSource() == btnMassEncode) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fc.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Portable Network Graphics (*.png)";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
} else {
return f.getName().toLowerCase().endsWith(".png");
}
}
});
fc.setAcceptAllFileFilterUsed(false);
File file = fc.getSelectedFile();
// This is where a real application would open the file.
sb.append("Opening: " + file.getName());
} else {
sb.append("Open command cancelled by user.");
}
}
System.out.println(sb.toString());
答案 0 :(得分:3)
在打开过滤器之前设置过滤器......
StringBuilder sb = new StringBuilder();
if (e.getSource() == btnMassEncode) {
fc.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Portable Network Graphics (*.png)";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
} else {
return f.getName().toLowerCase().endsWith(".png");
}
}
});
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
// This is where a real application would open the file.
sb.append("Opening: " + file.getName());
} else {
sb.append("Open command cancelled by user.");
}
}
System.out.println(sb.toString());