我有JFileChooser
并添加了2个文件扩展名过滤器,如下所示:
openFileChooser = new JFileChooser();
openFileChooser.setCurrentDirectory(new File("D:/"));
openFileChooser.setFileFilter(new FileNameExtensionFilter("OUT Files", "out"));
openFileChooser.setFileFilter(new FileNameExtensionFilter("PRN Files", "prn"));
如果我有.out文件,则我的逻辑有效,但是当我选择.prn文件时,.out文件的逻辑适用于.prn文件。我的问题是如何捕获哪种类型以及if(.out文件)->做其他事情(.prn文件)->做些什么?
答案 0 :(得分:0)
我无法清楚地理解您的问题/问题,因此,我将为您提供一个带有2个过滤器的文件选择器示例,可能会对您有所帮助。以下JFileChooser
允许用户仅选择 Mp3 和 Mp4 文件(在您的情况下是.out / .prn文件?)。阅读代码中的注释。
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
public class FileChooserExample {
public static void main(String[] args) {
String home = System.getProperty("user.home");
File desktop = new File(home, "Desktop");
JFileChooser chooser = new JFileChooser(desktop);
// Add filter for mp3 files.
chooser.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Mp3 Files";
}
@Override
public boolean accept(File f) {
// Show only mp3 Files(which can be selected) and folders (which can be OPENED)
return isMp3(f) || f.isDirectory();
}
});
// Add filter for mp4 files.
chooser.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Mp4 Files";
}
@Override
public boolean accept(File f) {
// Show only mp4 Files(which can be selected) and folders (which can be OPENED)
return isMp4(f) || f.isDirectory();
}
});
// Only files allowed. If it is a directory, do not select it but open it to
// choose files
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// Remove the "All files" filter. We want only our custom file filters to take
// action.
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
if (isMp3(selectedFile)) {
System.out.println("This is an mp3 file, and i wanna dance.");
} else if (isMp4(selectedFile)) {
System.out.println("This is an mp4 file, and i wanna grab pop corn.");
}
}
}
private static boolean isMp4(File f) {
return f.getName().toLowerCase().endsWith(".mp4");
}
private static boolean isMp3(File f) {
return f.getName().toLowerCase().endsWith(".mp3");
}
}