Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I align all elements to the left in JPanel?

I would like to have all elements in my JPanel to be aligned to the left. I try to do it in the following way:

JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setAlignmentX(Component.LEFT_ALIGNMENT); 

As a result Java use left side of all elements as a position of the element and then put all elements in the center (not left part) of the JPanel.

like image 210
Roman Avatar asked Apr 26 '10 15:04

Roman


People also ask

How do I change the layout of a JPanel?

You can set a panel's layout manager using the JPanel constructor. For example: JPanel panel = new JPanel(new BorderLayout()); After a container has been created, you can set its layout manager using the setLayout method.

How do you center align in box layout?

The problem can be solved by using myLabel. setAlignmentX(Component. CENTER_ALIGNMENT); . It works with JLabel , JButton and JRadioButton .


2 Answers

You should use setAlignmentX(..) on components you want to align, not on the container that has them..

JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(c1); panel.add(c2);  c1.setAlignmentX(Component.LEFT_ALIGNMENT); c2.setAlignmentX(Component.LEFT_ALIGNMENT); 
like image 29
Jack Avatar answered Sep 20 '22 11:09

Jack


The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); 

adding a component normally to this panel will place it on the left

like image 96
Chris Avatar answered Sep 20 '22 11:09

Chris