JPanel size by inner components

前端 未结 8 2385
夕颜
夕颜 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:39

    The javax.swing mysteries reveal themselves only gradually, and only to those who are prepared to offer many libations (particularly torn out clumps of hair, hours burning the midnight oil, etc.) to the gods of Swing.

    However, for this case in point I would suggest the following as a sort of Swiss army knife which usually does what you think the framework should do anyway:

    myJPanel.getTopLevelAncestor().validate()
    

    As the sacred text says, "Validates this container and all of its subcomponents." (Container.validate). NB getTopLevelAncestor() is a JComponent method.

    Can't remember how JSplitPane fits into this: try it and you'll probably find that it validates both components (right and left, top and bottom), but I would be surprised if changing the divider doesn't do this for you anyway.

提交回复
热议问题