Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

The Component Class

java



+ Font mai mare | - Font mai mic



The Component Class

All visual elements of a graphical interface have functionalities in common. Top-level windows, visual controls such as text boxes and push buttons, as well as simple elements for drawing images on the screen have a commonality of capabilities. The Component class, which implements these common functionalities, is an ancestor class for all graphical interface elements.

In the Java system, all classes that implement graphical interface elements are subclasses of the Component class. There are several families of Component class methods, which allow you to control the internal state and on-screen appearance of all Components. They cover the following areas of functionality:



.  Component hierarchy. Components are placed on the screen within special Container components. Containers may be placed within other Containers, and so on, forming an on-screen hierarchy of Components.

.  Component positioning and sizing.

.  Common Component states. All Components share a basic set of internal state variables. The Component class implementation provides methods that allow these state variables to be polled and modified.

.  On-screen rendering.

.  Delivering and handling events. These include user, custom, and system events such as mouse events, keyboard and keyboard focus events, and so on.

.  Preparing and displaying images.

In addition to the Component classes included in the java.awt package, you can create your own custom Components. You can create almost any imaginable visual element as a custom Component. The Project for this chapter demonstrates the creation of a relatively simple custom Component called a Hotspot.

Component Hierarchy

Each Component object instance is "owned by" a parent Component object. The on-screen positioning of a Component is restricted to being within the bounds of its parent Component. More specifically, the rectangle of actual display device pixels, or "bounding rectangle," dedicated to a particular Component is restricted to lying completely within the bounding rectangle of its parent Component. Figure 2-1 illustrates the hierarchy of Components and Container components of a simple graphical user interface. The graphical Component controls are contained within Containers, which are in turn contained within the Frame window, another type of Container component. The Frame window is a top-level window, and so does not have a parent Container.


Figure 2-1  Component hierarchy of a simple dialog box

Components that can contain other Components are derived from the Container class. There are several areas of interest specific to the Container class. This chapter will cover a minority of those topics as necessary to understand the Component class concept.

The getParent method provides a reference to the Container of any Component object:

Container parent = myComponent.getParent();

Components that have not been placed within a parent Container, obviously, will not have a parent Container object reference returned by getParent. For orphan Components, as well as for top-level Frame windows, a null will be returned by this method. Components are placed within Containers using the add method of class Container. The specifics of the overloaded versions of this method are discussed in Chapter 3. For simplicity's sake, you can assume that a call to this method effectively sets the owner of the Component object to the specific Container. Listing 2-1 adds a single push button (a type of Component object) to the interface of an Applet (a type of Container object).

Listing 2-1 Adding a Component to a Container using the Container's add method

public class MyApplet extands Applet



Component Positioning

All Component objects have a rectangle of display area in which they render themselves. This rectangle is called the Component's bounding rectangle. The size of the Component's bounding rectangle can be looked up using the Component's size method. The resize method allows you to modify these dimensions:

Dimension dimComp = myComponent.size();
myComponent.resize(dimComp.width + 10, dimComp.height + 10);

Note that the actual rectangle of screen real estate a Component is allowed to render itself on is the intersection of the component's bounding rectangle with the parent Container's bounding rectangle (which is intersected with its parent's bounding rectangle, and so on). Therefore, if a Component has been resized to be larger in dimension than its parent Container, then the Component will be "clipped" on the screen according to its position relative to its parent Container.

For the most part, the positioning of a Component object within its parent Container is under the control of the Container's LayoutManager object. Chapter 3 discusses how Components are laid out within a Container by the LayoutManager object. A Component object is positioned relative to the upper-left corner of its parent Container. The location method returns the coordinates of a Component relative to the upper-left corner of its parent Container. That is, the upper-left corner of the parent Container is (0,0) for all Component positioning coordinates. The move method is called to change the position of a Component relative to its parent Container:

// Move myComponent 10 pixels right and down.
Point ptLoc = myComponent.location();
myComponent.move(ptLoc.x + 10, ptLoc.y + 10);

A Component's bounding rectangle can be fully described by its position and dimensions. The bounds method returns a Rectangle object whose x and y members indicate the position of the Component, and whose width and height members describe the dimensions of the bounding rectangle. The reshape method allows you to modify both the position and dimensions of a Component's bounding rectangle. Listing 2-2 demonstrates the positioning methods for Components. It centers a Component relative to its parent Container's bounding rectangle.

Listing 2-2 Centering a Component with respect to its parent's bounding rectangle

Component comp;

// Comp is set to be a reference to a Component

Rectangle rectCompBounds = comp.bounds();
Dimension dimParent = comp.getParent().size();

rectCompBounds.x = (dimParent.width / 2) -
(rectCompBounds.width / 2);
rectCompBounds.y = (dimParent.height / 2) -
(rectCompBounds.height / 2);

comp.reshape(rectCompBounds.x, rectCompBounds.y,
rectCompBounds.width, rectCompBounds.height);

Common Component States

All basic visual elements such as push buttons, list boxes, and check boxes can either be enabled or disabled. By default, Components are enabled, though they may be disabled. Disabled Components generally take on a "hampered mode" look and feel, and are generally unreactive to user actions like mouse clicks or keyboard input. Figure 2-2 illustrates several basic visual elements when enabled and disabled. The disable method disables a Component object, and enable forces a Component to be enabled. The isEnabled method returns a boolean true or false, indicating whether the Component is currently enabled.


Figure 2-2  Enabled and disabled Button, List, and Choice objects

Components can also be hidden or visible. By default, Components when created are visible, but they can be hidden using hide. A hidden Component is effectively removed from the visual interface, as are all of that object's child Components. The Component positioning and other internal state member methods act exactly the same for a Component whether the Component is hidden or visible. The show method forces a Component to be visible. The Component's isVisible method returns a boolean true or false, indicating whether the Component is currently visible. Hiding a Component can be an effective method for removing inappropriate visual elements from the graphical interface.

The isShowing method tells you whether or not a Component has any display surface real estate assigned to it. That is, isShowing returns true only if the Component is visible, and is positioned such that its bounding rectangle intersected with its parent's bounding rectangle is non-null.

A Component can also be marked as valid or invalid. The state of the validation flag indicates whether or not the Component must be laid out using the Component's layout method. The default implementation of this method actually does nothing. However, the Container class overrides the layout method to actually arrange any child Components on the screen.

Use the invalidate method to mark the Component as invalid. The validate method will call layout if the state of the Component is invalid (i.e., invalidate was called prior to the call to validate). If the Component has not been marked as invalid, then validate returns without doing anything.

On-Screen Rendering

All the basic visual Components, such as list boxes and push buttons, are able to render themselves on the screen. You can also create custom controls such as gas gauges, spin dials, or just about any visual element imaginable. The SuperBible project for this chapter illustrates the creation of just such a custom control. Your custom controls, however, must render themselves. To actually render custom controls you must re-implement one or more Component class methods.

The central method used to render a Component on the screen is paint. The paint method is passed a Graphics object attached to the display device, and clipped to the bounding rectangle of the Component. (Chapter 1, Applets and Graphics, discussed the Graphics class in detail and how Graphics objects are used to paint on a drawing surface.) The simplest custom Component classes re-implement this method to render the Component in the graphical interface. Listing 2-3 shows a trivial custom paint method implementation that simply draws a filled oval within the Component's bounding rectangle.

Listing 2-3 A simple custom Component

class MyComponent extends Canvas
public void paint(Graphics g)

Note that the custom Component class MyComponent actually is derived from the Canvas class. You cannot derive a class from the Component class directly, since the Component class has no public constructors. Generally, you will create custom Component classes, which are derived from the Canvas class, since the Canvas class is the simplest Component with a public constructor.

The Java system calls a Component's paint method asynchronously whenever it determines a Component object must be re-drawn on the display surface. This call is performed by a Thread created and controlled by the Java system. The Java system manages the Graphics object passed to paint directly because graphical device contexts are a limited resource in most graphical operating systems. You must not call paint directly. To force a repainting of a Component object, use the Component's repaint method. Using this method, you can schedule a repainting of the Component within a specific time period, and you can also restrict the repainting to a subset of the the Component's full bounding rectangle. There are four overloaded versions of the repaint method:

repaint();
repaint(lMillisecs);
repaint(x, y, width, height);
repaint(lMillisecs, x, y, width, height);

The two versions, which do not specify a time limit, instruct the Java runtime system to schedule a repainting of the Component at some time in the future. The Java system may not schedule a repainting for ten minutes, or the repainting could happen instantaneously. Repainting is a relatively low-priority operation, so the system waits until there is a lull in processing to actually perform the repainting. Using one of the two versions of the repaint method that take a lMillisecs parameter, you can specify a maximum number of milliseconds the Java system can wait before forcing a repainting of your Component object.

The repaint method instructs the Java runtime system to schedule an asynchronous call to Component.update. The update method is responsible for calling paint. The default implementation of update erases the entire drawing surface of the Component object using the Component's background Color, then selects the Component's foreground Color into the Graphics object before calling paint. Figure 2-3 illustrates how Component rendering is accomplished through the three cooperating methods: paint, repaint, and update. You can see that the only method a custom Component needs to re-implement is paint. Re-implementing the update method can be quite useful, especially when animation techniques are used. A discussion of animation techniques and the update method is included in Chapter 1.


Figure 2-3  Cooperative methods paint, repaint, and update used to keep on-screen rendering of a Component up-to-date

Delivering and Handling Events

An event, in Java lingo, is an object that describes some specific occurrence in the system. For example, there are several types of mouse events to describe a user's mouse actions. There are also several types of keyboard events to describe user keyboard interactions. Event objects are created by the Java runtime system whenever a specific occurrence is detected, and these Event objects are delivered to specific Components through the Component class Event delivery and handling methods.

The Component class Event delivery methods implement a system whereby Events are passed from a Component to its parent Container, to that object's parent Container, and so on until the event is "handled."

The delivery system can best be illustrated through an example. Figure 2-4 is a screenshot of a very simple user interface in an Applet run within the JDK's AppletViewer. This interface is comprised of the Applet object itself, and a Button object with the caption OK. Imagine the user clicks on the OK Button. This causes an Event object of type ACTION_EVENT to be generated by the Java system and delivered to the OK Button. Button objects, by default implementation, do not handle this type of Event, and so the Event is further delivered to the Button's Container-the Applet object. The Applet object may or may not handle this Event. If not, the Event will further be delivered to the Applet's Container, and so on until either the Event is handled or a top-level Container is reached.


Figure 2-4   A very simple Applet interface

Delivering an Event to a Component is done using the Component's postEvent method. The Java runtime system delivers mouse, keyboard, or other Events to a specific Component using this method.

You can also create your own custom Events (objects derived from the Event class) and deliver them to Components using a similar mechanism. Instead of calling the postEvent method directly, call Component.deliverEvent. The default implementation of deliverEvent takes the Event and passes it to postEvent. Thus, the deafult implementation of deliverEvent is a simple wrapper for postEvent.

The postEvent method is responsible for finding an object to handle each Event it is passed. postEvent offers the Event to three different objects. If no object handles the Event, postEvent returns benignly and the Event is forgotten. The three objects postEvent offers each event to are (in order)

.  The Component's peer, through peer.handleEvent

.  The Component itself, through this.handleEvent

.  The Component's parent Container, through parent.postEvent

The handleEvent method returns a boolean true or false value, indicating whether or not the Event was handled. This pseudo-code in Listing 2-4 illustrates the simple algorithm used by postEvent to find an object to handle each event passed to a particular Component.

Listing 2-4 Pseudo-code for postEvent

boolean method postEvent(Event evt):
1. if peer.handleEvent(evt) == true, return true.
2. if this.handleEvent(evt) == true, return true.
3. if parent.postEvent(evt) == true, return true.
4. return false.
end method postEvent

The default implementation of handleEvent is a giant switch statement. Each Event is classified according to the type of Event, and an appropriate Component class handling method is called. For example, the Component class method mouseDown is called by the default implementation of handleEvent whenever a MOUSE_DOWN Event occurs. The summary section on the next page details all the Component class Event handling methods. Custom Component implementations should override these methods to handle specific types of Events.

Preparing Images for Display

Before an Image object can be rendered onto any drawing surface, a representation of the Image suitable for painting on that surface must be constructed by the Java system. The construction is an asynchronous process carried out by the Java system because this process may include downloading of Image data from a remote server. (Downloading of any kind of data is always an asynchronous operation.) The Component class includes methods to manage the Image construction process so that any Component object may prepare and display Images.

The Image construction process is started by a call to the Component's prepareImage method. The Image object to prepare is passed as a parameter to this function. To receive asynchronous notification of the progress of Image construction, an object must implement a special interface called java.awt.image.ImageObserver. The ImageObserver's imageUpdate method, the only method defined by the ImageObserver interface, is called by the Java system automatically as the Image object construction process proceeds.

An implementation of imageUpdate is included in the Component class, so any Component object may be used as an ImageObserver. The default implementation of this method schedules an asynchronous repainting of the Component when the Image has been prepared sufficiently to display. The code snippet in Listing 2-5 illustrates how any Component can prepare an Image for display.

Listing 2-5 Preparing an Image for display

class MyComponent extends Component

// This re-implementation of Component.imageUpdate() detects
// when an Image has been fully prepared for rendering.
public void imageUpdate(Image img, int flags, int x, int y,
int width, int height)

Summary of the Component Methods

Table 2-1 lists all the methods of the Component class, and provides a brief description of each. The methods are broken down by functional grouping rather than alphabetically.

Table 2-1 Summary of Component methods


Group

Method

Description


Event Handlers

action

Handles ACTION_EVENT Events. Button pushes and menu bar selections are two types of user interactions.

lostFocus

Handles LOST_FOCUS Events. The keyboard focus has been removed from this Component, as when the user hits the key in a dialog.

gotFocus

Handles GOT_FOCUS Events. The keyboard focus has been moved to this Component, as when the user hits the key in a dialog.

keyDown

Handles KEY_DOWN Events. For the Component with keyboard focus, each keypress by the user creates such an Event.

keyUp

Handles KEY_RELEASE Events. For the Component with the keyboard focus, each time a key is released such an Event is created.

mouseDown

Handles MOUSE_DOWN Events. The user has clicked the mouse button within the Component's bounding rectangle.

mouseDrag

Handles MOUSE_DRAG Events. The user has moved the mouse with the mouse button held down.

mouseEnter

Handles MOUSE_ENTER Events. The mouse cursor has been moved from outside the Component's bounding rectangle to within it.

mouseExit

Handles MOUSE_EXIT Events. The mouse cursor has been moved from within the Component's bounding rectangle to outside it.

mouseMove

Handles MOUSE_MOVE Events. The mouse has been moved without the mouse button being held down.

Size and Position

bounds

Returns a Rectangle object whose x and y members indicate the position of the upper-left corner of the Component relative to the origin of the parent Container's origin. The Rectangle's width and height members hold the Component's dimensions.

inside

Tells whether or not a particular point lies within the Component's bounding rectangle.

locate

Returns a reference to the Component or subComponent that contains the indicated point.

location

Returns a Point object whose x and y members indicate the position of the Component's upper-left corner relative to the parent Container's origin.

move

Moves the upper-left corner of the Component to the indicated point relative to the parent Container's origin.

resize

Changes the dimensions of the Component object's bounding rectangle.

size

Returns a Dimension object whose width and height members indicate the size of the Component's bounding rectangle.

reshape

Changes the Component's position and dimensions in a single call. The move and resize methods are actually wrappers around this method.

minimumSize

Override this method to specify the smallest size a parent Container should dedicate to this Component.

preferredSize

Override this method to specify the preferred size a parent container should dedicate to this Component.

Visual State

isValid

Indicates whether or not the Component has been marked as valid.

invalidate

Marks the Component as invalid.

validate

If the Component is invalid, calls layout before resetting the valid flag to valid.

isVisible

Indicates whether or not the Component is currently marked as visible.

show

Makes the Component visible.

hide

Makes the Component invisible.

isShowing

Returns true only if the Component is visible and owns some rectangle of the desktop.

isEnabled

Indicates whether or not the Component is enabled.

enable

Enables the Component.

disable

Disables the Component.

Graphics State

getForeground

Gets the Color object for the Component's foreground color. The Graphics passed to paint uses this color as its current foreground color. Uses parent's foreground if Component's color has not been set using setForeground.

setForeground

Sets the current drawing color for the Graphics passed to paint.

getBackground

Gets the color used to erase the Component in update. Returns parent's background color if Component's background has not been set using setBackground.

setBackground

Sets the color used by update to erase the Component.

getFont

Returns the Font used to render text in paint. Parent's Font is returned if font has not been set by setFont.

setFont

Sets the Font used to display text in paint.

getColorModel

Returns the color model used by the desktop to display the Component.

getGraphics

Returns a Graphics object attached to this Component's on-screen rectangle.

getFontMetrics

Returns a FontMetrics detailing the Component's Font (what is returned from getFont) as rendered to the Graphics display surface.

Component

Purpose

Abstracts all window components. Functionalities common to all such components are implemented in the Component class.

Syntax

public abstract class Component implements ImageObserver;

Description

An abstract windowing component. All Components have a bounding rectangle of on-screen space in which to render themselves. Java has several predefined Component classes, such as a TextField, a Checkbox, or a Frame. The Component class implements methods for Event handling and management of an on-screen bounding rectangle. Figure 2-5 is an inheritance diagram for the Component class.


Figure 2-5  Inheritance diagram of the Component class

PackageName

java.awt

Imports

java.io.PrintStream,java.awt.peer.ComponentPeer, java.awt.image.ImageObserver, java.awt.image.ImageProducer,

java.awt.image.ColorModel

Constructors

None.

Parameters

None.

action

ClassName

Component

Purpose

Event handler for ACTION_EVENT Events.

Syntax

public boolean action(Event evt, Object arg);

Parameters

Event evt

The ACTION_EVENT Event object.

Object arg

Argument attached to the Event object evt. This is identical to the arg member of evt.

Description

Called by the default implementation of handleEvent whenever an ACTION_EVENT is sent to the Component object. Action events include selection of a menu item and pressing a button. Override the default implementation of this method to make your Component react to action events.

Imports

None.

Returns

Returns true if the action event is handled by this Component object. A return value of false causes the Event to be automatically sent to the parent Container of this Component. The default implementation simply returns false.

See Also

The handleEvent method of the Component class

Example

The following example alternatively disables and enables a Go button whenever the Example button is pressed. The action method's arg in this case is the String title of the button that was pressed.

public class MyContainer extends Panel

action(Event evt, Object arg)

bounds

ClassName

Component

Purpose

Gets the bounding rectangle for this Component.

Syntax

public Rectangle bounds();

Parameters

None.

Description

This method gets a Rectangle object whose x and y members are set to the coordinates of the upper-left corner of the Component, relative to the origin of the parent Container. The width and height members of the Rectangle are set to the dimensions of the Component.

Imports

None.

Returns

A Rectangle object describing the bounding rectangle of this Component object is returned. The values expressed are relative to the origin of the parent Container object. The x and y members describe the upper-left corner of the Component.

See Also

The java.awt.Rectangle class

Example

The following example calculates and writes out the exact coordinates of the lower-right corner of the Component rectangle.

public class MyComponent extends Component



checkImage

ClassName

Component

Purpose

To check the status of construction of an Image.

Syntax

public int checkImage(Image img, ImageObserver observer); public int checkImage(Image img, int width, int height, ImageObserver observer);

Parameters

Image img

The Image object whose status is to be checked.

int width

The scaled size of the image representation being checked.

int height

ImageObserver observer

An ImageObserver object currently being notified of the progress of construction of the Image object.

Description

Checks the status of the construction of an Image object. The second overloaded version of this method checks the construction of a scaled representation of the Image object.

Imports

None.

Returns

A logical ORing of the ImageObserver flags indicating what information about the Image is available. This can include one or more of the following ImageObserver values: WIDTH, HEIGHT, PROPERTIES, SOMEBITS, FRAMEBITS, ALLBITS, ERROR.

See Also

The ImageObserver interface

Example

This example prevents the Component from painting its surface until the Image construction flag ALLBITS has been passed to the ImageObserver watching the image construction process.

public MyComponent extends Canvas
// paint does nothing until image has been
// fully constructed.
public void paint(Graphics g)

createImage

ClassName

Component

Purpose

Creates an in-memory Image with a specified width and height, or from the output of an ImageProducer object.

Syntax

public Image createImage(int x, int y); public Image createImage(ImageProducer producer);

Parameters

int x

The width and height of the resultant Image object.

int y

ImageProducer producer

The ImageProducer object which will provide the data that defines the resultant Image.

Description

Creates an Image object of the specified width and height. This Image is suitable for drawing on for double-buffered screen updating. (See Chapter 1's discussion of double-buffered updating.) The resultant Image will have a compatible ColorModel to the display device associated with this Component object. The second overloaded version of this method creates the Image using data from the ImageProducer.

Imports

java.awt.image.ImageProducer

Returns

An Image object. The Image has not been constructed yet. Use Component.prepareImage() to begin construction of a screen representation of the Image.

See Also

The ImageProducer class

Example

This example creates an in-memory Image, draws on it, and then renders the entire in-memory Image to the Component's display surface.

public void paint(Graphics g)

deliverEvent

ClassName

Component

Purpose

Called within your Java code to deliver an Event to any Component object. The Java system uses a different mechanism to deliver user-generated Events.

Syntax

public void deliverEvent(Event evt);

Parameters

Event evt

The Event object to deliver to this Component.

Description

Delivers an Event object to this Component. The default implementation simply calls postEvent. To send a custom Event to a Component object, use the Component's deliverEvent method. This ensures the Event will automatically be routed to the Component's Container if the Component does not handle the Event. The Java system uses a different mechanism to deliver user-generated Events to a Component. That mechanism involves calling the Component's postEvent method directly using a special callback Thread, without using deliverEvent.

Imports

java.awt.Event

Returns

None.

See Also

The Event class

Example

This example delivers a custom Event object to a Component. The Component has been given a custom handleEvent to handle the custom Event type.

public class MyEvent extends Event


public class MyClass

public deliverEvent(Object arg)

disable

ClassName

Component

Purpose

Disables a Component, which prevents delivery of user-interaction Events to the Component.

Syntax

public void disable();

Parameters

None.

Imports

None.

Description

Disables the component. The Component's peer is also disabled as a result of calling this method. Predefined Components, such as Buttons or Labels, take on a grayed outlook when they are disabled. All Components, either predefined or custom ones, no longer receive user-interaction events once they are disabled.

Returns

None.

Example

See the example for the action method of the Component class.

enable

ClassName

Component

Purpose

Enables or disables the Component.

Syntax

public void enable(); public void enable(boolean fEnabled);

Parameters

boolean fEnabled

If true, the Component is enabled. If false, the Component is disabled.

Imports

None.

Description

Enables the Component. The Component's peer is also enabled as a result of calling this method. The second overloaded version will enable or disable the Component according to the boolean value passed. A disabled Component no longer receives user-generated Events, such as mouse or keyboard Events. Predefined Components, such as Buttons or Labels, take on a grayed out look to denote to the user that they are disabled. Enabled Components receive all user-generated Events.

Returns

None.

Example

See the example for the action method of the Component class.

getBackground

ClassName

Component

Purpose

Gets this Component's current background color.

Syntax

public Color getBackground()

Parameters

None.

Imports

java.awt.Color

Description

Gets the background Color object that is automatically applied to Graphics objects passed to the paint method.

See Also

The Color class; the getForeground, setForeground, and setBackground methods of the Component class

Example

This example code snippet demonstrates the default implementation of the update method of the Component class. The only reference to a Component's background color within the Java API is within update, which uses the background color to erase the Component's entire display surface.

public void update(Graphics g)

getColorModel

ClassName

Component

Purpose

Gets the ColorModel for the display surface attached to this Component object.

Syntax

public ColorModel getColorModel();

Imports

java.awt.ColorModel

Description

Gets the ColorModel for the display surface attached to this Component object. A ColorModel provides methods for converting pixel values to red, green, blue, and alpha color component values. In Java 1.0, this method returns an IndexedColorModel, from which you can get the current palette for the system's desktop.

Returns

A ColorModel that encapsulates methods for converting pixel values to red, green,blue, and alpha color components when displayed on the Component's display surface.

See Also

The ColorModel class

Example

This example displays the number of bits/pixel for the Component's display surface.

public MyApplet extends Applet

public void init()

public void start()

getFont

ClassName

Component

Purpose

Gets the Font object associated with this Component.

Syntax

public Font getFont();

Imports

java.awt.Font

Description

Gets the Font associated with this Component. You associate a Font with a Component using setFont. Note that the Font returned by getFont may still have to be selected by the Component's Graphics object using Graphics.setFont. For the predefined Component classes in the java.awt package, such as Button and List, it is not necessary for the Graphics object to select the Font. But for custom Components, you will have to add a line like this to your paint method to ensure the Component's Font is selected into the Graphics object:

public void paint(Graphics g)

Returns

The Font object currently associated with this Component. If a Font has not been associated with this Component, using setFont will get the parent Container's Font.

See Also

The Font class; the setFont method of the Component class

Example

This example method bolds a Component's Font when called.

public void makeFontBold(Component c)

getFontMetrics

ClassName

Component

Purpose

Gets the FontMetrics for a specified Font as it is rendered on the Component's display surface.

Syntax

public FontMetrics getFontMetrics(Font f);

Parameters

Font f

The Font for which to create the FontMetrics.

Imports

java.awt.Font, java.awt.FontMetrics

Description

Gets the FontMetrics for the passed Font. The FontMetrics are for the display surface associated with this Component. You can use the return value from getFont as the Font parameter to this method, like so

FontMetrics fm = getFontMetrics(getFont());

See Also

The Font class and the FontMetrics class

Example

This example measures the width in pixels of a given string on the Component's display surface using the Component's Font.

public class MyComponent extends Canvas

getForeground

ClassName

Component

Purpose

Gets the Color used for foreground painting on the Component's display surface in the paint method.

Syntax

public Color getForeground();

Parameters

None.

Imports

java.awt.Color

Description

Gets the foreground Color for this Component. The Foreground color is automatically associated with Graphics objects passed to the paint method by the default implementation of update. See the example of the getBackground method to see how this association happens.

Returns

A Color object representing the current color of the Graphics object passed to paint.

See Also

The Color class; the setForeground method of the Component class

Example

This example sets the foreground and background colors of an in-memory Image object's Graphics to be the same as the component's foreground and background colors.

public class MyComponent extends Canvas



getGraphics

ClassName

Component

Purpose

Gets a Graphics object whose display surface is the rectangle of the on-screen desktop controlled by this Component.

Syntax

public Graphics getGraphics();

Parameters

None.

Imports

java.awt.Graphics

Description

Returns a Graphics object for this Component. If the Component has not been added to a Container using Container.add, this method will return null. The foreground Color, background Color, and Font have been selected by the Graphics object.

Returns

A Graphics object attached to the on-screen rectangle controlled by this Component.

See Also

The Graphics class

Example

See the example for the getForeground method of the Component class.

getParent

ClassName

Component

Purpose

Gets the parent Container of this Component.

Syntax

public Container getParent();

Parameters

None.

Imports

java.awt.Container

Description

Gets the Container for this Component object. If the Component is a top-level Frame window, or the Component has not been added to a Container using Container.add, then this method will return null.

Returns

A reference to the Container object which controls this Component. If the Component does not have a parent Container, null will be returned.

See Also

The add method of the Container class

Example

This example places the Component in the lower-right corner of the parent Container's bounding rectangle.

public class MyComponent extends Component



getPeer

ClassName

Component

Purpose

Gets the ComponentPeer associated with this Component object. The ComponentPeer is the proxy through which calls to the native windowing system are made.

Syntax

public ComponentPeer getPeer();

Parameters

None.

Imports

java.awt.peer.ComponentPeer

Description

Gets the Peer object associated with this Component. If this Component has no Peer, null will be returned.

Returns

A Reference to the ComponentPeer attached to this Component. If no ComponentPeer exists, as would be the case if the Component has not been added to a Container using Container.add, then null will be returned.

See Also

The ComponentPeer class

Example

This example implements a virtual Component, which is a Component that does not have a peer. Virtual Components are useful because they inherit all the Component bounding rectangle and Event handling methods. Virtual Components can be used to manage overlapping rectangles of on-screen space, especially because sibling virtual Components will not "clip" each other on the desktop.

public class VirtualComponent extends Canvas



getToolkit

ClassName

Component

Purpose

Gets the Toolkit object, which is the proxy for the native windowing system itself.

Syntax

public Toolkit getToolkit()

Imports

java.awt.Toolkit

Description

Gets the Toolkit object for this Java session. The Toolkit is the proxy for the native windowing system on the local computer. Through the Toolkit you can create ComponentPeers and retrieve various windowing system parameters such as the list of available Fonts.

Returns

A reference to the Toolkit associated with this Component.

See Also

The Toolkit class

Example

The Toolkit can be used to download images or audio clips directly. This example uses a Component's Toolkit to download an Image from within a non-Component object.

public class MyClass

gotFocus

ClassName

Component

Purpose

Event handler method for GOT_FOCUS Events.

Syntax

public boolean gotFocus(Event evt, Object arg);

Parameters

Event evt

The GOT_FOCUS Event sent to this Component.

Object arg

The argument to the GOT_FOCUS Event. This parameter is identical to the arg member of evt.

Imports

java.awt.Event

Description

This notification method is called by the default implementation of handleEvent when a GOT_FOCUS Event is sent to this Component, indicating that this Component has the keyboard focus. The default implementation of the Event handling method simply returns false. Override the default implementation to allow your Component to react when the Component receives the keyboard focus.

Returns

Have your default implementation return true, indicating the GOT_FOCUS Event has been handled. If false is returned, then the Event will be posted to the this Component's parent Container.

Example

This example reports to System.out when the Component receives or loses keyboard focus.

public class MyComponent extends Canvas

public boolean lostFocus(Event evt, Object arg)

handleEvent

ClassName

Component

Purpose

Called to allow the Component a chance to handle user-generated or other Events.

Syntax

public boolean handleEvent(Event evt);

Parameters

Event evt

The Event to be handled by this Component.

Imports

java.awt.Event

Description

This method acts as a central clearing house for all events sent to this Component, or unhandled events sent to subcomponents of this object. The default implementation is a large switch() statement which calls more specific methods, such as keyDown(), mouseMove(), gotFocus(), etc. The return value indicates whether the Event has been handled or should be sent to the parent Container.

Returns

A return value of true indicates the Event has been handled. False indicates it has not, and the Event will be sent to the parent Container.

See Also

All of the Event handle methods of the Component class; the Event class

Example

In this example, it is known that the defined class of Components never handles any Events. The default implementation of handleEvent will still run through its long switch statement and attempt to find a handler for the Event. This class is optimized to stop the Java system from performing that unnecessary handleEvent code.

public class MyNoHandlerComponent extends Component



hide

ClassName

Component

Purpose

Makes the Component invisible or "hidden."

Syntax

public void hide();

Parameters

None.

Imports

None.

Description

Hides the Component. Hidden components are not drawn, nor do they take up space on the display surface.

Returns

None.

See Also

The show method of the Component class

Example

This example Panel uses a Label to display a countdown. When the countdown reaches 0, the Label is hidden. Note that this example does not halt its background Thread in its stop() method implementation for purposes of readablility.

public class MyCountDownApplet extends Applet implements
Runnable

public void start()

public void run() catch (Exception e)
_nCount--;
_label.setText(new String(""+_nCount));
}

_label.hide();
}

imageUpdate

ClassName

Component

Purpose

This is the only method of the ImageObserver interface. The default implementation repaints the entire Component whenever any progress is made in the construction of an image.

Syntax

public boolean imageUpdate(Image img, int flags, int x, int y, int width, int height);

Parameters

Image img

The Image object to check. If progress on a screen representation of this Image has been made, then the Component will be repainted asynchronously.

int flags

The ImageObserver flags indicating the progress of construction of a screen representation of the Image object. These ImageObserver flags are ORed together.

int x

Indicates the rectangle of the Image for which the flags parameter is valid.

int y

int width

int height

Imports

None.

Description

Causes an asynchonous repainting of the Component if construction of the Image's representation has made progress. The same flags parameter as is returned by checkImage method is passed. Because this method is implemented in the Component class, any Component object may act as an ImageObserver.

Returns

Returns true if further notification of image construction should continue. False causes further notification to be terminated.

See Also

The imageUpdate method of the ImageObserver interface

Example

This example prevents the Component from repainting unless the ALLBIT flag is passed as part of the flags parameter.

public class MyComponent extends Canvas



inside

ClassName

Component

Purpose

Checks to see if a particular point lies within this Component's bounding rectangle.

Syntax

public boolean inside(int x, int y);

Parameters

int x

The coordinates of the point to check.

int y

Imports

None.

Description

Checks whether a particular point lies inside or outside the Component's bounding rectangle. The point to check is specified relative to the parent Container's origin (generally its upper-left corner).

Returns

True is returned if the point lies within this Component's bounding rectangle. Otherwise false is returned.

Example

This example method moves the Component's origin to a point if that point does not lie within the Component's bounding rectangle.

public class MyComponent extends Canvas



invalidate

ClassName

Component

Purpose

Marks the Component as invalid. Calls to Component.validate are ignored unless the Component has been marked as invalid.

Syntax

public void invalidate();

Parameters

None.

Imports

None.

Description

Sets an internal boolean variable, indicating the Component must be validated. Use validate to re-validate the Component Container components. In conjunction with a LayoutManager object, use the invalidate/validate methods to layout subcomponents. By default implementation, Component objects do not react to being tagged as invalid.

Returns

None.

See Also

The Container class and the LayoutManager interface

isEnabled

ClassName

Component

Purpose

Tells whether or not the Component is enabled.

Syntax

public boolean isEnabled();

Parameters

None.

Imports

None.

Description

Checks to see if the Component is currently enabled. When created, a Component is enabled. The disable method is used to disable a Component.

Returns

True if the Component is currently enabled. False if it is not.

Example

The paint method of this Component draws differently if the Component is disabled.

public class MyComponent extends Canvas else
}



isShowing

ClassName

Component

Purpose

Tells whether or not any part of the Component is currently showing on the desktop.

Syntax

public boolean isShowing();

Parameters

None.

Imports

None.

Description

Checks to see whether the Component object is currently showing on the display screen. The Component is not showing if it is currently hidden. It is not showing if its bounding rectangle has a 0 dimension along either axis. It is not showing if the intersection of its bounding rectangle with its parent's bounding rectangle has a 0 dimension along either axis. That is, Component positioned outside the bounds of its parent Container's bounding rectangle.

Returns

True is returned by this method for all Components which currently have some rectangle of screen real estate. False is returned otherwise.

See Also

The hide and show methods of the Component class

Example

This Component is optimized by immediately returning from its paint implementation if it is not currently showing.

public class MyComponent extends Canvas



isValid

ClassName

Component

Purpose

Tells whether or not this Component is currently flagged as "nvlaid.

Syntax

public boolean isValid();

Parameters

None.

Imports

None.

Description

Checks to see whether the Component object is currently valid. Each Component has an internal invalid flag. The invalidate method is used to set this flag, and the validate method is used to clear the flag. The default implementation of validate actually does nothing except clear the flag. The Container class, however, uses the invalid flag and the validate method as an indication of when it should rearrange its child Components with the help of its LayoutManager.

Returns

Valid Components return true from calls to this method. Invalid ones return false.

See Also

The invalidate and validate methods of the Component class

isVisible

ClassName

Component

Purpose

Tells whether or not the Component is currently visible.

Syntax

public boolean isVisible();

Parameters

None.

Imports

None.

Description

Checks to see whether the Component object is currently hidden. To hide a Component object, call its hide method. The show method will alternatively make the object unhidden. Components, when created, are not hidden by default.

Returns

If the Component is currently hidden, false is returned. If it is not hidden, true is returned.

Example

This Component object suspends its background processing Thread while it is hidden. This is accomplished by overriding its show method and by implementing the Runnable interface.

public class MyComponent extends Canvas implements
Runnable

public synchronized void quit()


public synchronized void show()

public synchronized void run()

// do one iteration of background processing
}
}



keyDown

ClassName

Component

Purpose

Event handler for KEY_PRESS Events.

Syntax

public boolean keyDown(Event evt, int key);

Parameters

Event evt

The KEY_PRESS or KEY_ACTION Event which was sent to this Component.

int key

The key pressed. Note that the key is also stored in the key member of evt.

Imports

java.awt.Event

Description

This method is called by the the default implementation of handleEvent whenever a KEY_PRESS or KEY_ACTION Event is sent to the Component. The passed parameters indicate the code for the key pressed. A custom implementation should return true if the event is handled by the Component and should not be sent on to the Component's Container.

Returns

The default implementation of this method simply returns false, indicating the Event should be passed on to the parent Container's handleEvent method.

See Also

The Event class; the handleEvent method of the Component class

Example

This example Component changes its background color whenever the spacebar is pressed. The Component is not repainted until a KEY_RELEASE Event is sent to the Component.

public class MyComponent extends Canvas

public boolean keyDown(Event evt, int key)

return false;
}

public boolean keyUp(Event evt, int key)

return false;
}

keyUp

ClassName

Component

Purpose

Event handler for KEY_RELEASE Events.

Syntax

public boolean keyUp(Event evt, int key);

Parameters

Event evt

The KEY_RELEASE or KEY_ACTION_RELEASE Event which was sent to this Component.

int key

The key pressed. Note that the key is also stored in the key member of evt.

Imports

None.

Description

This method is called by the the default implementation of handleEvent whenever a KEY_RELEASE or KEY_ACTION_RELEASE Event is sent to the Component. The passed parameters indicate the code for the key pressed. A custom implementation should return true if the event is handled by the Component and should not be sent on to the Component's Container.

Returns

The default implementation of this method simply returns false, indicating the Event should be passed on to the parent Container's handleEvent method.

See Also

The Event class; the handleEvent method of the Component class

Example

See the example for the keyDown method of the Component class.

layout

ClassName

Component

Purpose

Called by the default implementation of validate if the Component is currently invalid. The default implementation of Component.layout does nothing.

Syntax

public void layout();

Parameters

None.

Imports

None.

Description

Called when invalid Component objects are being validated as part of validate. This method is primarily used to layout child Components in Container objects. The default implementation of Component.layout does nothing. The Container class implementation of layout relies on a LayoutManager object to handle the laying out of child Components.

Returns

None.

See Also

The validate and invalidate methods of the Component class

list

ClassName

Component

Purpose

To display the internal state of the Component to a PrintStream object.

Syntax

public void list();

public void list(PrintStream out);

public void print(PrintStream out, int indent);

Parameters

PrintStream out

The stream to write a textual description of the state of this Component to.

int indent

The number of space characters (ASCII char 32) to prepend to each line of text written to out.

Imports

java.io.PrintStream

Description

Outputs a textual description of the internal state of the Component to a PrintStream. This can be useful for debugging purposes. The first overloaded version of this method writes the listing to System.out, with an indentation of 0. A call to list() (without parameters) is equivalent to System.out.println(this).

See Also

The PrintStream class; the toString method of the Component class

Example

This example Container class method displays the Container's entire subtree of Components by tracing its hierarchy depth-first, indicating depth by indentation on the PrintStream. Output is written to System.out.

public class MyContainer extends Panel

public void displayChildren(Container target, int indent)
}

locate

ClassName

Component

Purpose

Returns a reference to this Component if the passed point lies within this Component's bounding rectangle.

Syntax

public Component layout(int x, int y);

Parameters

int x

int y

These two parameters describe a point, relative to this Component's origin, to test.

Imports

None.

Description

A hit-test method which checks to see which Component, or subcomponent, contains the point described by the passed x and y parameters. The Container class uses this method to determine which of its child Component's contains a particular point.

Returns

The Component, or subcomponent, that contains the point (x,y). If the point lies outside the bounds of this Component, null is returned. Container.locate() re-implements this method to test all subcomponents.

See Also

The Container class

location

ClassName

Component

Purpose

Gets the location of this Component's origin.

Syntax

public Point location();

Parameters

None.

Imports

None.

Description

Gets the coordinates of the upper-left corner of this Component. The returned Point is relative to the parent Container's origin.

Returns

The coordinates of the upper-left corner of this Component.

See Also

The Point class

lostFocus

ClassName

Component

Purpose

Event handler for LOST_FOCUS Events.

Syntax

public boolean lostFocus(Event evt, Object arg);

Parameters

Event evt

The LOST_FOCUS Event sent to this Component.

Object arg

The argument to the LOST_FOCUS Event. This parameter is identical to the arg member of evt.

Imports

java.awt.Event

Description

This notification method is called by the default implementation of handleEvent when a LOST_FOCUS Event is sent to this Component, indicating this Component no longer has the keyboard focus.

Returns

A return value of true indicates the LOST_FOCUS Event is handled by this Component. Returning false causes the event to automatically be sent to this Component's parent Container object.

See Also

The handleEvent method of the Component class

Example

See the example for the gotFocus method of the Component class.

minimumSize

ClassName

Component

Purpose

Allows a Component to tell its parent Container the minimum bounding rectangle it requires.

Syntax

public Dimension minimumSize();

Imports

None.

Description

Returns the minimum sized rectangle of display surface required for this Component to display itself. When the Component's Container lays out its subcomponents, this method is called to establish a minimum amount of screen real estate needed by the Component.

Returns

The returned Dimension object should indicate the minimum required width and height needed for this Component to display itself. The default implementation of Component.minimumSize() returns the minimum size required as indicated by the Component's peer. If no peer exists, the current size of the Component is returned.

See Also

The preferredSize method of the Component class; the LayoutManager interface; the Dimension class

Example

This example custom Component reports that it requires at least a 10 x 10 bounding rectangle, but would prefer a bounding rectangle large enough to display an initializer String.

public class MyComponent extends Canvas

public Dimension minimumSize()

public Dimension preferredSize()



mouseDown

ClassName

Component

Purpose

Event handler for MOUSE_DOWN Events.

Syntax

public boolean mouseDown(Event evt, int x, int y);

Parameters

Event evt

The MOUSE_DOWN Event sent to this Component.

int x

int y

The on-screen coordinates where the mouse was clicked. The coordinates are expressed relative to the origin of this Component object. These two parameters are identical to the x and y members of evt.

Imports

java.awt.Event

Description

This notification method is called by the default implementation of handleEvent when a MOUSE_DOWN Event is sent to this Component, indicating the user has clicked the mouse inside this Component.

Returns

A return value of true indicates the MOUSE_DOWN Event is handled by this Component. Returning false causes the event to automatically be sent to this Component's parent Container object.

See Also

The handleEvent, mouseUp, and mouseDrag methods of the Component class

Example

This simple example custom Component prints the coordinates of the mouse while the mouse button is down.

public class MyComponent extends Component {
boolean _bMouseIsDown = false;
Point _ptMouseCoords = null;

public MyComponent()

public void paint(Graphics g)

public boolean mouseDown(Event evt, int x, int y)

public boolean mouseDrag(Event evt, int x, int y)

public boolean mouseUp(Event evt, int x, int y)

mouseDrag

ClassName

Component

Purpose

Event handler for MOUSE_DRAG Events.

Syntax

public boolean mouseDrag(Event evt, int x, int y);

Parameters

Event evt

The MOUSE_DRAG Event sent to this Component.

int x

int y

The coordinates where the mouse was dragged to. These parameters are identical to the x and y members of evt.

Imports

java.awt.Event

Description

This notification method is called by the default implementation of handleEvent when a MOUSE_DRAG Event is sent to this Component, indicating that the mouse has been moved while the mouse button is held down.

Returns

A return value of true indicates the MOUSE_DRAG Event is handled by this Component. Returning false causes the event to automatically be sent to this Component's parent Container object.

See Also

The handleEvent, mouseDown, mouseUp, and mouseMove methods of the Component class; the Event class

Example

See the example for the mouseDown method of the Component class.

mouseEnter

ClassName

Component

Purpose

Event handler for MOUSE_ENTER Events.

Syntax

public boolean mouseEnter(Event evt, int x, int y);

Parameters

Event evt

The MOUSE_ENTER Event sent to this Component.

int x

int y

The argument to the GOT_FOCUS Event. This parameter is identical to the arg member of evt.

Imports

java.awt.Event

Description

This notification method is called by the default implementation of handleEvent when a MOUSE_ENTER Event is sent to this Component, indicating that the mouse cursor has moved onto this Component's display rectangle. A Component will only receive a single MOUSE_ENTER Event before a subsequent MOUSE_EXIT Event is sent. That is, each call to mouseEnter is matched by exactly one subsequent call to mouseExit.

Returns

A return value of true indicates the MOUSE_ENTER Event is handled by this Component. Returning false causes the event to automatically be sent to this Component's parent Container object.

See Also

The handleEvent and mouseExit methods of the Component class; the Event class

Example

This example component uses the mouseEnter and mouseExit Event handlers to detect when the mouse cursor is over it. When the mouse is over it, the Component exchanges its background and foreground colors compared to when the mouse is not over it.

public class MyComponent extends Canvas

public boolean mouseExit(Event evt, int x, int y)



mouseExit

ClassName

Component

Purpose

Event handle for MOUSE_EXIT Events.

Syntax

public boolean mouseExit(Event evt, int x, int y);

Parameters

Event evt

The MOUSE_EXIT Event sent to this Component.

int x

int y

The coordinates of the first point outside the Component's bounds that the mouse is moved to after being inside the bounds. Coordinates are relative to the upper-left corner of the Component.

Imports

java.awt.Event

Description

This notification method is called by the default implementation of handleEvent when a MOUSE_EXIT Event is sent to this Component, indicating that the mouse cursor has moved out of this Component's display rectangle. A Component will only receive a single MOUSE_ENTER event before a subsequent MOUSE_EXIT event is sent. That is, each single call to mouseEnter is matched by a single subsequent call to mouseExit. MOUSE_EXIT Events are still sent to a Component even if the user is dragging the mouse (that is, moving the mouse while the mouse button is held down).

Returns

A return value of true indicates the MOUSE_EXIT Event is handled by this Component. Returning false causes the event to automatically be sent to this Component's parent Container object.

See Also

The Event class; the handleEvent and mouseEnter methods of the Component class

Example

See the example for the mouseEnter method of the Component class.

The MouseMove method is described at the end of this chapter on page 135.

mouseUp

ClassName

Component

Purpose

Event handler for MOUSE_UP Events.

Syntax

public boolean mouseUp(Event evt, int x, int y);

Parameters

Event evt

The MOUSE_UP Event sent to this Component.

int x

The coordinates of the mouse cursor when the mouse button was released.

int y

These parameters are identical to the x and y members of evt.

Imports

java.awt.Event

Description

This notification method is called by the default implementation of handleEvent when a MOUSE_UP Event is sent to this Component, indicating the user has let go of the mouse button.

Returns

A return value of true indicates the MOUSE_UP Event is handled by this Component. Returning false causes the event to automatically be sent to this Component's parent Container object.

See Also

The Event class; the handleEvent, mouseDown, mouseMove, and mouseDrag methods of the Component class

Example

See the example for the mouseDown method of the Component class.

move

ClassName

Component

Purpose

Moves the entire Component within its parent Container.

Syntax

public void move(int x, int y);

Parameters

int x

int y

The new coordinate of the upper-left corner of the Component object. The coordinates are expressed relative to the upper-left corner of the parent Container.

Imports

None.

Description

Relocates the Component relative to the upper-left corner of the parent Container. The dimensions of the moved Component are preserved.

Returns

None.

See Also

The location method of the Component class

Example

See the example for the inside method of the Component class.

nextFocus

ClassName

Component

Purpose

Moves the keyboard focus to the next Component within the same Container.

Syntax

public void nextFocus();

Parameters

None.

Imports

None.

Description

Calling this method, moves the keyboard focus to the next Component within the same Container that is eligible to receive keyboard focus. Calling this method for a Component which does not currently have keyboard focus is a no-op. Use of the Component.requestFocus method instead of nextFocus is strongly encouraged. See the example of the requestFocus method.

Returns

None.

See Also

The requestFocus, gotFocus, and lostFocus methods of the Component class

paint

ClassName

Component

Purpose

Called whenever the Java system determines the Component must repaint its surface.

Syntax

public void paint(Graphics g);

Parameters

Graphics g

A Graphics object which has been attached to the display surface for the Component, and whose clipping rectangle has been set to whole or part of the Component's bounding rectangle.

Imports

java.awt.Graphics

Description

This method is called whenever the Component should render itself on the display surface. The Graphics object passed to this method is attached to the display surface, and is clipped to the Component's bounding rectangle. Custom Component objects should override this method. The paint method can be called by Java at any time, such as when your Java application is covered up by another application running at the same time. When the other application is removed from on top of your Java application, a paint call will be issued for all visible Components.
There are no guarantees on the internal state of the Graphics object, except that the clipping rectangle will be set to a rectangle equal to or contained by the Component's bounding rectangle. If you do not override the Component's default update method, then the foreground and background colors are also guaranteed to be selected in the Graphics object. In general, it is always safe to select the foreground Color, background Color, Font, and other special drawing features into the Graphics object, just to be sure that the Graphics' internal state is as it is expected to be. Use the repaint method to force an asynchronous paint call to be issued for the Component.

Returns

None.

See Also

The Graphics class; the repaint method of the Component class

Example

This example Component re-implements both the paint and repaint methods. The re-implementation of the repaint method guarantees that the foreground Color and Font are selected into paint's Graphics parameter, and the Component's surface has not been erased at all. Re-implementing the update method, to not erase a Component's surface, is the technique usually used to avoid flicker in graphics-intensive applications.

public class MyComponent extends Canvas

public void paint(Graphics g)



paintAll

ClassName

Component

Purpose

Paints the Component after calling validate.

Syntax

public void paintAll(Graphics g);

Parameters

Graphics g

A Graphics object, which has been attached to the display surface for the Component, and whose clipping rectangle has been set to whole or part of the Component's bounding rectangle.

Imports

java.awt.Graphics

Description

This method paints the Component after calling validate. Note that this method is usually used to force a Container to repaint itself and all its child Components.

Returns

None.

See Also

The Graphics class; the validate method of the Component class

postEvent

ClassName

Component

Purpose

Routes an Event to its handler method.

Syntax

public boolean postEvent(Event evt);

Parameters

Event evt

The Event object being sent to this Component.

Imports

java.awt.Event

Description

This method handles delivering an Event to either a Component's peer, the Component's handleEvent method, or to the Component's parent Container postEvent method (in that order). Note that the Java system calls a Component's postEvent method to deliver all Events to the Component. When delivering your own Events to a Component, use the deliverEvent method. The recursive design of the postEvent method is used to pass unhandled Events up from Component to parent Container to parent Container until some Event handler method returns true. deliverEvent simple calls postEvent. postEvent will actually allow the peer's handleEvent method to have a first shot at the Event. If the peer's handleEvent returns true, indicating the Event has been handled, then the Component's own handleEvent implementation is never called. This is the reason that, say, Scrollbar objects (which are directly derived from Component) cannot handle a MOUSE_DOWN or MOUSE_UP Event. Instead, the Scrollbar's peer handles these types of Events and changes them into SCROLLBAR_* Events to be handled by the Scrollbar. If neither the peer's nor the Component's handleEvent method handles the Event, the parent Container's postEvent method is passed the Event.

Returns

A return value of true indicates the Event has been handled by either the peer, this Component itself, or the Component's parent Container.

See Also

The Event class; the deliverEvent and handleEvent methods in the Component class

Example

Under some circumstances, you may actually want the Component's parent Container to take the first shot at handling the Component's Events. In this example, postEvent is re-implemented to allow the parent Container first shot at all Events.

public class MyComponent extends Canvas



preferredSize

ClassName

Component

Purpose

Allows the Component to tell its parent Container its preferred amount of on-screen real estate.

Syntax

public Dimension preferredSize();

Parameters

None.

Imports

java.awt.Dimension

Description

Returns the preferred size of the rectangle of display surface for this Component to display itself. When the Component's Container lays out its subcomponents, this method is called to establish a preferred amount of screen real estate for the Component. Re-implement this method to request a particular preferred size for your custom Component.

Returns

The returned Dimension object should indicate the preferred width and height for this Component to display itself. The default implementation of preferredSize returns the preferred size as indicated by the Component's peer. If no peer exists, the current size of the Component is returned.

See Also

The Dimension class; the minimumSize method of the Component class

Example

See the example for the minimumSize method of the Component class.

prepareImage

ClassName

Component

Purpose

Kick-starts the Image construction process.

Syntax

public boolean prepareImage(Image img, ImageObserver observer); public boolean prepareImage(Image img, int width, int height, ImageObserver observer);

Parameters

Image img

The Image object to create a screen representation of.

int width

int height

The scaled size of the Image's representation.

ImageObserver observer

The ImageObserver object that receives notification of the asynchronous progress of the construction of the Image's representation.

Imports

java.awt.Image, java.awt.image.ImageObserver

Description

Starts construction of a screen representation of an Image object. The second overloaded version begins construction of a scaled version of the Image. An Image must be constructed before it can be displayed on a Component's surface. Note, that when you use Graphics.drawImage with a reference to an unconstructed Image object, the Image's construction process is automatically started for you. The prepareImage method allows you to start this process before the Image is displayed on any surface.

Returns

True is returned if the representation of the Image object is complete. Otherwise, false is returned and the Image construction process is started.

See Also

The Image class; the ImageObserver interface; the checkImage and updateImage methods of the Component class

Example

See the example for the checkImage method of the Component class.

print

ClassName

Component

Purpose

To render the Component to a printer device.

Syntax

public void print(Graphics g);

Parameters

Graphics g

A Graphics object that has been attached to a printer device, and whose clipping rectangle has been set to whole or part of the Component's bounding rectangle.

Imports

java.awt.Graphics

Description

This method is called whenever the Component should render itself on a printer device. The Graphics object passed to this method has been attached to a printing device, and it is clipped to the Component's bounding rectangle. The default implementation simply calls paint, using the same Graphics object. Override this method if your custom Component is to be displayed differently when printed compared to on a display device. There are no guarantees on the internal state of the Graphics object, except that the clipping rectangle will be set to a rectangle equal to or contained by the Component's bounding rectangle. It is a good idea to select the foreground Color, background Color, Font, and other special drawing features into the Graphics object to be sure the Graphics' internal state is as it is expected to be. Note that the print method is essentially the same thing as the paint method. The print method is provided for those instances when you need to know that your Component is being rendered to a printer.

Returns

None.

See Also

The Graphics class; the paint method of the Component class

Example

See the example for the paint method. The paint method and the print method are essentially the same thing.

printAll

ClassName

Component

Purpose

Prints the Component after calling validate.

Syntax

public void printAll(Graphics g);

Parameters

Graphics g

A Graphics object that has been attached to a printer device, and whose clipping rectangle has been set to whole or part of the Component's bounding rectangle.

Imports

java.awt.Graphics

Description

This method prints the Component after calling validate. Note that this method is usually used to force a Container to repaint itself and all its child Components.

Returns

None.

See Also

The Graphics class; the validate method of the Component class

repaint

ClassName

Component

Purpose

Requests an asynchronous repainting of the Component.

Syntax

public void repaint();

public void repaint(long lMillisecs);

public void repaint(int x, int y, int width, int height);

public void repaint(long lMillisecs, int x, int y, int width. int height);

Parameters

long lMillisecs

Maximum number of milliseconds to wait before the Component's update method is called.

int x

int y

int width

int height

These four parameters define a rectangle of area that should be repainted.

Description

You call this method at any time to force an asynchronous repainting of the Component. The Java system schedules a repainting of the Component to be completed by a different Thread at a later time. The second and fourth overloaded version of this method specify a maximum amount of time for the system to wait to schedule a repainting of the Component. The third and fourth overloaded versions allow you to specify a subset of the Component's bounding rectangle to repaint. Unless you use one of the overloaded versions of this method, which allows you to specify a maximum time limit, there is no guarantee on the amount of time before a repaint will be performed. If multiple repaint calls are made in quick succession, they will be combined into a single repainting operation. Repainting is achieved by an asynchronous call to update by the Java system.

See Also

The update and paint methods of the Component class

Example

See the example under the mouseDown method of the Component class.

requestFocus

ClassName

Component

Purpose

If possible, gives the input focus to this Component.

Syntax

public void requestFocus();

Parameters

None.

Imports

None.

Description

Makes a request for the keyboard focus to be switched to this Component. This Component will be notified by a call to gotFocus when the keyboard focus has been switched. Note that disabled Components can not gain the keyboard focus.

Returns

None.

See Also

The nextFocus, gotFocus, and lostFocus methods of the Component class

Example

This example Container has two child Components, a text field, and a checkbox. When the checkbox becomes checked, then the text field is enabled and keyboard focus is given to it. When the checkbox becomes unchecked, then the text field becomes disabled and keyboard focus is given to the checkbox.

public class FocusContainerExample extends Panel

// An action Event is given to the parent Container
// when the checkbox is checked or unchecked.
action(Event evt, Object arg) else
}

reshape

ClassName

Component

Purpose

Changes the origin and dimensions of the Component object in one method call.

Syntax

public void reshape(int x, int y, int width, int height);

Parameters

int x

int y

int width

int height

These four parameters describe a new bounding rectangle for the Component. The x and y coordinates are relative to the upper-left corner of the parent Container.

Imports

None.

Description

Modifies the bounding rectangle of the Component. The move and resize methods are actually wrappers around the reshape method. To detect when your (non-Frame) Component object is being resized or moved, re-implement the reshape method to set some detection flag before calling the base implementation, as demonstrated in the example below.

Returns

None.

See Also

The move and resize methods of the Component class

Example

This example Container re-implements reshape so that it can detect when it is being sized below a particular width and change its LayoutManager accordingly.

public class MyContainer extends Panel



resize

ClassName

Component

Purpose

Changes the dimensions of this Component.

Syntax

public void resize(int width, int height); public void resize(Dimension dim);

Parameters

int width

int height

The new width and height of the Component.

Dimension dim

The width and height members of this object describe the new width and height of the Component.

Imports

java.awt.Dimension

Description

Modifies the width and height of the bounding rectangle for this Component to be width pixels in width and height pixels in height. Note that the resize method is just a wrapper around the reshape method.

See Also

The Dimension class; the move and reshape methods of the Component class

Example

This example Component resizes itself to always be large enough to display a particular string.

public class MyComponent extends Canvas



setBackground

ClassName

Component

Purpose

Sets the background color used to erase the Component when it is rendered.

Syntax

public void setBackground(Color c);

Parameters

Color c

The background color to use when rendering the Component in the future.

Imports

None.

Description

Sets the background Color to use when painting or printing this Component on a drawing surface. The update method uses a Component's background Color to erase the Component's bounding rectangle on the desktop before calling paint. If update is re-implemented so that it does not erase the Component, then the background Color is never used and might as well never be set.

Returns

None.

See Also

The Color class; the update method of the Component class

Example

See the example under the mouseEnter method of the Component class.

setForeground

ClassName

Component

Purpose

Sets the foreground color used for rendering in the paint method.

Syntax

public void setForeground(Color c);

Parameters

Color c

The background color to use when rendering the Component in the future.

Imports

java.awt.Color

Description

Sets the foreground Color to use when painting or printing this Component on a drawing surface. update modifies the foreground Color used by the passed Graphics to be c before passing the Graphics on to paint. Therefore, Components that override the default implementation of update must set the foreground color explicitly in paint or update.

Returns

None.

See Also

The Color class; the getForeground, update, and paint methods in the Component class

Example

See the example under the mouseEnter method of the Component class.

show

ClassName

Component

Purpose

Makes the Component either hidden or unhidden, according to the parameters passed.

Syntax

public void show(); public void show(boolean fShow);

Parameters

boolean fShow

True if the Component should be unhidden. False if it should be hidden.

Imports

None.

Description

Shows the Component. Hidden components are not drawn, nor do they take up space on the display surface. The second overloaded version allows you to hide or show the Component based on the value of fShow.

Returns

None.

See Also

The hide method of the Component class

Example

This example Component gets hidden whenever it is disabled.

public class MyComponent extends Canvas

public void enable()


size

ClassName

Component

Purpose

Gets the dimensions of this Component object.

Syntax

public Dimension size();

Parameters

None.

Imports

None.

Description

Gets the width and height of this Component.

Returns

A Dimension object whose width and height public member variables contain the Component width and height in pixels, respectively.

See Also

The bounds method of the Component class

Example

See the examples under the methods resize, getParent, and getForeground of the Component class.

toString

ClassName

Component

Purpose

Creates a descriptive string detailing the internal state of the Component.

Syntax

public String toString();

Parameters

None.

Imports

None.

Description

Gets a String containing a textual description of this Component object. The resultant String is a concatenation of the object's class, and certain information about the Component's internal state such as whether or not it is enabled or hidden.

Returns

A textual description in a String object.

See Also

The toString method of the Object class

update

ClassName

Component

Purpose

Called by the Java system whenever the Component should repaint itself.

Syntax

public void update(Graphics g);

Parameters

Graphics g

A Graphics object attached to the Component's display device, with a clipping rectangle equal to or a subset of the Component's bounding rectangle.

Imports

java.awt.Graphics

Description

Called automatically by the system when it is time to render the Component on a drawing surface. Calls to repaint cause an asynchronous call to update to be made by a separate Thread. The default implementation of update passes the Graphics object on to paint after erasing the entire drawing surface with the background color and selecting the foreground color into the Graphics object. Many Components, which require a lot of graphical updating, override update so that the entire drawing surface will not be erased. This prevents the Component from appearing to flicker with each graphical update.

See Also

The Graphics class; the paint method of the Component class

Example

See the example for the paint method of the Component class.

validate

ClassName

Component

Purpose

To clear the invalid flag of this Component.

Syntax

public void validate();

Parameters

None.

Imports

None.

Description

Forces the Component to validate itself. When created, Components are marked as valid. Subsequent calls to the invalidate method mark the Component as invalid. Invalid Components validate themselves by calling the layout method before clearing their internal invalid flag. The default implementation of layout does nothing. The invalidate/validate methods are used mostly by Containers to force subcomponents to be laid out by a LayoutManager object.

Returns

None.

See Also

The invalidate and layout methods of the Component class; the layout method of the Container class

The Component Project: A Hotspot Custom Component

The Component Project illustrates the construction of a simple custom Component class: the Hotspot class. The Hotspot class is a Component that has two Images associated with it: an ActiveImage and an InactiveImage. The behavior of a Hotspot object is to display the ActiveImage when the mouse cursor is moved on to the Hotspot. When the mouse is not over the Hotspot, the InactiveImage is displayed. This is a generic custom Component suitable for use in your own Java applications or applets.

This project demonstates several key concepts of Components and custom Components:

.  Rendering a custom Component by overriding the Component.paint() method.

.  Event handling by implementing Hotspot.mouseEnter() and Hotspot.mouseExit() to make the Hotspot react to user interaction. The Hotspot's Container-the HotsportApplet in this project-can also handle mouse click Events originally delivered to the Hotspot objects.

.  Image preparation. The Hotspot implements the ImageObserver interface so that it can be notified of the progress of construction of the on-screen representation of the ActiveImage and the InactiveImage.

Figures 2-6 and 2-7 show the active and inactive images used for one of the Hotspot components in this project.


Figure 2-6  Active image for the first Hotspot component of the Hotspot project


Figure 2-7  Inactive image for the second Hotspot component of the Hotspot project

Assembling the Project

1.  Create a file called Hotspot.java using a text editor. This file holds the implementation of the Hotspot custom Component class. Begin by declaring the class and its member variables:

import java.awt.*;
import java.awt.image.*;

public class Hotspot extends Canvas implements ImageObserver

3.  When the mouse moves over the Hotspot, the active image should be displayed. This is performed by the mouseEnter event handler, which is called automatically whenever a MOUSE_ENTER Event is delivered to the Component. Similarly, when the mouse is no longer over the Component, then the inactive image is displayed. This is performed by the mouseExit Event handler, which is called whenever a MOUSE_EXIT Event is delivered to the Component.

public boolean mouseEnter(Event evt, int x, int y)

public boolean mouseExit(Event evt, int x, int y)

4.  To reduce flicker, prevent default implementation of update from erasing the Component before calling paint.

public void update(Graphics g)

5.  Painting the Hotspot Component merely involves displaying the Image referred to by _imgCurrent.

public void paint(Graphics g)

6.  Create a second file named HotspotApplet.java in the same directory. This file holds a sample Applet which displays two Hotspots. The following code initializes and displays two Hotspot Components on the surface of an Applet.

import java.applet.Applet;
import java.awt.*;
import java.net.URL;

public class HotspotApplet extends Applet catch(Exception e)

// Create the Image objects from these URLs.
Image imgActive1 = getImage(urlActive1);
Image imgActive2 = getImage(urlActive2);
Image imgInactive1 = getImage(urlInactive1);
Image imgInactive2 = getImage(urlInactive2);

// Create the two Hotspot objects and add them
// as Components of this Applet Container. Resize
// the hotspots to the size the images
// are expected to be.
_hotspot1 = new Hotspot(imgActive1,
imgInactive1);
_hotspot2 = new Hotspot(imgActive2,
imgInactive2);

add( '1', _hotspot1 );
add( '2', _hotspot2 );

_hotspot1.resize(204, 140);
_hotspot2.resize(204, 140);

return;
}

// Re-implementation of the mouseDown() event handling
// method allows us to react to the user clicking on
// one of the Hotspot Components.
public boolean mouseDown(Event evt, int x, int y)

if(evt.target == _hotspot2)

return false; // Event was not handled.
}

7.  Create a file named Hotspot.html. This is an HTML file with an embedded HotspotApplet in it. Copy the following text to your Hotspot.html file:

<HTML>
<HEAD>
<TITLE>HotspotApplet Sample Project</TITLE>
</HEAD>

<HTML>
<HEAD>
<TITLE>HotspotApplet Sample Project</TITLE>
</HEAD>

<BODY>
<APPLET CODE='HotspotApplet.class' WIDTH=450 HEIGHT=200>
<PARAM NAME='ActiveImageURL1' VALUE='active1.gif'>
<PARAM NAME='ActiveImageURL2' VALUE='active2.gif'>
<PARAM NAME='InactiveImageURL1' VALUE='inactive1.gif'>
<PARAM NAME='InactiveImageURL2' VALUE='inactive2.gif'>
</APPLET>
</BODY>
</HTML>

8.  Compile HotspotApplet.java using the JDK's javac compiler. From the directory where your .JAVA and .HTML files are located, run this command:

> javac HotspotApplet.java

9.  Create four .GIF files to act as your Active and Inactive images. The images displayed above can be used. They are located on the Java API SuperBible CD under the directory FOOBLAHWHATEVER. Copy these four files to the same directory your .JAVA and .HTML files are in. Make sure the names of these four files are "active1.gif", "active2.gif", "inactive1.gif" and "inactive2.gif", respectively.

10.  Load the HotspotApplet into the JDK's AppletViewer. From the same directory where your project files are, type this command:

> appletviewer Hotspot.html

How It Works

The Hotspot class maintains an internal reference to two Image objects. The Hotspot._imgActive member variable is a reference to an Image to display when the mouse cursor is over the Hotspot component. The Hotspot._imgInactive member variable is a reference to an Image to display when the mouse cursor is not over the Hotspot. The Hotspot._imgCurrent member variable is a reference to the Image to display: either the active or the inactive Image.

The Hotspot constructor requires references to the active and inactive Image as parameters. Part of object construction includes kick-starting construction of on-screen representation of both these Images using Component.prepareImage(). Always, before an Image can be drawn on a display device, the Image must be prepared by the Java system for rendering on the display device. The Hotspot object uses its inherited implementation of the ImageObserver interface, which is implemented by the Component class. The Component class' implementation of this interface causes the Component to transparently schedule a full repainting of the Hotspot component once the Image has been prepared.

The value of _imgCurrent changes whenever the mouse cursor either enters or exits the bounding rectangle of the Hotspot. Overriding implementations of the mouseEnter and mouseExit Event handling methods are used to detect the position of the mouse cursor. Through the Event delivery methods, the Java system calls a Component's mouseEnter() method exactly once, when the mouse is moved from outside the Hotspot's bounding rectangle to within it. When the mouse cursor is moved from inside to outside the Hotspot's bounding rectangle, the mouseExit method is also called exactly once. Each Hotspot implementation of these methods performs three important tasks:

.  Modifies the value of _imgCurrent to indicate either the active or inactive Image.

.  Schedules a repainting of the Hotspot using the parameterless repaint() method.

.  Returns true from the Event handling method, indicating that the Event has been handled and can be discarded.

Hotspot.paint() is implemented to paint the Hotspot's display surface with the Image indicated by Hotspot._imgCurrent. Before this can be done, the Hotspot must make sure the Image has been fully prepared for display on the device. checkImage() will return a logical ORing of the ImageObserver flags indicating which data for the Image has been successfully prepared for rendering. Hotspot checks for the ALLBITS flag, which indicates the Image has been fully prepared. Once this flag is detected, the Hotspot draws the Image.

Figure 2-8 is a screenshot of the the HotspotApplet running within the JDK's AppletViewer. Note that the mouse cursor is over the first of the two Hotspot Components, so the first Hotspot is displaying its Active image, while the second Hotspot is displaying its Inactive image.


Figure 2-8  Screenshot of the HotspotApplet running within the JDK's AppletViewer

mouseMove

ClassName

Component

Purpose

The Event handler for MOUSE_MOVE Events.

Syntax

public boolean mouseMove(Event evt, int x, int y);

Parameters

Event evt

The MOUSE_MOVE Event object that was passed to this Component's handleEvent method.

int x

int y

The x and y coordinates, relative to the Component's origin, where the mouse cursor was moved to.

Description

The mouseMove method is called by the default implementation of the handleEvent method of the Component class whenever a MOUSE_MOVE Event is passed to that method. By handling MOUSE_MOVE Events in the mouseMove method, your Component can detect where the mouse cursor is currently positioned within the Component. The first MOUSE_MOVE Event is passed to your Component only after a MOUSE_ENTER Event (MOUSE_ENTER Events can be handled by the mouseEnter Event handler). The MOUSE_EXIT Event, handled by the mouseExit Component method, indicates that the mouse cursor has left your Component's bounding rectangle on the desktop, and that you will no longer receive MOUSE_MOVE Events. If the mouse is being moved with the mouse button held down, then your Component will receive MOUSE_DRAG Events, handled by the mouseDrag Event handler method.

Returns

As with all Event handlers, your implementation of this method should return true if the Event is completely handled by your code. A return value of false will cause the Event to be passed on to your Component's Container through the Event passing mechanism described earlier in this chapter.

See Also

See the mouseDrag, mouseEnter, and mouseExit methods of the Component class.

Example

This example demonstrates simple handling of MOUSE_MOUSE Events using a mouseMove method implementation. The method just writes the mouse position to System.out.

public class MyComponent extends Canvas



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 811
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved