繁体   English   中英

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

[英]GridBagLayout - Placing multiple components below a long text field

我正在使用GridBagLayout测试一个简单的表单,并且遇到一些对齐问题。 我想在顶部“项目”行下方的行上放置两个小字段,但是长文本字段导致其下方的小文本字段无法正确对齐。

这是当前操作的图像,我只需要第二行的小框放在第一个价格字段旁边。

在此处输入图片说明

码:

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);

你最终会得到类似...

GridBagLayout的

看看如何使用GridBagLayout了解更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM