我对文件过滤器有疑问。我实际上只是按照 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());
最佳答案
在打开过滤器之前设置它...
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());
关于java - 文件选择器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29001373/