我有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,以自动编写代码来执行某些操作,例如将这些项添加到列表或哈希映射中。