如何在 JPanel 中将所有元素向左对齐?
我希望 JPanel 中的所有元素都向左对齐。我尝试按以下方式执行此操作:
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
结果 Java 使用所有元素的左侧作为元素的位置,然后将所有元素放在 JPanel 的中心(而不是左侧部分)。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现将对象放置在左侧的最简单方法是使用 FlowLayout。
通常向该面板添加组件会将其放置在左侧
The easiest way I've found to place objects on the left is using FlowLayout.
adding a component normally to this panel will place it on the left
您应该在要对齐的组件上使用 setAlignmentX(..) ,而不是在包含它们的容器上使用。
You should use
setAlignmentX(..)
on components you want to align, not on the container that has them..我最喜欢使用的方法是 BorderLayout 方法。以下是组件可能进入的每个位置的五个示例。该示例针对的是组件是按钮的情况。我们将把它添加到 JPanel,第 17 页。该按钮将被称为 b。
不要忘记通过键入以下内容来导入它:
BorderLayout 类中还有其他方法涉及方向等内容,但如果您对此感到好奇,可以对此进行自己的研究。我希望这有帮助!
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.
Don't forget to import it as well by typing:
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!