views:

121

answers:

1

I have a stumper which doesn't seem to make sense.

If I run the program below, I get two dialog boxes each containing JPanels.

alt text alt text

The first one has a couple of JLabels that are left-aligned. The second one extends the first and adds another JPanel as a subpanel, but the group of labels is right-aligned (even though within the group they are left aligned). What gives, and how do I fix it so that everything is left-aligned? (Or how would I right-align them all?)

package com.example.test.gui;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class BoxLayoutQuestion {
    public static class TestPanel1 extends JPanel
    {
        public TestPanel1()
        {
            super();
            initTestPanel1();
        }
        void initTestPanel1()
        {
            setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
            add(new JLabel("Four score and seven years ago"));
            add(new JLabel("One small step for man"));
            add(new JLabel("To be or not to be, that is the question"));
        }
    }
    public static class TestPanel2 extends TestPanel1
    {
        public TestPanel2()
        {
            super();
            initTestPanel2();
        }
        void initTestPanel2()
        {
            JPanel subpanel = new JPanel();
            subpanel.setBorder(
                    BorderFactory.createTitledBorder("something special"));
            subpanel.add(new JLabel("Where's the beef?"));
            add(subpanel);
        }
    }
    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, new TestPanel1(), 
                "quotations", JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, new TestPanel2(), 
                "more quotations", JOptionPane.INFORMATION_MESSAGE);
    }   
}
+1  A: 

I've found box layout to be very sensitive to the alignment of the components it contains. You probably need to set the component alignmentX for the components you are adding to the dialog.

If you call setAlignmentX(LEFT_ALIGNMENT) on each component before you add them you should get consistent left aligned behaviour.

Aaron
thanks, that does the trick! (+ also lets me right-align if I like)
Jason S
(FWIW, it looks like you can add them first and do setAlignmentX() afterwards, and that works too. I created an addAligned() method so I could use it multiple times.)
Jason S