用反射的功能来优化这段代码使其能在jar包程序运行时顺利显现图片:public static Image upImg = Toolkit.getDefaultToolkit().getImage("img/up.png"); public static Image downImg = Toolkit.getDefaultToolkit().getImage("img/down.png"); public static Image leftImg = Toolkit.getDefaultToolkit().getImage("img/left.png"); public static Image rightImg = Toolkit.getDefaultToolkit().getImage("img/right.png"); //蛇身 public static Image bodyImg = Toolkit.getDefaultToolkit().getImage("img/body.png"); //食物 public static Image foodImg = Toolkit.getDefaultToolkit().getImage("img/food.png");
时间: 2024-03-25 21:38:30 浏览: 56
在jar包程序运行时,需要使用 ClassLoader 来加载资源。可以使用以下代码来实现:
```
public static Image upImg;
public static Image downImg;
public static Image leftImg;
public static Image rightImg;
public static Image bodyImg;
public static Image foodImg;
static {
String[] imageNames = {"up.png", "down.png", "left.png", "right.png", "body.png", "food.png"};
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
for (int i = 0; i < imageNames.length; i++) {
String imagePath = "img/" + imageNames[i];
try {
images[i] = ImageIO.read(classLoader.getResource(imagePath));
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这样就可以在jar包程序中正确加载图片了。
阅读全文