When is the size of the JComponent is calculated? After being shown in the screen or before that?
if I send .getSize()
message before .setVisible(true)
, would it give me the right answer?
Thanks
I sometimes check the sizes of my components when debugging to find out why I can't see them for instance. In most cases, the sizes will be realized when the GUI has been rendered. This can occur when pack()
or setVisible(true)
has called on the top-level window. My usual sequence of method calls is to call pack()
first as this tells the layout managers to lay out the components that they are responsible for, and sets the sizes of the components and the GUI, then call setLocationRelativeTo(null)
to center my GUI, then call setVisible(true)
to display it.
setLocationRelativeTo(null)
- I generally use setLocationByPlatform(true)
for GUIs running in 1.5+ JREs. –
Metastasis The layout manager is responsible for determining the size of a component, so you don't know its actual size until the component has been added to the frame and the frame has been pack()ed ore made visible.
If you use a layout manager that respects the preferred size of a component then you can use:
component.getPreferredSize();
Why do you think you need to know the size? Generally you don't worry about sizes and let the layout manager do its job.
JWindow
that will expand when the user clicks on a "more options"-button, and i wanted to know in advance the parameter of the .setSize()
message –
Suazo In addition to the usual pack()
> setVisible(true)
> getPreferredSize()
sequence, you can validate()
the relevant Container
to preview the geometry, as shown here.
If I understand properly, the reason why you want to know the size of a component is to reset the size of a JWindow once a user click on the "More options" button, isn't it?
I would suggest to do the following: when the user clicks on that button, update your UI adding the extra component, and the execute pack()
on the JWindow
. It should resize to the proper size.
JWindow
that is larger that the available screen space. For this case, I would recommend putting the check boxes into a JScrollPane
that is placed in a JPanel
. The JPanel
in turn would have a maximum size set. After the check boxes fill the available space, the scroll bars appear. –
Metastasis © 2022 - 2024 — McMap. All rights reserved.