CS102: Class Hierarchy Example: java.awt

Copyright © 1999, Kenneth J. Goldman

GridBagLayout


This is the most complicated Layout manager that the awt provides. It lets you arrange components in rows and columns and specify constraints on how the components will "grow" to fill the available space. For example, this MyFrame.java
file defines a frame with the components shown below.


We can think of the container as a grid using any scale we want. For example

A is at (0,0) and its size is 10 x 1
B is at (0,1) and its size is 5 x 8
C is at (0,9) and its size is 5 x 1
D is at (5,1) and its size is 5 x 9

When we add each object to the container, we use a GridBag Constraints object that specifies these dimensions, plus gives a width (0 to 100) of how much the component should grow in X and Y relative to other components, and a constant that specifies in what dimensions it can grow.
You can reuse the GridBag Constraints object for each component as you add it, since the GridBagLayout manager makes a copy. It's handy to define a method to set all these constraint values.

Creating Your Own Layout Manager


The existing layout managers embody algorithms for positioning things on the screen and rearranging/resizing components when a window is resized. But sometimes, you may want to control the layout yourself. As an extreme example of this let's define a layout manager that doesn't rearrange the components or resize them at all -- it just leaves them where you put them, and doesn't resize the container.


Note: All Component objects have setBound and setSize methods that can be used by the layout manager to move and resize them. Also, getPreferredSize() etc. are provided by components as "hints" to the layout manager.


For example, this FreeFormLayout layout manager allows the programmer to specify all the sizes and positions of components directly, as described above.

Creating Your Own Components


You can only go so far with the built-in buttons and checkboxes. To create your own components for a user interface, you can extend Component. For example, let's create a component, Picture, that can be used to display an image.