如何根据 swing 中的 JPanel(table) 行数增加 JFrame 的大小

how to increase JFrame size according to number of JPanel(table) rows in swing

我有执行以下操作的 swing 应用程序:

public void init() {
    jFrame = new JFrame();
...
    jFrame.add(sortingDataInputComponent.asComponent()); 
...
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.pack();
    jFrame.setVisible(true);
    jFrame.toFront();
}

sortingDataInputComponent 是 JPanel 与

jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS));

里面还有一个JPanel

jPanel.setLayout(new GridLayout(0,numberOfColumns));

其中

private final int numberOfColumns = 3;

并且内部 jpanel 在按下按钮时增长:

    jPanel.add(rowElement.getLabel(), insertionIndex);      
    jPanel.add(rowElement.getField(), insertionIndex + 1);
    jPanel.add(rowElement.getDeleteButton(), insertionIndex + 2);

    rowElements.add(rowElement);

    jPanel.revalidate();
    jPanel.repaint();

但主要 windows 不随 JPanel 一起增长。 它具有相同的初始大小。如何让JFrame随着内部JPanel的增长而增长?

JList 实施 Scrollable interface in the component to which you add rows and override getPreferredScrollableViewportSize() as shown for JTable and here。在封闭的 Window 上调用 pack() 将导致它成为 "sized to fit the preferred size and layouts of its subcomponents."