【问题标题】:How to dynamically add consecutive components to JPanel with no extra vertical space如何在没有额外垂直空间的情况下将连续组件动态添加到 JPanel
【发布时间】:2020-05-13 10:34:28
【问题描述】:

嘿,我是新手,所以请见谅。

我正在尝试使用GridBagLayout向JPanel添加组件,我将weightxweighty都设置为1并将anchor设置为NORTH,第一个组件乖乖地锚定在顶部面板,但下一个组件锚定的间隙与面板的剩余高度成比例,因此看起来面板被分成等于组件数量的部分。

当我添加第一个组件时会发生这种情况:

这是我添加第二个组件时发生的情况:

以此类推:

粉色是Jpanel,青色是组件

该组件是另一个 Jpanel,它包含 4 个 Jtextfeild 组成一行。

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

}

这是处理添加组件的代码

【问题讨论】:

  • 只是use a JTable?
  • 谢谢,我将使用 Jtable,但我这样做是为了增加挑战,但我仍然不清楚为什么它们会以现在的方式呈现

标签: java swing layout-manager


【解决方案1】:
constraints.weighty = 1;

“权重”约束告诉每个组件增长以填充额外的空间。

由于每个组件具有相同的“权重”值,因此每个组件将获得相同的额外空间。

我建议你摆脱这个限制。

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

【讨论】:

    猜你喜欢
    • 2014-08-15
    • 2017-09-14
    • 1970-01-01
    • 2011-07-23
    • 2019-10-01
    • 2021-04-02
    • 2014-11-16
    • 2013-10-05
    • 1970-01-01
    相关资源
    最近更新 更多