当我动态地一个接一个地添加组件时,如何自动增加 JFrame 的高度

How to automatically increase height of JFrame when I am adding components one by one dynamically

我正在设计一个 swing 独立应用程序。在我的应用程序中,我有一个表单,当单击添加按钮时,我在其中动态地一个接一个地添加一些组件。我的要求是当我从上到下添加组件时,当添加的组件高度超过时,jframe 和 Main jpanel 必须增加其高度。

将 ContainerListener 添加到您的 JFrame。在 componentAdded 方法中,打包 JFrame。像这样:

    JFrame frame = getJFrame();
    frame.addContainerListener(new ContainerListener() {

        @Override
        public void componentAdded(ContainerEvent e) {
            frame.pack();
        }

        @Override
        public void componentRemoved(ContainerEvent e) {
        }
    });