Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get real JPanel Size?

How should I get real JPanel size in JFrame?

like image 651
Yoda Avatar asked Aug 17 '12 17:08

Yoda


People also ask

What is default size of JPanel?

JPanel have default size 0 width and 0 height. You can set the size: manually: panel. setSize() , panel. setPreferredSize()

Can you set the size of a JPanel?

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.

Is a JPanel a JComponent?

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.

What is the difference between JPanel and JFrame?

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.


2 Answers

The size will be 0,0 until it is displayed because the components and layout are not calculated beforehand.

like image 117
Garrett Hall Avatar answered Nov 04 '22 04:11

Garrett Hall


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();
like image 33
km1 Avatar answered Nov 04 '22 06:11

km1