JPanel size by inner components

前端 未结 8 2239
夕颜
夕颜 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条回答
  •  Happy的楠姐
    2021-02-18 14:39

    Here's an example of a panel which:

    • Resizes with it's parent.
    • Sets the width to the width of the parent.
    • Sets the height according to sum of the height of all of it's children.
    JPanel panel = JPanel(new GridBagLayout())
    
    panel.setMaximumSize(new Dimension(panel.getMaximumSize().width, panel.getPreferredSize().height))
    
    panel.validate()
    panel.repaint()
    

提交回复
热议问题