Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 奇怪地布置部件的盒子_Java_Swing_Jpanel_Jlabel_Boxlayout - Fatal编程技术网

Java 奇怪地布置部件的盒子

Java 奇怪地布置部件的盒子,java,swing,jpanel,jlabel,boxlayout,Java,Swing,Jpanel,Jlabel,Boxlayout,我正在为用java制作的游戏编写gui,代码如下: 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"); publ

我正在为用java制作的游戏编写gui,代码如下:

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);
}
我希望这个面板看起来像是一个框中的所有组件都向右对齐。然而,当我运行这个程序时,除了标签与布局的其余部分不匹配外,其他一切都正常工作。有谁能解释一下我做错了什么,或者有什么可能的解决方法吗

这是我的问题,我知道它很模糊,但你可以看出标签向右偏移了。

您应该设置每个组件的x对齐方式。来自java:“通常,由一个自上而下的BoxLayout对象控制的所有组件都应该具有相同的X对齐方式。”

因此,您应该添加这一行:

label.setAlignmentX(Component.CENTER_ALIGNMENT);

您能更详细地解释一下“标签与布局的其余部分不匹配”的原因吗?它被移到了所有其他组件的右边,并且它没有对齐。请看图片