Sams Teach Yourself C in 21 Days

(singke) #1

Using Buttons and Pop-Up Windows ..........................................................


Although drawing graphics shapes is often useful, more often a Java program must use
predefined screen elements such as buttons, menus, text boxes, and the like. The AWT
provides a full range of classes for all the screen elements that you see used in window-
ing applications. In addition, Java provides the capability to detect user events, such as
when the user clicks on a menu command or a button. It then allows you to react appro-
priately. Later, a program will be presented that demonstrates a few of these capabilities,
but first you need some more background information.

Layout Managers in Java
When you create a window that contains a variety of elements, such as buttons, labels,
and text boxes, you, of course, want to arrange these elements within the window in a
neat and attractive manner—one that makes sense with respect to the program’s function-
ality. Some programming languages, such as Visual Basic, let the programmer precisely
position window elements both by dragging them around during program design and by
setting their locations and sizes numerically. The developers of Java did not choose this
approach because Java programs are designed to run on such a wide variety of platforms
with widely different display hardware. Some other approach to window layout was
needed.
The approach that they developed uses a tool called a layout manager. When you create
a window or any other container that can hold visual elements, you associate a layout
manager with it. Then, as buttons and other elements are added to the container, the lay-
out manager controls how they are arranged within the container. Because this happens
when the program is running, information about the specific display hardware is avail-
able to the layout manager, and it can arrange the elements appropriately for the current
display.
The Java AWT has five basic layout managers. The default,FlowLayout, arranges ele-
ments left-to-right, top-to-bottom. The other managers are called GridLayout,
BorderLayout,CardLayout, andGridBagLayout. The layout managers are classes, as is
just about everything else in Java, so you must create an instance of the one you want to
use:
FlowLayout lm = new FlowLayout();

754 Bonus Day 6

DOlearn about the classes available in
the AWT in order to program graphics
effectively.

DON’Tforget that creating a shape and
actually drawing it are two different
steps.

DO DON’T


41 448201x-Bonus6 8/13/02 11:23 AM Page 754

Free download pdf