如何在 GridBagLayout 中将 JLabel 与 JTextField 对齐

How to align JLabel next to a JTextField in a GridBagLayout

我的表单非常简单,我只想在文本字段旁边添加标签。标签默认居中,这使表单看起来很奇怪。我想要标签正好在文本字段旁边。我玩过标签和文本字段的水平对齐,但它没有改变任何东西。

这是我的代码:

JPanel root = new JPanel(new GridBagLayout());
                 GridBagConstraints gbc = new GridBagConstraints();
                 gbc.insets= new Insets(0,0,0,0);

                 newVehicleRecord.setLayout(new BorderLayout());
                 newVehicleRecord.add(root,BorderLayout.PAGE_START);


                 JLabel title = new JLabel("New Vehicle Record - Customer ID:" + customerIDInfo.getText());
                 title.setFont(fontTitle);
                 gbc.weightx = 0;
                 gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth= 2;

                 root.add(title,gbc);

                 gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth= 1;
                 root.add(Box.createVerticalStrut(15),gbc);


                 gbc.gridx = 0; gbc.gridy = 2;
                 JLabel classificationLabel = new JLabel("Classification:");
                 classificationLabel.setHorizontalAlignment(JLabel.RIGHT);
                 root.add(classificationLabel,gbc);

                 gbc.gridx = 1; gbc.gridy = 2;
                 JTextField classificationTextField = new JTextField(10);
                 classificationTextField.setHorizontalAlignment(JTextField.LEFT);
                 root.add(classificationTextField,gbc);

                 gbc.gridx = 0; gbc.gridy = 3;
                  JLabel modelLabel = new JLabel("Model:");
                 root.add(modelLabel,gbc);

                 gbc.gridx = 1; gbc.gridy = 3;
                 JTextField modelTextField = new JTextField(10);
                 root.add(modelTextField,gbc);

                 gbc.gridx = 0; gbc.gridy = 4;
                  JLabel makeLabel = new JLabel("Make:");
                 root.add(makeLabel,gbc);

                 gbc.gridx = 1; gbc.gridy = 4;
                 JTextField makeTextField = new JTextField(10);
                 root.add(makeTextField,gbc);

我得到以下显示:http://prntscr.com/6j3iki

如您所见,标签和文本字段之间有很多我不想要的空白 space。

I want to the labels exactly next to the textfield.

您需要使用 anchor 约束:

gbc.anchor = GridBagConstraints.LINE_END;
panel.add(label, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(textField, gbc);

另外你可能想要这样的东西:

gbc.insets = new Insets(5, 10, 5, 10);

所以标签的右边缘与文本字段的左边缘之间有一些 space。

阅读有关 How to Use GridBagLayout 的 Swing 教程部分,了解有关所有约束的更多信息。

像这样:

             gbc.gridx = 0; gbc.gridy = 3;
             gbc.anchor = GridBagConstraints.EAST;
             JLabel modelLabel = new JLabel("Model:");
             root.add(modelLabel,gbc);

所以你需要添加行

gbc.anchor = GridBagConstraints.EAST;

给你的每个标签。

另一种可能性:

             gbc.gridx = 0; gbc.gridy = 3;
             gbc.fill = GridBagConstraints.HORIZONTAL;
             JLabel modelLabel = new JLabel("Model:");
             modelLabel.setHorizontalAlignment(SwingConstants.RIGHT);
             root.add(modelLabel,gbc);