Is it possible to tell JPanel to set its size to fit all components that it contains? Something like pack()
for JFrame.
edit: The trick with preferredSize didn't help. I've got JSplitPane, where in one part there is GridBagLayout with many labels (see screenshot) and labels overlap each other.
screenshot http://foto.darth.cz/pictures/screen.png
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.
JPanel is a subclass of the JComponent, which is a child of the Container; therefore, JPanel is also considered a container. There are many methods used by JPanel, which it inherits from its parent classes.
You can put many operations inside one panel. JPanel is a subclass of JComponent, and JComponent is a subclass of Container, therefore, JPanel is also a container. There are so many methods that can be used for JPanel, which it inherited from its super classes.
Generally if you want to draw something manually you'll extend JComponent and override the paintComponent() method. When people extend JPanel they rarely override any JPanel methods.
After looking at the source code for pack()
, I came up with:
panel.setPreferredSize(panel.getPreferredSize());
This forces the panel to recalculate its preferred size based on the preferred sizes of its subcomponenents.
You may or may not have to call validate()
afterward; in my tiny example, it seemed to make no difference, but the Javadoc says:
The
validate
method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.
So I guess it depends on why you're having to repack your JPanel
.
By default Container
s have a preferred size that matches the preferred layout size given by the container. So literally all you have to do is:
panel.setSize(panel.getPreferredSize());
Presumably you are doing something odd with the parent to stop the parent's layout manager doing the equivalent of this.
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