Re: Detailed GridBagLayout tutorial
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) 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%.
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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test extends JFrame {
public test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = .7;
JButton b = new JButton("70%");
add(b,c);
c.weightx = .3;
b = new JButton("30%");
add(b,c);
setSize(400,300);
setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
new test();
}
};
EventQueue.invokeLater(r);
}
}