【问题标题】:Swing: can't center a vbox inside a JPanel [duplicate]Swing:无法在 JPanel 中居中 vbox [重复]
【发布时间】:2020-07-31 02:21:23
【问题描述】:

我有这段代码可以创建一个简单的带有文本的 JPanel

User profile panel
username: a user
email: email@gmail.com
Button1 Button2

每一行 - 是一个HorizontalBox,所有行都进入一个VerticalBox。我尝试将结果居中VerticalBox,但它不起作用。

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

public class TestProfile extends JPanel  {
    {
        setup();
    }
    public void setup() {
        Box vBoxUserData = Box.createVerticalBox();

        Box hBoxUsername = Box.createHorizontalBox();
        hBoxUsername.add(new JLabel("username: "));
        hBoxUsername.add(new JLabel("a user"));
        vBoxUserData.add(hBoxUsername);

        Box hBoxEmail = Box.createHorizontalBox();
        hBoxEmail.add(new JLabel("email: "));
        hBoxEmail.add(new JLabel("email@gmail.com"));
        vBoxUserData.add(hBoxEmail);

        Box hBoxButtons = Box.createHorizontalBox();
        hBoxButtons.add(new JButton("Button1"));
        hBoxButtons.add(new JButton("Button2"));

        Box vBoxContent = Box.createVerticalBox();
        vBoxContent.add(new JLabel("User profile panel"));
        vBoxContent.add(hBoxUsername);
        vBoxContent.add(hBoxEmail);
        vBoxContent.add(hBoxButtons);

        vBoxContent.setAlignmentX(CENTER_ALIGNMENT);
        vBoxContent.setAlignmentY(CENTER_ALIGNMENT);
        hBoxUsername.setBackground(Color.RED);

        add(vBoxContent);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new TestProfile());
        frame.setVisible(true);
        frame.setDefaultCloseOperation(
                WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
    }

}

看起来像这样:

虽然我需要它看起来像这样:

我也很困惑为什么

        hBoxUsername.setBackground(Color.RED);

没有把它涂成红色?

【问题讨论】:

  • (1-) 昨天您的问题得到了答案。所有组件都需要相同的alignmentX。您还获得了一个如何进行垂直间距的示例。

标签: java swing boxlayout vbox hbox


【解决方案1】:

Box 布局只是在其自然方向上堆叠其子级。如果您想在这些孩子之前拉伸空间,请将glue 添加到您想要居中的孩子之前和之后的框中:

Box vBoxContent = Box.createVerticalBox();
vBoxContent.add(new JLabel("User profile panel"));
vBoxContent.add(Box.createVerticalGlue());
vBoxContent.add(hBoxUsername);
vBoxContent.add(hBoxEmail);
vBoxContent.add(hBoxButtons);
vBoxContent.add(Box.createVerticalGlue());

但仅此还不够。您的 TestProfile 类扩展 JPanel 但从不设置布局。默认布局是 FlowLayout,它不会尝试让其子元素填充其空间,因此您将永远看不到添加胶水组件的效果。

这可以通过使用强制(唯一)子组件填充 JPanel 的整个空间的布局来解决,例如BorderLayout

setLayout(new BorderLayout());
add(vBoxContent);

最后,JLabel 是透明的,除了它们的内容。如果你想用颜色填充 JLabel,make it opaque:

hBoxUsername.setBackground(Color.RED);
hBoxUsername.setOpaque(true);

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多