What's the easiest way to make a JPanel
that takes up a fixed percentage of its parent container, by width?
Its width should update when that of its parent container changes.
I tried using Box.createHorizontalStrut()
, but that doesn't update when the width of the JPanel
's parent container changes.
Another option is to use a
SpringLayout
:You could use the Relative Layout. This layout was designed for this purpose since none of the layouts from the JDK support this directly (and easily).
As a simple example you could have 3 panels at 25%, 25% and 50% of the width:
What you want is a GridBagLayout. (How to use?)
Using a GridbagLayout allows you to define GridBagConstraints for each single component you add.
These constraints include
weightx
which does exactly what it says on the tin. This is a relative value calculated across all components in that "grid-row", similar to distribution parts.Be aware that the weightx only begins to come into play, when the preferred size of components is exceeded. Be aware that this may lead to interesting bugs, when setting minimumSize(), see also this SO answer.
Anyways: you can get the value you need for weightx by specifying it's percentage across the components in it's current row, or any multiple of that.
This means for a component to take 50% of the available parent container width, use
weightx = 0.5
. make sure that the row's weightx values add up to1.0