Re: Detailed GridBagLayout tutorial
A. Bolmarcich wrote:
On 2006-09-25, Knute Johnson <nospam@rabbitbrush.frazmtn.com> wrote:
A. Bolmarcich wrote:
If someone is interested, I'm looking to make the following:
A JTable covering the frame 100% horizontally and about 70% vertically,
located at the very top of the frame.
Just below the JTable I will have a small JPanel that will cover 100% of
the horizontal size and 10% vertically.
Just below that JPanel I will have yet another JPanel covering the rest
of the frame.
GridBagLayout does not support allocating percentages of the container
size among the components in the container. You can get that effect
using GridBagLayout by also overriding the preferred and minimum sizes
of the components. However, it would be better to use a layout manager
that supports the type of layout that you want, such as TableLayout (see
http://java.sun.com/products/jfc/tsc/articles/tablelayout/index.html).
That's just not true. GBL is great for just that type of layout.
What I wrote is true. In the example program, the "70%" button is
allocated 70% of the extra width, not 70% of the width of the container.
The extra width is the difference between the width of the container
and the sum of the preferred (or minimum) widths of the two buttons.
When I compile and run the program (after changing the invocation of the
setLayout and add methods to invoke on the content pane of the JFrame
rather than the JFrame)
As of 1.5 JFrame.add() is the same as JFrame.getContentPane().add()
the width of "70%" button is 248 and the width
of the "30%" button is 140. Which is a 64%/36% distribution of the
width, not 70%/30%.
Looks pretty close to me.
If setSize(400,300) is replaced with pack(), then the width of each
button is 59. Which is a 50%/50% distribution of the width, not
70%/30%.
If the ratios of the preferred and minimum widths of the two buttons
is 70%/30%, then having GridBagLayout distribute 70% of the extra
space to the larger button and 30% of the extra space to the smaller
button will keep the widths of the components in the 70%/30% ratio.
If the components are at their minimum sizes they will probably be the
same size.
TableLayout looks nice but it isn't part of Sun's API. I try not to use
things like that because they go out of date or are no longer supported
or whatever. If you stick to what comes with the API you can do what
the OP wanted, to a reasonable degree, and that's all you usually get
out of a layout manager any way.
The one thing I see that he is going to have a problem with is that
JTables don't appear to resize vertically.
The easiest solution is to not use a layout manager. I know that that
sends shudders through the cognoscenti but there are millions of C
programs out there that position their components that way.
knute...