0
JLabel imagine_hearth = new JLabel(new ImageIcon( new ImgUtils().scaleImage(35,35,"health.png")));
    JLabel imagine_bullet = new JLabel(new ImageIcon( new ImgUtils().scaleImage(35,35,"bullet.jpg")));
    JLabel player_icon = new JLabel();
    Board2 b2 = new Board2();
    JPanel stats = new JPanel();
    stats.setSize(100,450);
    stats.setLayout(new GridLayout(12,2));
    for(i=1; i<5 ; i++)
    {
        stats.add(new JLabel("Player " + i));
        player_icon.setIcon(new ImageIcon( new ImgUtils().scaleImage(35,35,pioni[i-1])));
        stats.add(player_icon,BorderLayout.CENTER);
        stats.add(new JLabel("X" + pl[i-1].nr_lives));
        stats.add(imagine_hearth,BorderLayout.CENTER);
        stats.add(new JLabel("X" + pl[i-1].nr_bullets));
        stats.add(imagine_bullet,BorderLayout.CENTER);
    }

this is how it looks I just started coding in java and I encountered a problem with an JLabel Grid Layout. As you can see in the code above i tried to make a matrix 12X2 with text and pictures but the program only load the pictures for the final entry and I have no idea why. I tried several options like GridBagLayout without any succes. Thanks in advance for the help.

Scurtu
  • 1
  • 1
  • You can't add a component multiple times to a container. You need to actually make a new component that looks like it and add those. – Ordous Dec 13 '16 at 20:46

1 Answers1

1

A JLabel can only have 1 parent and be in 1 location. Thus, when you add it again, it removes itself from the old location, then adds to the new one. This is regardless of layout and is behaviour that is constant among all Swing components. To fix this you will need to make several JLabels. You can still share the ImageIcon however.

ImageIcon imagine_hearth = new ImageIcon( new ImgUtils().scaleImage(35,35,"health.png"));
ImageIcon imagine_bullet = new ImageIcon( new ImgUtils().scaleImage(35,35,"bullet.jpg"));

<other code you had, *without player_icon*>
for(i=1; i<5 ; i++) {
    <loop code>
    JLabel player_icon = new JLabel(new ImageIcon( new ImgUtils().scaleImage(35,35,pioni[i-1])));
    stats.add(player_icon);
    <...>
    stats.add(new JLabel(imagine_hearth));
    <...>
    stats.add(new JLabel(imagine_bullet));
}

P.S. Underscores are typically discouraged in pure Java code (although often OK in C-style code like low-level networking). See Java Code Conventions.

Ordous
  • 3,844
  • 15
  • 25