JPanel size by inner components

前端 未结 8 2240
夕颜
夕颜 2021-02-18 13:48

Is it possible to tell JPanel to set its size to fit all components that it contains? Something like pack() for JFrame.

edit: The trick with preferredSize d

8条回答
  •  时光取名叫无心
    2021-02-18 14:40

    After looking at the source code for pack(), I came up with:

        panel.setPreferredSize(panel.getPreferredSize());
    

    This forces the panel to recalculate its preferred size based on the preferred sizes of its subcomponenents.

    You may or may not have to call validate() afterward; in my tiny example, it seemed to make no difference, but the Javadoc says:

    The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.

    So I guess it depends on why you're having to repack your JPanel.

提交回复
热议问题