【发布时间】:2014-07-13 07:07:50
【问题描述】:
我尝试查找此问题,但大多数答案是文件路径错误,但很可能并非如此。该文件在我第一次使用时有效。
我正在制作战舰游戏,并使用 JLabels 在地图上显示战舰。我想制作一个按钮来将船从水平旋转到垂直,但是当我尝试更改它时它的图标消失了。
当我运行这个构造函数代码时:
public Ship(int size, String direction, boolean active, Client c,
ClientGUI cg) {
this.c = c;
this.cg = cg;
health = size;
this.active = active;
this.direction = direction;
file = "img/" + Integer.toString(health) + direction + ".png"; // String
try {
System.out.println(file);
tx = ImageIO.read(new File(file)); // BufferedImage
} catch (IOException e) {
e.printStackTrace();
}
texture = new JLabel(new ImageIcon(tx));
if (direction.equals("v"))
texture.setBounds(0, 0, 40, 40 * size);
else
texture.setBounds(0, 0, 40 * size, 40);
texture.setVisible(true);
}
一切正常,我可以看到图像。
然后我尝试旋转它,使用几乎相同的代码:
void rotate() {
if (direction.equals("h")) {
direction = "v";
file = "img/" + Integer.toString(health) + direction + ".png";
try {
System.out.println(file);
tx = ImageIO.read(new File(file));
} catch (IOException e) {
e.printStackTrace();
}
texture.setBounds(0,0,40, 40 * size);
texture.setIcon(new ImageIcon(tx));
} else {
direction = "h";
file = "img/" + Integer.toString(health) + direction + ".png";
try {
System.out.println(file);
tx = ImageIO.read(new File(file));
} catch (IOException e) {
e.printStackTrace();
}
texture.setIcon(new ImageIcon(tx));
texture.setBounds(0,0,40 * size, 40);
}
cg.repaint(); // not sure if I need to do this
}
然后它就消失了……
我试过放置两艘船,一艘是旋转的,只是缺少 JLabel 或 JLabel 上的图标。
【问题讨论】:
-
谷歌“我如何比较 Java 中的字符串”。我懒得链接了
-
非常糟糕的字符串比较以这种方式
direction == "h"是错误的。 -
@Braj 好的,我已修复,但这与我的问题无关
-
我怎么知道它没有引起问题?这是朝着解决这个问题迈出的重要一步。
-
文件存储在哪里?它们是在 src 中还是在外部文件中