JLabel定位到JPanel

时间:2014-02-27 17:41:12

标签: java swing jpanel jlabel layout-manager

我已编写此代码以建立数据库连接并添加客户端:

//adding the left panel
JPanel left = new JPanel();
left.setPreferredSize(new Dimension(250, 500));
left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
add(left);

//adding the right panel
JPanel right = new JPanel();
right.setPreferredSize(new Dimension(250, 500));
right.setLayout(new BoxLayout(right, BoxLayout.Y_AXIS));
add(right);

//adding the jlabel title to the left panel
JLabel leftTitle = new JLabel("Add a client");
leftTitle.setAlignmentX(CENTER_ALIGNMENT);
left.add(leftTitle);

//adding the jlabel title to the right panel
JLabel rightTitle = new JLabel("Make a reservation");
rightTitle.setAlignmentX(CENTER_ALIGNMENT);
right.add(rightTitle);

//adding the jlabel "name"
JLabel nameL = new JLabel("Name:");
left.add(nameL);

我想在这里移动这个JLabel: move that "Name:" into the left

我已经尝试过nameL.setAlignmentX(LEFT_ALIGNMENT);,但它仍无效

1 个答案:

答案 0 :(得分:2)

您的问题是您使用了BoxLayout

left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
                   ^^^^^^^^^

您的BoxLayout设置为沿y轴居中对齐,因此不会改变设置对齐量。要解决您的问题,您需要使用其他布局管理器,例如GroupLayoutCardLayout