These items are the ones that enable the user to dynamically interact with your program. They range from buttons to text display areas. Although different operating systems tend to use slightly different interaction elements, the AWT provides a rich enough set that users on all platforms will feel pretty much at home. This is especially true because the visual representation of each item actually is generated by the host operating system on the machine on which the application or applet is running. In addition, freeware, shareware, and commercial widget kits already exist that extend the basic elements provided by the AWT (see the section "Extending the AWT," later in this chapter, for more details).
Component Class-Shared Features of All Active GUI Elements
As you saw in Figure 17.3, all the active components (other than menus), such as Button, inherit from the Component class. The Component methods provide a wide selection of functionality applicable to any interactive graphical element. Although you can't create an instance of Component, you'll use its methods fairly often. Component has a lot of methods, but this section lists some of the ones you'll use fairly often. These methods are invoked in response to various types of events. In all cases, if the method returns TRUE, it means that the method has handled the event. If FALSE is returned, the event is passed up the event chain. You can use these methods on multiple objects to deal with the same event.
boolean, action(Event e, Object o)
This method usually is overridden. It's called whenever an ACTION_EVENT occurs on a component.
boolean, keyDown(Event e, int key)
This is called when a KEY_PRESS or KEY_ACTION event reaches a component. The key parameter specifies which key was involved. You can use this to have components respond to key clicks.
boolean, keyUp(Event e, int key)
This method is invoked when the component receives a KEY_RELEASE event.
boolean, lostFocus(Event e, Object o)
This is called when the object receives a LOST_FOCUS event.
boolean, mouseDown(Event e, int x, int y)
This is invoked when the component receives a MOUSE_DOWN event, caused by the user clicking the mouse inside the component. The x and y coordinates are in the coordinate system of the component, where 0,0 is in the upper-left corner.
boolean, mouseDrag(Event e, int x, int y)
This is invoked when the user drags the mouse with the mouse button down over the component, generating a MOUSE_DRAG event.
boolean, mouseEnter(Event e, int x, int y)
This is invoked each time the mouse goes over the component, generating a MOUSE_ENTER event.
boolean, mouseExit(Event e, int x, int y)
This is called when the component receives a MOUSE_EXIT event. The x and y values-which are expressed in the component's coordinates-represent the first point outside the component's bounding rectangle that the mouse goes over.
Although Component has a large selection of methods, the following are the ones you'll use most often.
Rectangle, bounds()
Returns the bounding rectangle that contains the component.
int, checkImage(Image img, ImageObserver iobs)
Monitors the status of an image as it's being composed. You can use this to wait to display a component, such as a Canvas, that uses an image until the image is ready.
Image, createImage(int width, int height)
Creates a new Image of the specified size.
disable()
Disables the component so that the user can't interact with it. (This is a synchronized method.) The AWT draws a disabled component differently than an enabled one.
enable()
Enables a disabled component. This is a synchronized method.
Color, getBackground()
Returns the color of the background for the component.
Font, getFont()
Returns the current font for the component.
FontMetrics, getFontMetrics()
Gets the FontMetrics, which contains information about the size of text on the current platform, for the component.
Color, getForeground()
Returns the foreground color-the one that will be used to draw lines, fill shapes, and so on.
Graphics, getGraphics()
Gets the Graphics object associated with the component. You can then use drawing methods, such as fillRect, that are associated with the Graphics object to draw on the component.
hide()
Makes the component invisible. This is a synchronized method.
boolean, inside(int x, int y)
Returns TRUE if x,y lies inside the component's bounding rectangle. x and y should be specified in the coordinate system of the container that holds the component. The container's coordinate system origin is in the upper-left corner of the container. This is a synchronized method.
invalidate()
Sets a flag indicating that the component has been changed in a way that requires the Layout Manager to be called to lay out the screen again. A button's name might be made longer, for example, so the button will need to be resized.
boolean, isEnabled()
Returns TRUE if the component is enabled to respond to user actions.
boolean, isShowing()
Returns TRUE if the component is visible in its parent's window. It can be visible but not showing if its height or width is 0 or if its location is outside the parent's window; for example, it might have been scrolled off-screen.
boolean, isVisible()
Returns TRUE if the component currently is visible. You can make a component invisible by invoking its hide method.
Point, location()
Returns a point that contains the coordinates of the component's origin.
move(int x, int y)
Moves the component to the specified position in the parent container's coordinate system.
paint(Graphics g)
Redraws the component when it needs to be redrawn. Unless you want some custom behavior, the default method ensures that the component is drawn properly.
boolean, prepareImage(Image img, ImageObserver img_obs)
Enables you to get an image ready for display prior to displaying it on the component. Another version enables you to specify a size for the image so that it can be scaled.
repaint(long time)
Repaints this component by a specified time or cancels the request.
repaint(int x, int y, int width, int height)
Repaints the specified part of the component.
repaint(long time, int x, int y, int width, int height)
Tries to repaint the specified region. If it can't do so before the specified time, it quits.
reshape(int x, int y, int width, int height)
Enables you to specify the position and size of the component. This is a synchronized method.
resize(int width, int height)
Scales the component to fit in the defined bounding rectangle maintaining the same origin. This is the same as the version below except you specify the width and height separately rather than with a Dimension object.
resize(Dimension dim)
Scales the component to fit in the defined bounding rectangle maintaining the same origin.
setBackground(Color a_color)
Sets the background color for a component. This is a synchronized method.
setFont(Font a_font)
Specifies the font that will be used for any text drawn in the component. This is a synchronized method.
setForeground(Color a_color)
Sets the color used for drawing lines and filling in shapes. This is a synchronized method.
show()
Makes the component visible if it had been hidden.
Dimension, size()
Returns the height and width of the component.
update(Graphics g)
Erases the contents of the component's graphic area every time it's called.
validate()
Causes the component to see whether it or any of the components it contains is invalid. If any are invalid, the Layout Manager is called to bring things up-to-date. See the section "Buttons," later in this chapter, for an example of how to use invalidate/validate.
Remember that all the interactive interface elements, including containers such as applets and windows, inherit from Component.
Containers
The AWT containers contain classes that can contain other elements. Windows, panels, dialog boxes, frames, and applets are all containers. Whenever you want to display a component such as a button or pop-up menu, you'll use a container to hold it. The base class for all containers is-surprise! surprise!-the Container class.
The Container class has a number of methods that make it easy to add and remove components as well as to control the relative positioning and layout of those components. Containers can contain other containers, for example, so a window can contain several panels.
Container is an abstract class, and the methods you'll use most often follow.add(Component a_component)
Adds a component to the container.add(Component a_component, int pos)
Adds a component at the specified z position. This is a synchronized method. Be warned that the order of clipping based on relative z position may vary between machines. This problem should be fixed eventually, though.int, countComponents()
Returns the number of top-level components of a container. It doesn't count components inside components; for example, a panel with three buttons inside a window is counted only as one component for the window.Component, getComponent(int index)
Returns a reference to the index component. The index value is determined when the component is added. This is a synchronized method. This throws ArrayIndexOutOfBoundsException.Component[], getComponents()
Returns an array of references to all the components in the container. This is a synchronized method.insets, insets()
Returns the insets object for the container. Insets define the empty space the Layout Manager reserves around the edge of the container-the minimum distance from the edge of a component to the edge of the container.remove(Component a_component)
Removes the component from the container. This is a synchronized method.setLayout(LayoutManager lm)
Sets the Layout Manager the container will use. If you supply NULL as the argument, no Layout Manager is used; you can use absolute positioning.Panels
Applet inherits from this class, so this section examines Panel in detail so that you can understand how the various demonstration applets work. The other container classes are discussed later in this section.
Panel inherits from Container. It doesn't create its own window because it's used to group components inside other containers. Panels enable you to group items in a display in a way that might not be allowed by the available Layout Managers. If you have a number of entries in your interface, for example, that have a label and a text field, you can define a panel that contains a label and a text field and add the panel so that the label and the text field always stay together on the same line (which wouldn't be the case if you added the two items separately). Without the panel, the Layout Manager could put the label and the text field on different lines. Panels also are useful in Layout Managers in which only one item is allowed in an area, such as the BorderLayout Manager. By using a panel, you can put several components in a single BorderLayout area, such as North.
Note A Layout Manager autopositions and sizes the various interface components, taking into account the screen resolution and the window size.Insets
An inset object defines the amount of empty space around the edge of a panel. The creator method for insets follows:Insets, new Insets(int top, int left, int bottom, int right)This defines a new Insets instance, which defines the boundaries specified by the input arguments.
You can change the amount of empty space, which is set to 0 by default, by overriding the Insets method of the container. The applet in Listing 17.15 defines its own panel class that does that. It defines a plain panel and a custom version that overrides the Insets method. Each of the items has four buttons added. Both items have white backgrounds so that you can see the size of the item, not just where the buttons are.
Listing 17.15. Defining a panel class.
import java.awt.*;
import java.applet.Applet;
public class HelloWorld extends Applet
{
public void init()
{
Panel a;
my_panel b;
GridLayout gl;
Button buttons[];
int i;
//create a new GridLayout to force the 4 buttons to arrange themselves
// in a 2 by 2 grid
gl = new GridLayout(2,2);
//create two panels to contain the 8 buttons
a = new Panel();
b = new my_panel();
//tell the panels to use the GridLayout manager rather than the default
//FlowLayout manager
a.setLayout(gl);
b.setLayout(gl);
//Make the backgrounds of the panels white so you
//can see them in the picture
a.setBackground(Color.white);
b.setBackground(Color.white);
//add the panels to the applet
add(a);
add(b);
//make the buttons and add them to the panels
buttons = new Button[8];
for(i=0; i< 8;i++) {
buttons[i] = new Button("Button " + i);
if (i <4) {
a.add(buttons[i]);
} else {
b.add(buttons[i]);
}
}
}
}
class my_panel extends Panel {
//This class exists so we can override the insets method
public Insets insets() {
return new Insets(5,10,15,20);
}
}
The applet generates the applet interface shown in Figure 17.19; look closely to see the white background for the first panel. Because the insets for the top panel default to 0, the panel background is the same size as the space required by the buttons. The custom panel is larger than the buttons because of the inset's value; the space on each side is different because the four values assigned to the inset are all different.Frame
A frame is a full-fledged, top-level, resizable window with a menu bar. You can specify the title, an icon, and a cursor. See the "Frames" section for examples.Windows
This class isn't used very often, but it's a top-level window without borders and a menu bar.
No comments:
Post a Comment