Get size of JPanel before realizing
I've created JPanel and have already added components into it and I'm going to pass开发者_JAVA百科 that JPanel to PopUpFactory... So can I get size of JPanel before passing it?
I put Jlabel into it and text after that and I don't know the size of that text...
You can set the preferred size using setPreferredSize(Dimension)
; e.g.
JPanel pnl = new JPanel(new BorderLayout());
pnl.setPreferredSize(new Dimension(640, 480));
This value will subsequently be obtainable by calling getPreferredSize()
and will be used when laying out the component, although note that it is not guaranteed that it will actually be rendered at this size.
Why do you actually require the size prior to rendering it? Typically with Swing programming you don't need to deal with explicit dimensions / sizes as the chosen layout will take care of these specifics for you.
EDIT
To address the OP's query regarding JTextField
, one option here it to call the int
based constructor that accepts the anticipate number of columns. This causes the text field to be rendered wide enough to support that number of characters.
My second point addresses the comment that the setXXXSize methods should never be called directly and that the developer should rely solely on the LayoutManager
. This is not always appropriate - Typically it is necessary to set the preferred size of your main application frame. For example, suppose I were writing a a simple browser application in Swing. The majority of the main frame is a JEditorPane
for rendering HTML. If I do not set a preferred size for this component (or the containing frame) and I call pack()
the frame is likely to be rendered as small as possible, rather than with sensible dimensions.
JComponents
doesn't returns getSize
, getLocation
, getBounds
or getXxxSize
if a JComponents
hasn't been previously visible on the screen or after call pack()
but why care about that, because usage of (proper and correct) LayoutManager can do that automatically, that reason why LayoutManager
exist there, really why care about that
Just call getPreferredSize method for JLabel.No matter if container of it is not realized, preferred size changes if you are setting text of jlabel even before you set it visible.
精彩评论