Java Reference
In-Depth Information
Example 10•7: GridBagLayoutPane.java (continued)
this.add(new JButton("Button #2"), c);
c.gridx = 4; c.gridy = 1; c.gridwidth = 1; c.gridheight=1;
this.add(new JButton("Button #3"), c);
c.gridx = 4; c.gridy = 2; c.gridwidth = 1; c.gridheight=2;
this.add(new JButton("Button #4"), c);
c.gridx = 0; c.gridy = 4; c.gridwidth = 1; c.gridheight=1;
this.add(new JButton("Button #5"), c);
c.gridx = 2; c.gridy = 4; c.gridwidth = 1; c.gridheight=1;
this.add(new JButton("Button #6"), c);
c.gridx = 3; c.gridy = 4; c.gridwidth = 2; c.gridheight=1;
this.add(new JButton("Button #7"), c);
c.gridx = 1; c.gridy = 5; c.gridwidth = 1; c.gridheight=1;
this.add(new JButton("Button #8"), c);
c.gridx = 3; c.gridy = 5; c.gridwidth = 1; c.gridheight=1;
this.add(new JButton("Button #9"), c);
}
}
Hardcoded Layout
All AWT and Swing containers have a default layout manager. If you set this man-
ager to null , however, you can arrange components within a container however
you like. You do this by calling the setBounds() method of each component, or,
in Java 1.0, by calling the now deprecated reshape() method. Note that this tech-
nique does not work if any layout manager is specified because the layout man-
ager resizes and repositions all the components in a container.
Before using this technique, you should understand that there are a number of
good reasons not to hardcode component sizes and positions. First, since compo-
nents can have a platform-dependent look-and-feel, they may have different sizes
on different platforms. Similarly, fonts differ somewhat from platform to platform,
and this can affect the sizes of components. And finally, hardcoding component
sizes and positions doesn't allow for customization (using the user's preferred font,
for example) or internationalization (translating text in your GUI into other lan-
guages).
Nevertheless, there may be times when layout management becomes frustrating
enough that you resort to hardcoded component sizes and positions. Example
10-8 is a simple program that does this; the layout it produces is shown in Figure
10-8. Note that this example overrides the getPreferredSize() method to report
the preferred size of the container. This is functionality usually provided by the
layout manager, but in the absence of a manager, you must determine the pre-
ferred size of the container yourself. Since a Swing container is being used, over-
riding getPreferredSize() isn't strictly necessary; try calling setPreferredSize()
instead.
Search WWH ::




Custom Search