简体   繁体   English

如何在屏幕的两侧制作两个 JLabel?

[英]How do I make two JLabels on opposite sides of the screen?

I'm trying to make something that looks like this:我正在尝试制作看起来像这样的东西: 在此处输入图像描述

As you can see, I want the labels on opposite sides of each other on the same line in the same parent container.如您所见,我希望在同一父容器中的同一行上彼此相对的标签。

I tried using the GridBagLayout , and here is my code:我尝试使用GridBagLayout ,这是我的代码:

JPanel cont = new JPanel();

JLabel left = new JLabel("left");
JLabel right = new JLabel("right");

GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
cont.add(left, gbc);

gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.EAST;
cont.add(right, gbc);

You can use GridBagLayout, but I find using the constraints painful and sometimes unpredictable.您可以使用 GridBagLayout,但我发现使用约束很痛苦,而且有时无法预测。 This is easier with GridLayout and specifying the justification of the JLabel.使用 GridLayout 并指定 JLabel 的对齐更容易。

Here's an example that puts two JLabels in a row as in your drawing:这是一个将两个 JLabel 排成一行的示例,如您的绘图所示:

JPanel labelrow = new JPanel(new GridLayout(1,2));
JLabel left = new JLabel("left side", JLabel.LEFT);
JLabel right = new JLabel("right side", JLabel.RIGHT);

You can do the same with other controls, like buttons, if you put them inside JPanels with FlowLayouts that are left and right-justified.如果将按钮等其他控件放在具有左右对齐的 FlowLayouts 的 JPanel 中,则可以对它们执行相同的操作。

Here's an example showing it with buttons off to each side:这是一个示例,显示它的每一侧都有按钮:

JPanel buttons = new JPanel(new GridLayout(1,2));
JPanel left = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT));
left.add(new JButton("Left"));
right.add(new JButton("Right"));
buttons.add(left);
buttons.add(right);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM