Java 如何在 JPanel 中将所有元素向左对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2714663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:01:11  来源:igfitidea点击:

How can I align all elements to the left in JPanel?

javaalignmentjpanel

提问by Roman

I would like to have all elements in my JPanel to be aligned to the left. I try to do it in the following way:

我想让我的 JPanel 中的所有元素都向左对齐。我尝试通过以下方式做到这一点:

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);

As a result Java use left side of all elements as a position of the element and then put all elements in the center (not left part) of the JPanel.

因此,Java 使用所有元素的左侧作为元素的位置,然后将所有元素放在 JPanel 的中心(不是左侧部分)。

回答by Hyman

You should use setAlignmentX(..)on components you want to align, not on the container that has them..

您应该setAlignmentX(..)在要对齐的组件上使用,而不是在包含它们的容器上使用。

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);

c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);

回答by Chris

The easiest way I've found to place objects on the left is using FlowLayout.

我发现将对象放在左侧的最简单方法是使用 FlowLayout。

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

将组件正常添加到此面板会将其放置在左侧

回答by Chris

My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.

我最喜欢使用的方法是 BorderLayout 方法。以下是组件可以进入的每个位置的五个示例。该示例用于如果组件是按钮。我们将把它添加到一个 JPanel,p。该按钮将被称为 b。

//To align it to the left
p.add(b, BorderLayout.WEST);

//To align it to the right
p.add(b, BorderLayout.EAST);

//To align it at the top
p.add(b, BorderLayout.NORTH);

//To align it to the bottom
p.add(b, BorderLayout.SOUTH);

//To align it to the center
p.add(b, BorderLayout.CENTER);

Don't forget to import it as well by typing:

不要忘记通过键入以下内容导入它:

import java.awt.BorderLayout;

There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!

BorderLayout 类中还有其他方法涉及方向等内容,但如果您对此感到好奇,可以自行研究。我希望这有帮助!