How should I get real JPanel size in JFrame?
JPanel have default size 0 width and 0 height. You can set the size: manually: panel. setSize() , panel. setPreferredSize()
We change the background colour to red, and give the JPanel a size using setSize(width, height). We also give the widget a location using setLocation(x pixels, y pixels). This sets the top left hand corner of the widget to the specified position.
With the exception of top-level containers, all Swing components whose names begin with "J" descend from the JComponent class. For example, JPanel , JScrollPane , JButton , and JTable all inherit from JComponent . However, JFrame and JDialog don't because they implement top-level containers.
Basically, a JFrame represents a framed window and a JPanel represents some area in which controls (e.g., buttons, checkboxes, and textfields) and visuals (e.g., figures, pictures, and even text) can appear.
The size will be 0,0
until it is displayed because the components and layout are not calculated beforehand.
thePanel.getSize();
This returns the Dimension.
I sometimes add a ComponentListener to show the dimension when the panel is resized.
EDIT: If you want the size of the content pane of the JFrame then
theFrame.getContentPane().getSize();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With