gd1*_*gd1 5 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);
Run Code Online (Sandbox Code Playgroud)
当我测试应用程序时,我发现所有内容都未对齐并搞砸了:按钮和标签是随机缩进的,如果我调整窗口大小,缩进量会以一种奇怪的方式变化.进度条看起来很好(全宽).
我只是不明白发生了什么.你能给我一个线索吗?
BoxLayout无法处理不同的对齐方式:请参阅http://download.oracle.com/javase/tutorial/uiswing/layout/box.html
引用该文章:"通常,由顶部到底部BoxLayout对象控制的所有组件应具有相同的X对齐.同样,由左到右Boxlayout控制的所有组件通常应具有相同的Y对齐".
有时您需要获得一点创意并使用嵌套面板.但是我更喜欢这种方法,然后尝试学习并记住使用其他布局管理器(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);
}
}
Run Code Online (Sandbox Code Playgroud)