GridBagLayout - 将多个组件放置在长文本字段下方

GridBagLayout - Placing multiple components below a long text field

我正在使用 GridBagLayout 测试一个简单的表单,但遇到了一些对齐问题。我想在顶部 "Item" 行下方的行中放置两个小字段,但长文本字段导致其下方的小文本字段无法正确对齐。

这是它目前正在做的事情的图片,我只需要将第二行的小框放在第一个价格字段旁边。

代码:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.*;
public class GridBagLayoutTest {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panelMain = new JPanel();
    JPanel panelForm = new JPanel(new GridBagLayout());

    JLabel lblItem = new JLabel("Item: ");
    JLabel lblPrice = new JLabel("Price: ");
    JLabel lblQuantity = new JLabel("Quantity: ");

    JTextField txtItem = new JTextField(15);
    JTextField txtPricePounds = new JTextField(3);
    JTextField txtPricePence = new JTextField(2);
    JTextField txtQuantity = new JTextField(3);

    GridBagConstraints gbc = new GridBagConstraints();

    gbc.anchor = GridBagConstraints.LINE_END;
    gbc.gridx = 0;
    gbc.gridy = 0;
    panelForm.add(lblItem, gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    panelForm.add(lblPrice, gbc);

    gbc.gridx = 0;
    gbc.gridy = 2;
    panelForm.add(lblQuantity, gbc);

    gbc.anchor = GridBagConstraints.LINE_START;
    gbc.gridx = 1;
    gbc.gridy = 0;
    panelForm.add(txtItem, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    panelForm.add(txtPricePounds, gbc);


    gbc.gridx = 2;
    gbc.gridy = 1;
    panelForm.add(txtPricePence, gbc);

    gbc.gridx = 1;
    gbc.gridy = 2;
    panelForm.add(txtQuantity, gbc);


    panelMain.add(panelForm);

    frame.add(panelMain);
    frame.setSize(400, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

}

记住,GridBagLayout仍然是一个基于网格的布局管理系统。它也非常灵活。它提供的功能之一是能够配置组件可能跨越的列数或行数。

因此,如果我们可以修改您的代码并添加 gridwidth 以允许 txtItem 跨越 2 列,其余字段跨越 1;

gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 2;
add(txtItem, gbc);

gbc.gridwidth = 1;
gbc.gridx = 1;
gbc.gridy = 1;
add(txtPricePounds, gbc);

你最终会得到类似...

查看 How to use GridBagLayout 了解更多详情