njl
njl

Reputation: 57

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()

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)

How do I get the above code to add JLabels with icons?

(on a separate note, what's this kind of object construction called, where you just "add new JLabel" dynamically rather than initialising it before?)

Upvotes: 0

Views: 311

Answers (1)

Kezz
Kezz

Reputation: 1678

Unlike the constructor for a JLabel, the setIcon function doesn't return anything (or returns 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. It is, surprisingly, called Dynamic Object Construction.

Upvotes: 2

Related Questions