我想创建一个方法,以便我可以在我的源文件夹中加载所有图像,而无需为每个图像编码每一行,但我不断收到错误,并尝试了不同的方法来执行此操作,我仍然可以'想通了。这不可能吗?
以下是它的工作原理:我将所有需要的图像保存在文本文件中(在本例中为startUp.txt
),然后将文本文件中的行存储在链表中(String )然后我使用循环来获取图像并将它们存储在链表(图像)中,这样我就不需要为每个要加载的图像编写代码。
这是我的代码:
package com.game.task;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
import javax.swing.ImageIcon;
public class imagesTest {
public LinkedList<Image> storeImages = new LinkedList<Image>();
private LinkedList<String> storeStrings = new LinkedList<String>();
public imagesTest() {
load();
readimage();
}
public void readimage() {
for(int index = 0; index < storeStrings.size(); index++){
Image temp = new ImageIcon(this.getClass().getClassLoader().getResource("/res/"+storeStrings.get(index))).getImage();
storeImages.add(temp);
}
}
private void load() {
File file = new File("Data/startUp.txt");
try {
Scanner read = new Scanner(file);
while (read.hasNextLine()) {
storeStrings.add(read.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] arsg) {
imagesTest t = new imagesTest();
}
}
例外:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
at com.game.task.imagesTest.readimage(imagesTest.java:24)
at com.game.task.imagesTest.load(imagesTest.java:41)
at com.game.task.imagesTest.<init>(imagesTest.java:17)
at com.game.task.imagesTest.main(imagesTest.java:45)
答案 0 :(得分:0)
我找到了循环资源文件夹的方法,并没有那么难。 所有我必须使用make方法并继续在循环中调用它是代码
package com.game.task;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
import javax.swing.ImageIcon;
public class imagesTest {
public LinkedList<Image> storeImages = new LinkedList<Image>();
private LinkedList<String> storeStrings = new LinkedList<String>();
public imagesTest() {
load();
start();
}
public void readimage(String f) {
Image temp = new ImageIcon(this.getClass().getResource("/res/"+f)).getImage();//looks for it
storeImages.add(temp);//put it in a linked-List(Image)
}
public void start(){
for(int index = 0; index < storeStrings.size(); index++){
readimage(storeStrings.get(index));//calling the methode to look in resource folder
}
}
//reads the text file and puts the out put in a linked-list(String)
private void load() {
File file = new File("Data/startUp.txt");
try {
Scanner read = new Scanner(file);
while (read.hasNextLine()) {
storeStrings.add(read.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] arsg) {
imagesTest t = new imagesTest();
}
}