Java 从文件夹加载所有图像并从中生成命名图像

Java 从文件夹加载所有图像并从中生成命名图像,java,image,object,loading,Java,Image,Object,Loading,标题有点杂乱无章,但不确定最好的描述方式。还是一个从Obj-C转换过来的javanewb,所以我知道如何编码,但不确定是否/如何在Java中具体应用 基本上,我想这样做: ImageIcon a0amora = new ImageIcon(this.getClass().getResource("resource/" + "a0amora.png")); ImageIcon a1act1 = new ImageIcon(this.getClass().getResource("resource/

标题有点杂乱无章,但不确定最好的描述方式。还是一个从Obj-C转换过来的javanewb,所以我知道如何编码,但不确定是否/如何在Java中具体应用

基本上,我想这样做:

ImageIcon a0amora = new ImageIcon(this.getClass().getResource("resource/" + "a0amora.png"));
ImageIcon a1act1 = new ImageIcon(this.getClass().getResource("resource/" + "a1act1.png"));
ImageIcon a2hello = new ImageIcon(this.getClass().getResource("resource/" + "a2hello.png"));
ImageIcon a3anyonethere = new ImageIcon(this.getClass().getResource("resource/" + "a3anyonethere.png"));
ImageIcon a4imhere = new ImageIcon(this.getClass().getResource("resource/" + "a4imhere.png"));
ImageIcon a5stuck = new ImageIcon(this.getClass().getResource("resource/" + "a5stuck.png"));
ImageIcon a6silence = new ImageIcon(this.getClass().getResource("resource/" + "a6silence.png"));
ImageIcon a7ashamed = new ImageIcon(this.getClass().getResource("resource/" + "a7ashamed.png"));
ImageIcon a8free = new ImageIcon(this.getClass().getResource("resource/" + "a8free.png"));
ImageIcon a9endact = new ImageIcon(this.getClass().getResource("resource/" + "a9endact.png"));
但是在一个程序中,将读取文件夹中的所有PNG,并以文件名命名一个新的ImageIcon,因此我不必手动分配每个PNG

在服务器上找到该目录的“真实路径”。使用它来建立文件对象。 为PNG创建一个文件。 在该源目录上使用。它将返回一个包含PNG文件引用的文件[]。
这是假设图像作为松散的文件资源位于类路径上。如果它们在Jar中,我们必须迭代Jar的ZipEntry对象以动态发现它包含的内容。

我会列出目标目录中的文件,并将它们全部添加到类似以下内容的映射中

File  directory = new File("resource");
Map<String, ImageIcon> iconMap = new HashMap<String, ImageIcon>();

for (File file : directory.listFiles())
{
    // could also use a FileNameFilter
    if(file.getName().toLowerCase().endsWith(".png"))
    {
        iconMap.put(file.getName(), new ImageIcon(file.getPath()));
    }
}

如果您使用的是Java 8,您可以尝试以下方法:

public List<ImageIcon> get(){
    final FileFilter filter = f -> f.getName().endsWith(".png");
    final File res = new File(getClass().getResource("resource").getPath());
    return Arrays.asList(res.listFiles(filter)).stream().map(f -> new ImageIcon(f.getPath())).collect(Collectors.toList());
}

如果您不是,那么修改代码就不会那么难了,不过您已经知道了大概的想法。

这是不可能的。不能以编程方式生成新的命名变量。您可以将它们存储在一个映射中,这样您就可以调用map.geta0amora,它将返回正确的资源。不幸的是,由于这些都是jar文件中的资源,您必须使用ZipInputStream来扫描jar中的资源。或者,您可以添加一个列出所有资源的附加文件,并使用该文件获取图标。@ChrisBode:您可以使用自动生成的源代码。如果您使用“复制粘贴”来编写部分代码,则表示您做错了。这将非常方便。要么这样做,要么按照Chris的建议使用HashMap。构造函数ImageIconFile不存在。@JoshM很好。我想这就是我在不经过编译器的情况下更改答案中的代码所得到的。修复了传入文件名而不是文件名的示例。我认为您查找的是file.getPath,而不是file.getname。我最终使用了这个示例。不过,它需要一些修改才能正常运行和工作。谢谢