Java/Swing layer labels on top if each other

970 views Asked by At

I know this has been asked several times, but none of the solutions have worked for us. We are recreating a game which has a world map, and is supposed to show flags on every country. We got it working(sort of) by using a graphics method, but this was not persistent, also we couldnt adress a flag by a var name.

Thats why we want to have every flag in a JLabel, and draw them inside the gamePane, but on their specifiy coordinates. So we need to be able to position with a z-axis.

The GamePane has a JLabel with an ImageIcon inside, that should form the background. On top of that we want to create the flags

some code(might not be helpful):-

    gamePane = new JPanel();
    [...]

    public void paintFlagLabel() {
    for (Country currentCountry : risiko.getCountryList()) {
        JLabel flag = new JLabel();
        int x = currentCountry.getX();
        int y = currentCountry.getY();

        if (currentCountry.getOwningPlayer().equals(this.player)) {
            flag.setIcon(new ImageIcon(greenFlag));
        } else {
            flag.setIcon(new ImageIcon(redFlag));
        }
        String coordinates = "pos " + x + " " + y;
        gamePane.add(flag, coordinates);
        gamePane.revalidate();
        gamePane.repaint();
    }
}
1

There are 1 answers

0
camickr On

We are recreating a game which has a world map, and is supposed to show flags on every country.

You can easily add a JLabel to any other component, including a Jlabel.

The basic code is:

JLabel background = new JLabel( new ImageIcon(...) );
background.setLayout( null );

JLabel flag = new JLabel( new ImageIcon(...) );
flag.setSize( flag.getPrefferedSize() );
flag.setLocation(....);
background.add( flag );

we couldnt adress a flag by a var name.

You could keep a Hashmap of all the flags:

Hashmap<String, JLabel> flags = new Hashmap<String, JLabel>()
flags.add("theCountryName", theFlag);

Then when you want to access the flag you simply use the get(...) method of the Hashmap.