Search code examples
javaswingfullscreenjlabelcentering

JLabel doesn't center on full screen


On my JFrame I have a GridLayout(5,5). In one of the cells I have a CellPanel which extends JPanel in which I add a JLabel with an ImageIcon. I'm centering the JLabel but when I set my window to full screen the JLabel isn't center anymore. Any idea why? Also I would like to scale the JLabel when the window is full screen. JFrame size is 640x480.

Part of my code:

 for(int i=0; i<25; i++)
    {
        switch(i){
        case(0):
            icon = new ImageIcon("Resurse/entrance.png");
            cell = new CellPanel(icon.getImage());
            break;
        case(22):
            icon = new ImageIcon("Resurse/exit.png");
            cell = new CellPanel(icon.getImage());
            break;
        case(5):
            icon = new ImageIcon("Resurse/ground.png");
            cell = new CellPanel(icon.getImage());
            footPrint = new JLabel();
            iconSolver = new ImageIcon("Resurse/fading.png"); 
            footPrint.setIcon(iconSolver);
            footPrint.setHorizontalAlignment(JLabel.CENTER);
            footPrint.setVerticalAlignment(JLabel.CENTER);
            cell.add(footPrint);
            break;
            ...
       }
   } 

Normal size: enter image description here

Full screen: enter image description here


Solution

  • Key question: what layout do your cell JPanels use?

    You're using FlowLayout, so the JLabel defaults to its preferredSize and is placed top center, exactly what you're seeing.

    I'd go with either BorderLayout or GridBagLayout. The latter, the GridBagLayout will center a component added automatically, leaving it at its preferred size, if only one component is added and added without grid bag constraints. I've used this in a chess program for centering the chess pieces in the chess board cell. The BorderLayout with the label being added BorderLayout.CENTER will have your JLabel fill the cell JPanel, and that could work too if the JLabel's image centers when the JLabel is expanded.

    Some side recs:

    • Avoid re-reading your images in as your code seems to be doing. Instead consider reading your images in once, storing them in ImageIcon variables, and then using the icons as needed. The main risk of this recommendation is if your images are quite large, and in that situation you will have to watch memory constraints.