如何将一个元素与 JPanel 的右侧对齐,而另一个元素与左侧对齐?
How can I align one element to the right and another to the left side of my JPanel?
我创建了一个 JPanel
并在其中添加了两个 JButtons
。我将面板布局设置为 FlowLayout
。
我想要一个 JButton
在 JFrame
的左边,另一个 JButton
在右边。
我试过了,但它抛出了 IllegalArgumentException
:
JPanel mainPanel = new JPanel(new FlowLayout());
JButton login = new JButton("Login");
JButton register = new JButton("Register");
mainPanel.add(register, FlowLayout.RIGHT);
mainPanel.add(login, FlowLayout.LEFT);
我可以使用 FlowLayout
执行此操作吗?哪种布局可以使其发挥作用?
mainPanel.add(register, FlowLayout.RIGHT);
mainPanel.add(login, FlowLayout.LEFT);
那不是那些 FlowLayout 变量的使用方式。它们用作布局管理器的属性,而不是 add(...) 方法的约束。阅读 FlowLayout
API 了解更多信息。
I want one JButton to be on the left of the JFrame and the other JButton to be on the right. Can I do this using FlowLayout?
没有
Which layout would make it work?
您可以使用带有以下内容的面板:
BorderLayout
- 添加一个按钮到 BorderLayout.LINE_START
和一个按钮到 BorderLayout.LINE_END
BoxLayout
- 在两个按钮之间添加一个 Box.createHorizontalGlue()
。
阅读 Layout Managers 上的 Swing 教程部分,了解有关上述每个布局管理器的更多信息和示例。
我创建了一个 JPanel
并在其中添加了两个 JButtons
。我将面板布局设置为 FlowLayout
。
我想要一个 JButton
在 JFrame
的左边,另一个 JButton
在右边。
我试过了,但它抛出了 IllegalArgumentException
:
JPanel mainPanel = new JPanel(new FlowLayout());
JButton login = new JButton("Login");
JButton register = new JButton("Register");
mainPanel.add(register, FlowLayout.RIGHT);
mainPanel.add(login, FlowLayout.LEFT);
我可以使用 FlowLayout
执行此操作吗?哪种布局可以使其发挥作用?
mainPanel.add(register, FlowLayout.RIGHT);
mainPanel.add(login, FlowLayout.LEFT);
那不是那些 FlowLayout 变量的使用方式。它们用作布局管理器的属性,而不是 add(...) 方法的约束。阅读 FlowLayout
API 了解更多信息。
I want one JButton to be on the left of the JFrame and the other JButton to be on the right. Can I do this using FlowLayout?
没有
Which layout would make it work?
您可以使用带有以下内容的面板:
BorderLayout
- 添加一个按钮到BorderLayout.LINE_START
和一个按钮到BorderLayout.LINE_END
BoxLayout
- 在两个按钮之间添加一个Box.createHorizontalGlue()
。
阅读 Layout Managers 上的 Swing 教程部分,了解有关上述每个布局管理器的更多信息和示例。