views:

416

answers:

2

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.

A: 

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);
Jack
I do not think so. `setAlignementX(Component.LEFT_ALIGNEMENT)` means that left side of the component will be used to align elements. And elements will still be aligned to the center of JPanel.
Roman
Are you sure? Take a look here http://www.java2s.com/Code/Java/Swing-JFC/ComponentAlignment.htm the method setAlignmentX is used on buttons added to the panel, not on the panel itself
Jack
Jack, you are right that this method is used on buttons but it does not have the effect you described. It does not define the position of the button. It defines the part of the button which will be used for the alignment. For example "LEFT" side of the button will be used to put button in the center (left side of the button will be put into the center).
Roman
A: 

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

Chris