带/不带布局管理器的swing Java定位GUI组件
我试图定位一些组件,使其与左侧对齐
public class MyGUI extends JPanel
{
public MyGUI()
{
FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
setLayout(layout);
JLabel label_1 = new JLabel("label1");
JTextField textArea = new JTextField(15);
JButton button_1 = new JButton("button 1");
button_1.addActionListener(new EventHandler());
JLabel label_2 = new JLabel();
JButton button_2 = new JButton("button 2");
button_2.addActionListener(new EventHandler());
JLabel label_3 = new JLabel();
JButton button_3 = new JButton("button 3");
button_3.addActionListener(new EventHandler());
JLabel label_4 = new JLabel();
add(label_1);
add(textArea);
add(button_1);
add(label_2);
add(button_2);
add(label_3);
add(button_3);
add(label_4);
}
但这就是我所得到的:
我需要按钮定位在左边,标签(不可见)定位在右边。哪种布局管理器最适合于此,如何使用x/y坐标手动定位任何组件
# 1 楼答案
我认为你需要把你的框架宽度调大,以便在一条直线上安装所有的组件,因为FLowLayout默认情况下会对齐组件,除非没有更多的空间,它会跳转到下一条直线。或者你可以使用gridLayout一列多列,或者GridBagLayout,但是使用起来很痛苦
# 2 楼答案
可以通过使用空布局和设置边界(x,y)手动定位它们:
我想让你参考一下甲骨文的这本指南。关于布局管理器。Gridbag布局是最强大但最难学的布局之一
# 3 楼答案
你试过SpringLayout(http://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html)吗?使用SpringLayout,可以将组件的边附着到其他组件的边上。例如,此语句将
textArea
的西边缘附加到包含面板的西边缘,偏移量为5像素:也可以将同一构件的北边附着到包含该构件的配电盘:
可以将这些约束添加到所有组件中。这有点乏味,但是你可以控制组件的放置位置。这是一张照片:
下面是显示如何使用SpringLayout的代码示例:
# 4 楼答案
对于“哪个布局管理器最适合此任务”的问题,答案是主观的。任何有能力的布局管理器都可以轻松地进行布局—
GridBagLayout
、GroupLayout
、BoxLayout
(通过嵌套)或MigLayout
MigLayout
是迄今为止最有能力的布局管理器