Josh Sobel
Josh Sobel

Reputation: 1318

Box laying out components strangely

I am writing a gui for a game I am making in java, and I have this code:

private JLabel label = new JLabel("Enter New Level Name");
private JTextField field = new JTextField();
private static JButton createWorld = new JButton("Create World");
private JButton menu = new JButton("Main Menu");

public StartGame()
{
    setBackground(Color.CYAN);
    Box box = Box.createVerticalBox();
    box.add(label);
    box.add(Box.createRigidArea(new Dimension(0,10)));
    box.add(field);
    box.add(Box.createRigidArea(new Dimension(0,10)));
    Box hor = Box.createHorizontalBox();
    hor.add(createWorld);
    hor.add(Box.createRigidArea(new Dimension(10,0)));
    hor.add(menu);
    box.add(hor);
    add(box);
}

What I want this panel to look like is all the components in a box aligned to the right. How ever when I run this everything works except the label doesn't match up with the rest of the layout. Could anyone explain what I am doing wrong, and or possible ways to fix it.

Heres my problem, I know its blurry but you can make out that the label is offset to the right. Heres my problem

Upvotes: 1

Views: 60

Answers (1)

user0
user0

Reputation: 163

You should set the x alignment of each component. From the java tutorial: "In general, all the components controlled by a top-to-bottom BoxLayout object should have the same X alignment.".

So you should add this line:

label.setAlignmentX(Component.CENTER_ALIGNMENT);

Upvotes: 2

Related Questions