Search code examples
javaswingjframejlabelbluej

Java Positioning Problem of JLabel in JFrame


I´m creating a TileMap out of JLabels and my Problem is that the last Tile is not placed right. For some reason the last JLablel is on a wrong position. I think this Image:

https://i.sstatic.net/0KpSb.png

and the Code explains what my problem is.

Btw. I am using BlueJ (maybe there is a bug in it, that I dont know)

Thanks for help!!!

    //create Frame
    this.setSize((size+2)*imageSize+16,(size+2)*imageSize+39);
    this.addKeyListener(this);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.getContentPane().setBackground(Color.black);
    this.setVisible(true);
    //create MapJLabels
    for(int x = 0;x<size;x++){
        for(int y = 0;y<size;y++){
            mapJLabels[x][y] = new JLabel();
            this.add(mapJLabels[x][y]);
            mapJLabels[x][y].setSize(imageSize,imageSize);
            mapJLabels[x][y].setLocation((x+1)*imageSize,(y+1)*imageSize);
            mapJLabels[x][y].setVisible(true);
        }
    }

Solution

    1. The code is attempting to set the size/location of the component. This implies you are using a null layout. Don't. Swing was designed to be used with layout managers. You should use the GridLayout. Read the section from the Swing tutorial on Layout Managers for more information.

    2. You create an empty JLabel. By default a JLabel is transparent. I'm not sure now the picture you posted is created from the code you posted. I don't see how the grid is populated with images etc.

    3. Swing components are visible by default so there is no need for the setVisible(true)

    4. Your code attempts to set the size of the frame. Again, don't. When using layout managers you just pack() the frame and the size will be calculated automatically.

    5. Your code attempts to leave space between the frame and labels. Don't. If you want extra space you can add an EmptyBorder to the panel. Read the section from the Swing tutorial on How to Use Borders

    6. You code is using a KeyListener. Don't. Swing was designed to be used with Key Bindings

    7. Components should be added to the frame BEFORE the frame is made visible.

    The posted code looks reasonable, but since we can't see where you change the background of the labels or where you add icons to the labels, we don't know what the rest of your logic is doing. The problem could be there.

    If you need more help after fixing the above problems then post a proper minimal, reproducible example that demonstrates your new problem.