JFileChooser怎么判断选中的是单个文件 还是文件夹
时间: 2024-01-26 07:03:22 浏览: 32
要判断用户在 JFileChooser 中选择的是单个文件还是文件夹,可以使用 JFileChooser 的方法 `isFileSelectionEnabled()` 和 `isDirectorySelectionEnabled()` 来判断选择模式。
下面是一个示例代码,演示如何判断选择的是单个文件还是文件夹:
```java
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
public class Example {
public static void main(String[] args) {
JFileChooser fileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
if (fileChooser.isFileSelectionEnabled() && !fileChooser.isDirectorySelectionEnabled()) {
System.out.println("选中的是单个文件");
} else if (!fileChooser.isFileSelectionEnabled() && fileChooser.isDirectorySelectionEnabled()) {
System.out.println("选中的是文件夹");
} else {
System.out.println("选中的既是文件又是文件夹");
}
} else {
System.out.println("用户取消了选择");
}
}
}
```
在上面的示例代码中,我们创建了一个 JFileChooser 对象,并将选择模式设置为 `FILES_AND_DIRECTORIES`,允许用户选择文件和文件夹。然后,通过判断 `isFileSelectionEnabled()` 和 `isDirectorySelectionEnabled()` 的返回值,确定用户选择的是单个文件还是文件夹。