Can I get the right JComponent size before it's shown?

孤街醉人 提交于 2019-12-08 16:37:51

问题


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


回答1:


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.




回答2:


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.




回答3:


In addition to the usual pack() > setVisible(true) > getPreferredSize() sequence, you can validate() the relevant Container to preview the geometry, as shown here.




回答4:


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.



来源:https://stackoverflow.com/questions/7142609/can-i-get-the-right-jcomponent-size-before-its-shown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!