You can set your preferred size using setPreferredSize(Dimension) ; eg.
JPanel pnl = new JPanel(new BorderLayout()); pnl.setPreferredSize(new Dimension(640, 480));
This value will subsequently be available by calling getPreferredSize() and will be used when composing the component, although note that it is not guaranteed that it will actually be displayed at this size.
Why do you need size before rendering it? Generally, with Swing programming, you donβt have to deal with explicit dimensions / dimensions, since the selected layout will take care of these features for you.
EDIT
To address an OP request regarding a JTextField , one option here is to invoke an int based constructor that accepts the expected number of columns. This causes the text box to be displayed wide enough to support this number of characters.
My second point is the commentary that setXXXSize methods should never be called directly and that the developer should rely solely on LayoutManager . This is not always suitable - usually it is necessary to set the preferred size of the main frame of the application. For example, suppose I am writing a simple browser application in Swing. The main body of the main frame is JEditorPane for rendering HTML. If I do not set a preferred size for this component (or containing frame), and I call pack() , the frame will most likely be displayed as small as possible, rather than with reasonable sizes.
source share