有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

更改后未显示java JLabel图标

我试图查找这个问题,但大多数答案是文件路径错误,但很可能不是这样。这个文件在我第一次使用时就可以使用了

我正在制作一个战舰游戏,并使用jlabel在地图上显示战舰。我想做一个按钮,使船舶从水平旋转到垂直,但它的图标消失时,我试图改变它

当我运行此构造函数代码时:

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上的图标enter image description here


共 (2) 个答案

  1. # 1 楼答案

    I want to make a button to rotate ship from horizontal to vertical

    您可以使用Rotated Icon类为您执行旋转

  2. # 2 楼答案

    如果通过调用更改其状态的方法来更新JLabel texture,则可能会立即更新,也可能不会立即更新,除非调用texture.repaint()texture.paintAll(texture.getGraphics())或其他类似方法

    此外,我还将研究使用LayoutManager作为您用来保存jlabel网格的任何上层组件。如果您使用游戏板的GridLayout,并且:

    1. texture.setPreferredSize(Dimension)设置JLabel的首选大小,并在设置游戏时调用frame.pack()一次;或

    2. label.setSize(Dimension)设置JLabel的大小一次,不要打包JFrame

    只需设置一次JLabel的大小,而不是每次为标签设置新的ImageIcon。因为,理想情况下,你的游戏不应该做任何额外的工作,它不必这样做,所以它执行得更快

    我还建议将每个可能的ImageIcon作为类中的静态字段进行维护,而不是每次都从文件中访问它们。这样,您就可以从静态初始化方法中读取它们一次,然后在更改方向时可以直接访问这些方法