Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing BoxLayout ignoring AlignmentX

In the code below, by calling setAlignmentX with Component.LEFT_ALIGNMENT I expected to get a left aligned label over a centered slider. For some reason the label is also centered, seemingly regardless of what value is passed to setAlignmentX.

What value must I pass to setAlignmentX to get it left aligned?

package myjava;

import java.awt.Component;
import java.awt.Container;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;

public class LayoutTest {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("BoxLayoutDemo");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                // create left aligned label over centered column
                Container contentPane = frame.getContentPane();
                contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
                JLabel label = new JLabel("test");
                label.setAlignmentX(Component.LEFT_ALIGNMENT);
                contentPane.add(label);
                contentPane.add(new JSlider());

                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
like image 494
Mizipzor Avatar asked Feb 10 '12 13:02

Mizipzor


1 Answers

Basically, you can't have different alignments in BoxLayout, from How To Use BoxLayout

In general, all the components controlled by a top-to-bottom BoxLayout object should have the same X alignment.

Edit

Typically, it's not documented which default alignment a component type has (JSlider is centered by default, me incorrectly thought that a JLabel were centered while it is left-aligned ;-) One option is to keep a list somewhere (dooooh...), another is to simply force them all to the same alignment on adding.

Or use a third-party layoutManager, which doesn't have this rather unintuitve (for me) mix-in of layout and alignment.

like image 132
kleopatra Avatar answered Sep 22 '22 12:09

kleopatra