如何在BoxLayout

时间:2017-03-17 02:43:55

标签: java swing jlabel boxlayout

我是Java编程的新手,我有一个关于BoxLayout的问题。我无法将JLabel置于具有BoxLayout的面板中心

我想要的是改变现在的状态:

https://i.stack.imgur.com/12aB7.png

到此:

https://i.stack.imgur.com/IC68C.png

让标签完全位于面板中间。

这是我的代码:

import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test extends JFrame{

    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JLabel label4;
    private JLabel label5;

    public Test(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initWidgets();
        setVisible(true);
    }

    private void initWidgets(){
        setPreferredSize(new Dimension(300, 300));

        label1 = new JLabel("Label 1");
        label2 = new JLabel("Label 2");
        label3 = new JLabel("Label 3");
        label4 = new JLabel("Label 4");
        label5 = new JLabel("Label 5");

        JPanel jpanel = new JPanel();

        label1.setAlignmentX(CENTER_ALIGNMENT);
        label2.setAlignmentX(CENTER_ALIGNMENT);
        label3.setAlignmentX(CENTER_ALIGNMENT);
        label4.setAlignmentX(CENTER_ALIGNMENT);
        label5.setAlignmentX(CENTER_ALIGNMENT);

        jpanel.setLayout(new BoxLayout(jpanel, BoxLayout.PAGE_AXIS));

        jpanel.add(label1);
        jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
        jpanel.add(label2);
        jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
        jpanel.add(label3);
        jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
        jpanel.add(label4);
        jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
        jpanel.add(label5);

        add(jpanel);
        pack();
    }

    public static void main(String[] args) {
        new Test();
    }
}

2 个答案:

答案 0 :(得分:2)

要使组件垂直居中,您需要在开头和结尾添加“胶水”:

jpanel.add(Box.createVerticalGlue());
jpanel.add(label1);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label2);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label3);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label4);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label5);
jpanel.add(Box.createVerticalGlue());

阅读How to Use BoxLayout上的Swing教程中的部分以获取更多信息。

答案 1 :(得分:0)

尝试在setAlignmentX

之后添加此内容
label1.setHorizontalAlignment(SwingConstants.CENTER);
label2.setHorizontalAlignment(SwingConstants.CENTER);
label3.setHorizontalAlignment(SwingConstants.CENTER);
label4.setHorizontalAlignment(SwingConstants.CENTER);
label5.setHorizontalAlignment(SwingConstants.CENTER);

然后在面板上添加标签,如下所示:

jpanel.add(label1, BorderLayout.CENTER);
jpanel.add(label2, BorderLayout.CENTER);
jpanel.add(label3, BorderLayout.CENTER);
jpanel.add(label4, BorderLayout.CENTER);
jpanel.add(label5, BorderLayout.CENTER);