java 设置 JPanel 布局
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11790830/
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
Setting JPanel layout
提问by Sumudu
(Say) I've created a JPanel with three buttons. I want to place the buttons as follows (I've done this using netbeans GUI editor. But I need to write the whole GUI manually).
(说)我创建了一个带有三个按钮的 JPanel。我想按如下方式放置按钮(我已经使用 netbeans GUI 编辑器完成了此操作。但我需要手动编写整个 GUI)。
Can some one show me a way to achieve this.
有人可以告诉我一种方法来实现这一目标。
(In words, I need to place some buttons right aligned, some other left aligned.)
(换句话说,我需要将一些按钮右对齐,其他一些左对齐。)
回答by aioobe
I guess you want the Configurebutton to be as far to the left as possible, and the okand cancelgrouped together to the right. If so, I would suggest using a BorderLayout
and place the Configurebutton in WEST, and a flow-layout for Ok, Canceland place that panel in the EAST.
我猜您希望“配置”按钮尽可能靠左,而“确定”和“取消”组合在右侧。如果是这样,我建议使用 aBorderLayout
并将配置按钮放置在 WEST 中,并使用流布局Ok,Cancel并将该面板放置在 EAST 中。
Another option would be to use GridBagLayout
and make use of the GridBagConstrant.anchor
attribute.
另一种选择是使用GridBagLayout
和利用该GridBagConstrant.anchor
属性。
Since you're taking the time to avoid the NetBeans GUI editor, here's a nice example for you :-)
由于您正在花时间避免使用 NetBeans GUI 编辑器,因此这里有一个很好的示例:-)
Code below:
代码如下:
import java.awt.BorderLayout;
import javax.swing.*;
public class FrameTestBase {
public static void main(String args[]) {
// Will be left-aligned.
JPanel configurePanel = new JPanel();
configurePanel.add(new JButton("Configure"));
// Will be right-aligned.
JPanel okCancelPanel = new JPanel();
okCancelPanel.add(new JButton("Ok"));
okCancelPanel.add(new JButton("Cancel"));
// The full panel.
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.add(configurePanel, BorderLayout.WEST);
buttonPanel.add(okCancelPanel, BorderLayout.EAST);
// Show it.
JFrame t = new JFrame("Button Layout Demo");
t.setContentPane(buttonPanel);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setSize(400, 65);
t.setVisible(true);
}
}