gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:30:26 27 4
gpt4 key购买 nike

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

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

enter image description here

代码:

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

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

关于java - GridBagLayout - 将多个组件放置在长文本字段下方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49328855/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com