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);
Author by
Mercenary
Updated on June 04, 2022Comments
-
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 over 10 yearsyourGrid.setHorizontalAlignment(SwingConstants.LEFT); is illegal.
-
RamonBoza over 10 yearssolved, I dont have a compiler in front to test the code atm, ty! :D
-
Mercenary over 10 yearsOne more thing! What if there are two
JLabel
s and I need to place one to the extreme left and the other to the extreme right. How should theJPanel
be aligned? -
RamonBoza over 10 years
setLayout(new BoxLayout(panel,BoxLayout.LINE_AXIS);
and thenadd(label1); add(Box.createHoritzonalGlue());add(label2);