What is the difference between the setSize()
method and the setPrefferedSize()
method in a Frame, and in which situation should each be used?
What is the difference between the setSize()
method and the setPrefferedSize()
method in a Frame, and in which situation should each be used?
The method setPreferredSize()
is inherited from class Component
, and as its name suggests, it sets a preferred size for JFrame
. It is recommended to use it when we are using Layout Managers . >, because this is the way we tell him that we want the component to be, to the extent possible, that size. Of course, it can ignore this value, depending on its operation and the space required for the distribution of other components on the screen, and even because of the resolution of the monitor as well, but usually the managers use that size as a base and respect it at the time of rendering the component.
Other methods that can be used in conjunction with this to provide greater control of the component's size are the setMaximumSize()
" and setMinimumSize()
", which define the maximum and minimum size of the component, respectively.
The method setSize()
manually sets the window shape differently from the previous method that only suggests a size to the layout manager, but can also be ignored depending on the manager used. You can use it if the container of the component that is to be set does not have an active layout manager, otherwise it can also be ignored.
As a rule, you should always use the first one, since not using a layout manager can bring much greater complications than managing the size of the components.
Sources:
Java: Difference between the setPreferredSize () and setSize () methods in components
Class documentation Component
and < a href="https://docs.oracle.com/javase/9/docs/api/java/awt/Window.html"> Window
.