将 JLabel 放置在面板的中央,将 JLabel 放置在同一面板的右侧

Positioning a JLabel in the center of a panel and a JLabel to the right of the same panel

我有一个 JPanel,里面有两个 JLabel 组件:headerLabeltimeLabel

问题是我无法让 headerLabel 坐在面板的中央,而 timeLabel 坐在最右边。我尝试了几种不同的布局管理器(GridBagLayoutBorderLayout 等)和技术(Box.createHorizontalStrut(X)、添加 Insets),但它们最终都会推动 headerLabel到最左边,timeLabel 到最右边,或者将它们都放在中间。

下面是我希望它看起来如何的图形表示:

是否应该使用特定的布局管理器来获得此结果?

您应该可以使用 GridBagLayout 实现。

headerPanel 将位于 0,0,FILL_BOTH,居中且 fillx = 1.0

timePanel 将位于 0,1 并且没有进一步的填充选项。

现在,这些内容的显示很大程度上取决于您渲染的原始面板的大小。如果它位于 JDialog 或任何其他 pack()ed 的容器内,它们仍然会显示 "side by side",因为这是布局这些元素的最佳方式。

如果这仍然困扰您,您可以为 headerPanel 分配最小和首选大小,这样打包就不会将其缩小到该大小以下。

    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{0, 0, 0};
    gridBagLayout.rowHeights = new int[]{0, 0};
    gridBagLayout.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
    gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
    setLayout(gridBagLayout);

    JLabel lblHeader = new JLabel("HEADER");
    GridBagConstraints gbc_lblHeader = new GridBagConstraints();
    gbc_lblHeader.weightx = 1.0;
    gbc_lblHeader.insets = new Insets(0, 0, 0, 5);
    gbc_lblHeader.gridx = 0;
    gbc_lblHeader.gridy = 0;
    add(lblHeader, gbc_lblHeader);

    JLabel lblTime = new JLabel("TIME");
    GridBagConstraints gbc_lblTime = new GridBagConstraints();
    gbc_lblTime.gridx = 1;
    gbc_lblTime.gridy = 0;
    add(lblTime, gbc_lblTime);

I have tried several different Layout Managers (GridBagLayout, BorderLayout etc.)

嗯,post 你的代码。我们无法猜测您可能在做什么。

我会使用 BorderLayout.

将一个标签添加到 BorderLayout.CENTER,将另一个标签添加到 BorderLayouyt.LINE_END

setLayout( new BorderLayout() ):

JLabel center = new JLabel("CENTER");
center.setHorizontalAlignment(JLabel.CENTER); // maybe you are missing this
add(center, BorderLayout.CENTER);

JLabel right = new JLabel("RIGHT");
add(right, BorderLayout.LINE_END);

它告诉文本当有多余的水平线时如何自行对齐 space。