Java: Difference between the setPreferredSize() and setSize() methods in components

后端 未结 4 1573
眼角桃花
眼角桃花 2020-11-22 11:11

What is the main difference between setSize() and setPreferredSize(). Sometimes I used setSize(), sometimes setPreferredSize(), sometimes one does

4条回答
  •  孤城傲影
    2020-11-22 11:48

    setSize() or setBounds() can be used when no layout manager is being used.

    However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize() methods like setPreferredSize() and setMinimumSize() etc.

    And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout, GridBagLayout, and SpringLayout managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout and GridLayout usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.

提交回复
热议问题