如何动态添加连续组件到JPanel中,而不需要额外的垂直空间。

问题描述 投票:0回答:1

嘿,我是新手,所以有什么不对的地方请见谅。

我试图使用GridBagLayout来添加组件到JPanel,我已经设置了两个组件,即 weightxweighty 为1,并将 anchor北部第一个组件顺从地锚定在面板的顶部,但下一个组件锚定的间隙与面板的剩余高度成正比,所以看起来面板被分成了与组件数量相等的部分。

这就是我添加第一个组件时的情况。

enter image description here

这是我添加第二个组件时的情况。

enter image description here

以此类推

enter image description here

粉色是Jpanel,青色是组件。

该组件是另一个Jpanel,它可以容纳4个Jtextfeilds来组成一行。

import javax.swing.*;
import java.awt.*;

public class Table extends JPanel{
/*
Main table class that holds TableRow class as rows

couples with the controller class to update the rows
 */
private final GridBagLayout LAYOUT = new GridBagLayout();
private GridBagConstraints constraints;
private ActionPerformed actionListener;



public Table(){

    setLayout(LAYOUT);
    constraintParams();


}

private void constraintParams() {
    constraints = new GridBagConstraints();
    constraints.gridy = 0;
    constraints.gridx = 0;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.anchor = GridBagConstraints.NORTH;
    setBackground(Color.PINK);
}

public void updateRow(String data){
    /*
    accepts Array of String data and passes it to corresponding row to update fields
     */

    System.out.println(getComponentCount());
    boolean updated = false;
    try {
        Component[] components = getComponents();
        for (Component component : components) {
            TableRow previousRow = (TableRow) component;
            if (previousRow.getProductName().equals(data.split("!!!")[0])) {
  //                    previousRow.incrementQuantiy();
  //                    updated = true;
  //                    break;
            }
        }
        if (!updated) throw new IndexOutOfBoundsException();

    }catch(IndexOutOfBoundsException e) {
        constraints.gridy = getComponentCount();
        add(new TableRow(),constraints);
        TableRow row = (TableRow) getComponent(getComponentCount() - 1);
        row.updateRow(data);

    }
    Component[] components = getComponents();
    for (Component component : components) {
        TableRow row = (TableRow) component;
        row.setListener(actionListener);
    }

}

这是处理添加组件的代码。

java swing layout-manager
1个回答
1
投票
constraints.weighty = 1;

"weighty "约束告诉每个组件成长以填充额外的空间。

由于每个组件都有相同的 "weighty "值,所以每个组件将获得相同的额外空间。

我建议你去掉这个约束。

请阅读Swing教程中关于 如何使用GridBagLayout 关于约束条件的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.