Java 如何从多个图像文件快速创建图标(在键入的代码中)?

Java 如何从多个图像文件快速创建图标(在键入的代码中)?,java,image,swing,import,Java,Image,Swing,Import,我有100多张图像需要与新创建的ImageIcon对象关联。如何才能比手动输入每个图像更快地导入它们 ImageIcon imagefile = new ImageIcon("imagefile") 我正在用Eclipse编写代码。您可以编写一些代码来为您编写代码(如果您需要这样做的话) 然后,一旦代码被输出,您就可以将其复制/粘贴到应用程序中的类中 例如,这样做可以节省您大量的键入时间: import java.io.*; public class CodeWritingDemo {

我有100多张图像需要与新创建的
ImageIcon
对象关联。如何才能比手动输入每个图像更快地导入它们

ImageIcon imagefile = new ImageIcon("imagefile")

我正在用Eclipse编写代码。

您可以编写一些代码来为您编写代码(如果您需要这样做的话)

然后,一旦代码被输出,您就可以将其复制/粘贴到应用程序中的类中

例如,这样做可以节省您大量的键入时间:

import java.io.*;

public class CodeWritingDemo {

    public static void main(String[] args) throws Exception {
        String rootFolder = "src/res/"; // or args[0]
        File folder = new File(rootFolder);
        for (File file : folder.listFiles()) {
        if (file.getName().toLowerCase().endsWith("png") ||     file.getName().toLowerCase().endsWith("jpg")) {
                printFilename(file, "src/".length());
            }
        }
    }

    public static void printFilename(File file, int stripIndex) {
        String variableName = file.getName().replaceAll("[.]", "_");
        String template = "ImageIcon " + variableName + " = new ImageIcon(\"" + file.getPath().substring(stripIndex) + "\")";
        System.out.println(template);
    }
}

如果需要,可以修改printFilename方法中的System.out.println,以自动编写代码来执行某些操作,例如将这些项添加到列表或hashmap中

一种方法是创建一个ant/maven/which任务,该任务在Jar中生成并包含一个图像列表。投票以“太宽”结束。你对数组和/或集合了解多少?相当确定的问题是,他如何在一行输入100次后节省开支,。。我的建议是让他写一个方法,为他自动生成代码。@AndrewThompson我已经详细阐述了我的代码,以帮助您了解我的方法,我应该指出,当我写我的原始回复时,我没有看到任何评论。@AndrewThompson我已经清理了一点帖子(有更清晰的说明)和其他小的编辑。我还删除了我的嘈杂评论。另请参见&。