Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPanel size by inner components

Tags:

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

like image 957
Jakub Arnold Avatar asked May 11 '09 19:05

Jakub Arnold


People also ask

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?

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.

What is the difference between panel and JPanel?

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.

Does JPanel extend JComponent?

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.


2 Answers

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.

like image 117
Michael Myers Avatar answered Oct 09 '22 11:10

Michael Myers


By default Containers 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.

like image 25
Tom Hawtin - tackline Avatar answered Oct 09 '22 09:10

Tom Hawtin - tackline