我尝试查找这个问题,但大多数答案都是文件路径错误,但情况很可能不是这样。该文件在我第一次使用时有效。
我正在制作战舰游戏,并使用 JLabels 在 map 上显示船只。我想制作一个按钮将船从水平旋转到垂直,但当我尝试更改它时,它的图标消失了。
当我运行此构造函数代码时:
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 上的图标。
最佳答案
如果您通过调用更改其状态的方法来更新 JLabel 纹理
,它可能会也可能不会立即更新,除非您调用 texture.repaint()
或 texture.paintAll(texture.getGraphics())
,或一些类似的方法。
另外,我会考虑对您用来保存 JLabels 网格的任何上层组件使用 LayoutManager
。如果您使用游戏板的 GridLayout
且:
使用
texture.setPreferredSize(Dimension)
设置 JLabel 的首选尺寸,并在设置游戏时调用frame.pack()
一次;或使用
label.setSize(Dimension)
设置 JLabel 的大小一次,并且不打包 JFrame
您只需要设置 JLabel 的大小一次,而不是每次为标签设置新的 ImageIcon 时。因为,理想情况下,您的游戏不应该执行任何不必要的额外工作,这样它的执行速度会更快。
我还建议将每个可能的 ImageIcon 维护为类中的静态字段,而不是每次都从文件访问它们。这样,您可以从静态初始化方法中读取它们一次,然后到达船可以在改变方向时直接访问。
关于java - 更改后 JLabel 图标不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23837424/