简体   繁体   English

基本Java Swing - 在运行时添加带有图标的JLabel

[英]Basic Java Swing - adding JLabels with icons at runtime

I'm making a grid containing icons representing a game map, and this grid will sometimes need to be redrawn. 我正在制作一个包含代表游戏地图的图标的网格,这个网格有时需要重新绘制。 I'm working my way up from the basics. 我正在从基础工作中走出来。 Here's some code I got working 这是我工作的一些代码

    int i = 1;
    while (i < 50) {
            pnlMap.add(new JLabel(String.valueOf(i)));
        i += 1;
    }

Now I want the JLabels to display icons, but I can't figure out the syntax for the arguments on pnl.add() 现在我希望JLabels显示图标,但我无法弄清楚pnl.add()上参数的语法

I imagine it's something like 我想它就像是

pnlMap.add(new JLabel("").setIcon(new ImageIcon(ClientGUI.class .getResource("/resources/wall.jpg"))));

As you can guess this doesn't work. 你可以猜到这不起作用。 Error: The method add(Component) in the type Container is not applicable for the arguments (void) 错误: The method add(Component) in the type Container is not applicable for the arguments (void)

How do I get the above code to add JLabels with icons? 如何使用上面的代码添加带有图标的JLabel?

(on a separate note, what's this kind of object construction called, where you just "add new JLabel" dynamically rather than initialising it before?) (在另一个注释中,这种对象构造叫什么,你只是动态地“添加新的JLabel”而不是之前初始化它?)

Unlike the constructor for a JLabel , the setIcon function doesn't return anything (or returns void ). JLabelsetIcon函数不同, setIcon函数不返回任何内容(或返回void )。 This means your code looks a bit like this: 这意味着您的代码看起来有点像这样:

pnlMap.add(void);

Which is why that error is being thrown. 这就是抛出错误的原因。

Therefore, only a slight modification of your code is needed to make your loop work. 因此,只需稍微修改代码即可使循环工作。

int i = 1;
while (i < 50) {
    JLabel label = new JLabel(String.valueOf(i));
    label.setIcon(new ImageIcon(ClientGUI.class .getResource("/resources/wall.jpg")));
    pnlMap.add(label);
    i += 1;
}

Edit: In answer to your question about the new JLabel() construction in your code. 编辑:回答有关代码中new JLabel()构造的问题。 It is, surprisingly, called Dynamic Object Construction. 令人惊讶的是,它被称为动态对象构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM