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.
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.
The problem can be solved by using myLabel. setAlignmentX(Component. CENTER_ALIGNMENT); . It works with JLabel , JButton and JRadioButton .
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With