[英]How do I get JFileChooser to treat a folder as a directory?
I am trying to select all the files from a folder with a JFileChooser 我正在尝试使用JFileChooser从文件夹中选择所有文件
.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
but this doesn't let me select the folder it only lets me open it. 但这不能让我选择文件夹,而只能让我打开它。 So how would i be able to select a folder with JFileChooser and then input all the files in the selected folder without having to actually select each file individually because there might be a lot of file in the folder in the future. 因此,我如何能够使用JFileChooser选择一个文件夹,然后输入所选文件夹中的所有文件,而不必实际单独选择每个文件,因为将来该文件夹中可能有很多文件。 My whole code looks like this 我的整个代码看起来像这样
public class PicTest
{
public static void main(String args[])
{
File inFile,dir;
File[] list;
Image pic[] = new Image[50];
JFileChooser choose = new JFileChooser();
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int status = choose.showOpenDialog(null);
if(status == JFileChooser.APPROVE_OPTION)
{
dir = choose.getCurrentDirectory();
try
{
inFile = new File(choose.getSelectedFile().getAbsolutePath());
list = dir.listFiles();
for(int i=0; i < pic.length-1; i++)
{
BufferedImage buff = ImageIO.read(inFile);
pic[i] = buff;
}
}
catch(IOException e)
{
System.out.println("Error");
}
}
}
}
From your code, you don't seem to need to. 从您的代码中,您似乎不需要。 Simply allow the user to select the directory you want to process and use File#listFiles
to get it's contents 只需允许用户选择您要处理的目录并使用File#listFiles
来获取其内容
You would then iterate over this list and read each file, for example.. 然后,您将遍历此列表并读取每个文件。
Image pic[] = null;
JFileChooser choose = new JFileChooser();
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int status = choose.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
File dir = choose.getCurrentDirectory();
if (dir.exists()) {
File[] list = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return name.endsWith(".png")
|| name.endsWith(".jpg")
|| name.endsWith(".jpeg")
|| name.endsWith(".bmp")
|| name.endsWith(".gif");
}
});
try {
// Only now do you know the length of the array
pic = new Image[list.length];
for (int i = 0; i < pic.length; i++) {
BufferedImage buff = ImageIO.read(list[i]);
pic[i] = buff;
}
} catch (IOException e) {
System.out.println("Error");
}
}
}
The simple code below, allows me to select a directory and click Open , which will return the directory selected as the selected file when request... 下面的简单代码使我可以选择一个目录,然后单击Open ,这将在请求时返回选择为所选文件的目录...
JFileChooser choose = new JFileChooser();
choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (choose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
System.out.println(choose.getSelectedFile());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.