JLabel does not align correctly with GridLayout

11,011

When using BoxLayout you have to set the alignment for any of the elements inside.

As this example follows: http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html

Fixing Alignment Problems

You have to set alignment to your lab and yourGrid

lab.setHorizontalAlignment(SwingConstants.LEFT);
yourGrid.setAlignmentX(Component.LEFT_ALIGNMENT);
Share:
11,011
Mercenary
Author by

Mercenary

Updated on June 04, 2022

Comments

  • Mercenary
    Mercenary about 2 years

    The label does not align to the left of the center layout. If the GridLayout is not present, then it moves correctly. Is there a way to do it to move JLabel to the extreme left?

    I've tried setHorizontalAlignment and setAlignmentX and both did not work

    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    
    public class asd {
        public static void main(String[] args){
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            JLabel lab = new JLabel("LABEL",SwingConstants.LEFT);
            //lab.setHorizontalAlignment(SwingConstants.CENTER);
            GridLayout grid = new GridLayout(3,3,2,1);
            JPanel yourGrid = new JPanel(grid);
            panel.add(lab);
            for(int i=0; i<3; i++){
                for(int j=0; j<3; j++){
                    JButton but = new JButton();
                    yourGrid.add(but);
                }
            }
            panel.add(yourGrid);
            frame.getContentPane().add(BorderLayout.CENTER,panel);
            frame.setVisible(true);
            frame.pack();
        }
    }
    
  • Masudul
    Masudul over 10 years
    yourGrid.setHorizontalAlignment(SwingConstants.LEFT); is illegal.
  • RamonBoza
    RamonBoza over 10 years
    solved, I dont have a compiler in front to test the code atm, ty! :D
  • Mercenary
    Mercenary over 10 years
    One more thing! What if there are two JLabels and I need to place one to the extreme left and the other to the extreme right. How should the JPanel be aligned?
  • RamonBoza
    RamonBoza over 10 years
    setLayout(new BoxLayout(panel,BoxLayout.LINE_AXIS); and then add(label1); add(Box.createHoritzonalGlue());add(label2);