请帮我理解BoxLayout对齐问题

时间:2011-04-18 12:27:19

标签: java swing alignment boxlayout

我正在尝试使用Java Layouts创建一个非常简单的窗口。我有三个元素可以安排:按钮,进度条和标签。按钮必须垂直居中,进度条必须采用全宽,标签必须左对齐。

这是一些代码(只是假设窗格是JFrame的内容窗格,并且之前已经创建了按钮,progressBar和标签):

BoxLayout layout = new BoxLayout(pane, BoxLayout.Y_AXIS);
pane.setLayout(layout);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
pane.add(button);
progressBar.setAlignmentX(Component.CENTER_ALIGNMENT);
pane.add(progressBar);
label.setAlignmentX(Component.LEFT_ALIGNMENT);
pane.add(label);

当我测试应用程序时,我看到所有内容都未对齐并搞砸了:按钮和标签是随机缩进的,如果我调整窗口大小,缩进量会以一种奇怪的方式变化。 进度条看起来很好(全宽)。

我只是不明白发生了什么。你能给我一个线索吗?

5 个答案:

答案 0 :(得分:7)

BoxLayout无法处理不同的路线:请参阅http://download.oracle.com/javase/tutorial/uiswing/layout/box.html

引用该文章:“一般来说,由顶部到底部BoxLayout对象控制的所有组件应该具有相同的X对齐。同样,由左到右Boxlayout控制的所有组件通常应该具有相同的Y对齐。“

答案 1 :(得分:5)

有时您需要获得一点创意并使用嵌套面板。但是我更喜欢这种方法,然后尝试学习和记忆使用其他布局管理器(GridBagLayout,GroupLayout)时所需的所有约束,其中IDE设计用于为您生成代码。

import java.awt.*;
import javax.swing.*;

public class BoxLayoutVertical extends JFrame
{
    public BoxLayoutVertical()
    {
        Box box = Box.createVerticalBox();

        JButton button = new JButton("A button");
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        box.add(button);

        JProgressBar progressBar = new JProgressBar(0, 100);
        progressBar.setAlignmentX(Component.CENTER_ALIGNMENT);
        box.add(progressBar);

        JPanel panel = new JPanel( new BorderLayout() );
        JLabel label = new JLabel("A label");
        label.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(label);
        box.add(panel);

        add(box, BorderLayout.NORTH);
    }

    public static void main(String[] args)
    {
        BoxLayoutVertical frame = new BoxLayoutVertical();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setSize(300, 200);
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

答案 2 :(得分:2)

为了补充我对原始问题的评论,以下是使用DesignGridLayout的代码段:

JButton button = new JButton("Button");
JProgressBar progressBar = new JProgressBar();
JLabel label = new JLabel("Label");

// The interesting stuff is in the next 4 lines
DesignGridLayout layout = new DesignGridLayout(getContentPane());
layout.row().center().add(button).withOwnRowWidth();
layout.row().center().fill().add(progressBar);
layout.row().left().add(label);

pack();

它完全符合您在问题中所描述的内容,并且不需要对任何组件进行任何特定调用。

答案 3 :(得分:1)

也许您的代码只是一个代码段,但我错过了对pack()的调用。

手动编码摆动布局对标准布局管理器来说非常令人沮丧。我为此目的使用MiG Layout。它是直截了当的,只需几行代码就可以获得很好的布局。如果您没有被迫使用BoxLayout,我建议您试一试。

答案 4 :(得分:1)

相关问题