/
Text
THEJava Class
Libraries
Second Edition, Volume 2
java.applet, java.awt, java.beans
Patrick Chan
and
Rosanna Lee
java.applet
The applet framework involves two entities: the applet and the applet context. An applet is an
embeddable window (sec the Panel class) with a few extra methods that the applet context
can use to initialize, start, and stop the applet.
The applet context is an applica-
tion that is responsible for loading and
running applets. For example, the
applet context could be a Web browser
or an applet development environment,
as shown in Figure 1.
This package contains the classes
necessary to create an applet and the
classes an applet uses to communicate
with its applet context.
Applet
context
Applet
Web Browser
FIGURE 1: Relationship Between Applet Contexts and
Applets.
Applet Viewer
Applet
Applet Used for building an applet. All applets must be a subclass of this class.
A class becomes an applet by subclassing this class. It contains methods that the applet can
override and methods for retrieving media via a URL.
ja\ a.applet
Audio
I I. »!»! R
। Audi oCl i p Used to play and 4top sound clips. ।
This class contains methods for fetching and plusing sound clips at a URL. A sound clip can
be played once or in a continuous loop.
Applet Context
AppletContext Used by an applet for communicating with the applet context. (
I AppletStub Used in the implementation of the Appletcontext. Not directly used.
These interfaces specify the methods that all applet contexts must provide to applets. Lor
example, there are methods to display a status message in the applet context's status bar and
methods for discovering other applets that the applet context max contain.
2
The Abstract Window Toolkit (AWT) package contains all of the classes for creating user
interfaces and for painting graphics and images. A user interface object such as a button or a
scrollbar is called, in AWT terminology, a component. The Component class is the root of all
AWT components. See Component for a detailed description of properties that all AWT com-
ponents share.
Some components fire events when a user interacts with the components. The AWTEvent
class and its subclasses are used to represent the events that AWT components can fire. See
AWTEvent for a description of the AWT event model.
A container is a component that can contain components and other containers. A container
can also have a layout manager that controls the visual placement of components in the con-
tainer. The AWT package contains several layout manager classes and an interface for building
your own layout manager. See Container and LayoutManager for more information.
java.awt
Continued from previous page
java.awt
Continued
java.au t
Graphics
Graphi cs
Color
Font
FontMetri cs
Image
MediaTracker
SystemColor
Used for painting basic shapes like lines and rectangles and lor
painting images.
Represents a color; includes methods for converting between RGB
and HSB values.
Represents a font.
Used for determining information about a font, such as height and
character widths.
Represents an image with methods for retries ing its dimensions.
Used for preloading images.
Contains the colors used b\ the platform to paint native compo-
nents.
This set of classes is used to draw
shapes, text, and images on a drawing
surface. Drawing surfaces can
include the screen, an offscreen-
image, and the printer. To draw on a
drawing surface, you must first create
a graphics context on the drawing
surface (see Figure 2) and then use
the graphics context to draw. Since
drawing is always done through a
graphics context, a drawing routine is
easily written to be independent of
the drawing surface.
drawl ine()
Drawing
surface
FIGI RE 2: Graphics Contexts and Drawing Surfaces.
Printing
PrintCraphi cs
Printlob
Used for painting to a printer.
Used for printing to the system s printer.
Phis group of classes is used for printing. An application must first acquire a print job object
(see Tool ki t. getPri nt JobQ) and then use that object to create a graphics context. The
application can then use the graphics context to draw pages for printing.
6
Components
Adjustable
Button
Canvas
Checkbox
CheckboxGroup
Choice
Component
ItemSelectable
Label
List
Scrollbar
TextArea
Textcomponent
TextFi eld
Interface implemented by a component that has an adjustable value, i
A component that generates an event when clicked. |
A component typically used to render graphics. I
A component that maintains a boolean state.
Used for implementing a set of radio buttons.
A component that implements a drop down list.
The superclass of components.
Interface implemented by a component that has items that can be
selected (such as an item in a list). |
A component that displays a text string. I
A component that displays a list of items. |
A component that implements a scroll bar. ।
A component that provides editing for a multi line text string. I
The superclass of text components. ।
A component that provides editing for a one-line text string. 1
__________________________________________________:______J
Г Component "~j
Button 1
pfextField
। MenuComponent I
FIGURE 3: Component and MenuComponent.
The classes in this group represent the components that the AWT’ provides for building user
interfaces. Components interact with a program, which uses them via events. For example,
when a user clicks a component with the mouse, that component fires a mouse down event.
Events in the AWT are organized into a class hierarchy rooted at the abstract class AWTEvent.
Each component fires a different set of events, so you must check with each component’s class
description to determine the type of events a component fires.
All of the classes in this group and in the following containers group are subclasses of
Component, as shown in Figure 3. See the Component class to learn about the properties com-
mon to all components.
This group also contains two interfaces—Ad justable and ItemSelectable- which are
implemented by some of the component subclasses.
java.awt
Menu Components
[ CheckboxMenuItem A menu item that maintains a bool ean state.
। Menu 1 MenuBar 1 MenuComponent MenuContainer I Menuitem ' Menushortcut | PopupMenu L A menu that contains menu items. । A menu bar that contains menus. The superclass of menu components. I The superclass of menu containers. A menu item can be inserted into a menu. | /X sequence of key strokes that can be used io select a menu item. A menu that pops up near a component as a result of the user's mak- । ing a popup menu gesture. _ □
The classes in this group are used to build menus. Except for Menushortcut, all of the classes in this group are subclasses of MenuComponent. as shown in Figure 3. See the MenuCompo- nent class to learn about the properties common to all menu components.
Containers
I Container | Dialog I TileDialog i Frame ' Panel | Sc roll Pane | Window 1 _ I 1 he superclass of containers. The superclass of dialog boxes. । A dialog box for selecting an existing file or naming a new file. A top-level window that has a title, a menu bar. and borders. | A container that can be embedded in other containers. A container that contains a single component that can be \ iewed | using scroll bars. A top-level window that does not ha\e a title, a menu bar. oi bor I ders. ..J
A container can contain components and other containers. A container can also have a layout manager that controls the visual placement of components in the container. Some containers are top-level windows that cannot be embedded in another container.
Cursor
Cursor
Used to represent a cursor.
This class contains definitions of default cursor types.
8
Layout
BorderLayout A layout manager that places components along each edge and in the center.
CardLayout A layout manager that displays one component at a time.
FlowLayout A layout manager that places components left-to-right, top-to-bottom.
Gri dBagConst rai nts Used to specify constraints in a GridBagLayout object.
GridBagLayout A layout manager that places components in a grid that has flexible- sized cells.
GridLayout A layout manager that places components in a rigid grid that has fixed-sized cells.
LayoutManager The interface that a layout manager must implement.
LayoutManager? , The interface for supporting alignment-based layouts.
A layout manager is responsible for arranging the components in a container. For example, the
GridLayout layout manager arranges components in a grid whose cells are exactly (he same
size. The AWT provides a number of useful layout managers. The most versatile but difficult
to use is the GridBagLayout layout manager. If none of these layout managers are appropri-
ate, you can build your own using the LayoutManager and LayoutManager2 interfaces.
Geometry
Dimension Insets Used to specify the size of a rectangle (width and height). Used to specify the insets of a rectangle (top, left, bottom, and right).
Poi nt Polygon Rectangle Used to specify a point using x- and y-coordi nates. Used to hold an array of points. Used to specify (he location and size of a rectangle (x. y, width, and height).
Shape Interface for shapes such as a rectangle.
The classes in this group are used to hold collections of values. For example, a Rectangle
object holds four values that represent the locations of the edges of a rectangle. These classes
are used throughout the AWT classes.
javu.awt
Events
AWTEvent
AWTFventMulticaster
Event DEPRLCAHl)
EventQueue
The superclass of the event class hierarchy.
An event dispatcher lor the AWT events.
Replaced h\ AWTEvent and its hierarch) of event subclasses.
A queue tor posting and dispatching AWT events.
When a user interacts with a program using AWT
components» the user's actions are translated into
events. The Java LI event model is a notification-
based system. When a user clicks a component with
the mouse, that component generates a mouse down
event that is placed on the system event queue. When
the event reaches the head of the queue, it is dis-
patched to the component.
Objects that fire events are called event sources.
An object can listen tor events from such event
sources. These objects are called event listeners, For
each type of event that is fired, the source maintains
a list of event listeners for that event type. An event
listener registers with the event source. When an
event of the corresponding type is fired by the
source, the listener is notified. See Figure 4.
Ihe AWTEventMulti caster class is used to
Peer
System
Event
Queue
Event Source
AWTEvent
Dispatch
dispatchFventQ
processEventО
Event Listeners
Fire
C)
notify event listeners. The event is not forwarded to i кд re 4: AWT Event Hou.
other components in the AW'T component hierarchy.
regardless of whether any listeners processed the event. See Figure 5(a).
Events in the AWT are organized into a class hierarchy rooted at the abstract class
AWTEvent. The AWT event hierarchy organizes the different types of events that AWT compo-
nents can fire. /X subclass of an event class provides more details on the nature of the event.
For example, KeyEvent and MouseEvent are subclasses of the more general InputEvent. A
KeyEvent contains not only general InputEvent information, for example, about the pressed
modifier keys and the time of the input, but also information about the key that was pressed or
released. For details of the .AWT event model, see AWTEvent,
10
Frame
(h> Old Java 1.0 Evt-nC Model
FIGURE 5: Event Flow in Component Hierarchy.
In Java 1.0, an event is represented by the now-deprecated Event class and automatically
flows up the component’s containment hierarchy until it is handled by one or more event han-
dlers. Figure 5(b) shows a component hierarchy and an event flowing through that hierarchy. It
shows a user event first being delivered to a button component and then passing through all of
the component's ancestors. As the event flows up the hierarchy, any component receiving the
event can handle the event and therefore stop the event from continuing upward. As noted pre-
viously, Java 1.1 events are not forwarded in this manner. This model is still available in Java
1.1 for compatibility. However, it should no longer be used.
java.au t
Toolkit
1 Toolkit Used to retrieve information about the screen. |
This class contains methods that return information about the platform’s screen, such as its
dimension and resolution. It also contains methods that create native versions of Java сотри-
nents called peers. For example, when you create a Button component, the Button class uses
the Toolkit class to create a button peer. These peer creation methods are not normally used
directly, since each component class automatically calls the Toolkit methods to create and
destroy its associated peers.
Errors and Exceptions
AWTError Thrown if an unrecoverable condition arises. This error should not be caught.
AWTExcepti on Thrown if an error occurs in an AWT operation. This 1 exception must be caught or declared in a throws clause.
Il1 egalComponentStateExcepti on Thrown when the program attempts to perform an । operation on an AWT component while the com- | ponent is not in an appropriate state to perform the operation. i
These are the errors and exceptions declared in the /\WT package.
12
java.awt.datatransfer
This package contains interfaces and classes for transferring data between and within applica-
tions.
Clipboard
Clipboard Used for copy and paste operations between or within an application. I
Clipboardowner Used by an object wishing to be notified that its data is no longer in the
clipboard. ।
_________________________________________________________________________________I
A clipboard is an object that temporarily holds data as it is being transferred between or within
an application. It is typically used in copy and paste operations. Although it is possible to cre-
ate a clipboard to use within an application, most applications will use the system clipboard.
To retrieve a handle to the system clipboard, use Tool kit.getSystemCli pboardf).
A clipboard does not hold data directly. Instead, the data must be encapsulated in a trans-
ferable object before it can be placed on the clipboard. See the Transferable interface for
more details. Note; In Java 1.1.2, the system clipboard can hold only string selections (see
St ri ngSel ecti on).
The clipboard owner of a clipboard is the object whose data is presently in the clipboard.
By implementing the Clipboardowner interface, it can be notified when its data is no longer
in the clipboard.
ja\ u.au i.daiatran sfer
java, awt. datatran sfer
Clipboard Data
| DataFlavor Used (o retrieve the data in a transferable object. ।
[ Str? ng Select ion A data flavor for retrieving the data in a transferable
object as a string. *
I 1 ransf erab 1 e The t\ pe of objects that can be placed on a clipboard. |
। Unsupported 1 avorExcepti on Thrown if a '«'bferable object does not support a
। requested flavor.
When an application wants to place data on a clipboard, it must first encapsulate the data in an
object that implements the Transferable interface. Similarly, when an application retrieves
the contents of a clipboard, it is given a transferable object that it must use to retrieve the
encapsulated data.
To retrieve the actual data from the transferable object, an application must use a data fla-
vor. The data flavor specifies exactly how the data should be delivered to the requestor. l;or
example, if the clipboard contains a string, the requestor could ask for the data in the form of a
Stri ng object or as an St ri ngReader object.
14
java.awt.event
Components interact with a program that uses them through the use of events. For example»
when a user clicks a component with the mouse» that component fires a mouse down event.
Events in the AWT are organized into a class hierarchy rooted at the abstract class AWTEvent.
This package contains interfaces and classes for dealing with different types of events fired by
AWT components. See the AWTEvent class for details on the event model.
java.au t.e sent
Event Class Hierarchy
java.awt.event
1 ActionEvent Fired by a component or menu component to indicate that an action has occurred.
* AdjustmentEvent Fired by an adjustable object to indicate that its adjustment value has changed.
1 ComponentEvent Fired by a component whenever it is moved, resized, hidden, or made vis 1 ible. 1
1 ContainerEvent [ FocusEvent InputEvent Fired by a container whenever a component is added or removed from it. ( Fired by a component whenever it gains or loses focus. . Fired by a component whenever the user uses the keyboard and/or mouse i to interact with the component. |
1 ItemEvent 1 KeyEvent Fired by an itenbselectable object to indicate that its state has changed. । Fired by a component that has the focus whenever the user types at the « keyboard.
! MouseEvent Fired by a component that has the focus whenever the user uses the mouse.
1 PaintEvent Used internally by the AWT to manage the updating of the component's ' display area. 1
1 TextFvent Fired by a text component w henever the contents of the text component ) changes. .
1 WindowEvent Fired by a window whenever it is opened/closed. activated/deactivated. or
i i с о n i П ed/de i con i f i e d.
The AWT event hierarchy organizes the different types of events that AWT components can
fire. A subclass of an event class provides more details on the nature of the event. For exam-
ple, KeyEvent and MouseEvent are subclasses of the more general InputEvent, A KeyEvent
contains not only general InputEvent information, for example, about the pressed modifier
keys and the time of the input, but also information about the key that was pressed or released.
16
Event Listeners
ActionListener AdjustmentListener Interface implemented by objects wishing to receive action events. Interface implemented by objects wishing to receive adjustment events.
ComponentListener Interface implemented by objects wishing to receive component events.
Contai nerLi stener Interface implemented by objects wishing to receive container events.
FocusListener ItemListener KeyListener MouseListener Interface implemented by objects wishing to receive focus events. Interface implemented by objects wishing to receive item events. Interface implemented by objects wishing to receive key events. Interface implemented by objects wishing to receive mouse pressed/ released, entered/exited. and clicked events.
MouseMoti onLi stener Interface implemented by objects wishing to receive mouse dragged or mouse moved events
TextLi stener WindowListener Interlace implemented by objects wishing to receive text events. Interface implemented by objects wishing to receive window events.
The Java event model is a notification-based system. Objects that fire events are called event
sources. A single event source can fire one or more different types of events. For each type of
event it fires, the source maintains a list of event listeners for that event type. An event listener
registers with the event source using the registration methods provided. When an event of the
corresponding type is fired by the source, the listener is notified.
Each subclass of AWTEvent has an associated interface called the event listener interface.
For example, the ActionEvent class has an associated ActionListener interface. Each
interface defines one or more listener methods that a listener of that event type must imple-
ment. For example, the ActionListener interface contains the single listener method
actionPerformedO, which is invoked on the listener when an action event is fired by the
object with which it has registered.
jaxa.avM.event
Event Listener Adapters
ComponentAdapte r A component listener in which all callback methods are empty 1 implementations. |
Contai nerAdapter A container listener in which all callback methods are empty.
FocusAdapter A focus listener in which all callback methods are empty, '
KeyAdapter A key listener in which all callback methods are empty.
MouseAdapter A mouse listener in which all callback methods are empty. '
MouseMoti onAdapter A mouse motion listener in w’hich all callback methods arc empty
Wi ndowAdapter A window’ listener in which all callback methods are empty. '
java.awt.event
F;or convenience, when an event listener interface has more than one listener method (Compo-
nentEvent, ContainerEvent, KeyEvent. MouseEvent, FocusEvent. and WindowEvent),
the AWT also defines event adapter classes. An event adapter class defines empty implemen
rations for all of the methods in the corresponding event listener interface. This means a sub
class of an event adapter needs to provide (override) only implementations of the methods it
wants to handle. For example, if you want the listener to handle only the KEY_PRESSED sub-
type of KeyEvent, you would subclass from KeyAdapter and override keyPressedQ. To
achieve the same effect directly using the Key Li stener interface, you would need to provide
implementations for all three methods (keyPressedO, keyRel eased(), and keylypedO).
18
java. awt. image
This package contains classes for creating and modifying images. Images are processed using
a streaming framework that involves an image producer and an image consumer. This frame-
work makes it possible to progressively render an image while it is being fetched or generated.
Moreover, the framework allows an application to discard the storage used by an image and to
regenerate it at any time.
In between the image producer and the consumer, you
can insert one or more image filters that can modify the
image data as it passes through the image filler, figure 6
shows an image stream.
This package provides a number of image producers,
consumers, and filters that you can configure for your
image processing needs. If none of the provided classes
suits your needs, you can construct your own image pro-
ducers, consumers, and filters by using the supplied
classes, which serve as excellent examples.
Another participant in the image streaming framework
is the image observer. The image observer can receive
notifications on the progress of an image as it is being
FIGL'RF 6: (mage Producer,
Consumers, and Filters.
java.awi. image
loaded. A class can become an image observer by implementing the ImageObserver inter-
face.
Also included in this package are classes that deal with an image's color model, which
specifies how to translate the image's pixel value into colors.
Image Observer
. Imageobserver Used for obtaining the progress status of the loading of an image. I
Л class must implement this interface if it wants to receive the progress status of an image as
the image is being loaded.
Image Producers
I ImageProducer The superclass ol all image producers. ,
I MemoryImageSource Used for producing an image from an array of pixels.
The ImageProducer class is used to build image producers. One image producer is provided
for producing an image from an array of pixels.
Image Consumers
java.awt.image
1 । ImageConsumer The superclass of all image consumers. |
1 PixelGrabber i Used for extracting the pixel values from an image.
The Imageconsumer class is used to build image consumers. One image consumer. Pixel
Crabber, is provided for extracting pixel \alues from an image.
Image Filters
J AreaAveragingScaleFiHer Used to scale images using an area averaging algorithm. .
। ImageFiIter 'ITie superclass of all image filters. J
1 CropImageFi Her An image filter for creating a subimage from an image. |
| Fi1teredlmageSource Used for inserting an image filter into an image stream.
. ReplicateScaleFiIter Used to scale images using a simple pixel replication algo- |
rithm.
j RGBImageFilter Used to create an image filter. 1
The ImageFi Iter class is used to build image consumers. Three image filter classes are avail-
able for various kinds of image filtering. Two classes for scaling images are also available.
20
Color Models
ColorModel Di rectColorModel Indexed orModel The superclass of all color models. A color model whereby the colors arc encoded in the pixel values. A color model whereby pixel values are indexes into a color table. 1
A color model is associated with an image and specifies how to translate the image's pixel val-
ues into colors.
java. awt. peer
java.awt.peer
An AWT component such as a button uses the platform's native implementation of a button.
For example, on Solaris the AWT button uses the Motif button widget, while on Windows 95
the AWT button uses the button control. To make the AWT button component behave the same
on all platforms, the button is assigned a peer, whose task is to lake care of translating the
behavior of the platform's native button to the behavior of the AWT button.
For the AWT subsystem to be able to use a set of peers with a platform and a vendor-
dependent implementation, the peers must implement a set of common interfaces called the
peer interfaces. These peer interfaces are all contained in this package as part of the Java pack-
age hierarchy. The peer classes that implement these interfaces, however, are not pan of the
Java package hierarchy. Rather, they are located in a package that has a platform- and vendor-
dependent name, such as sun.awt.win32. The name of the package is contained in a system
property (so that the AWT subsystem can find it). Figure 7 shows a component hierarchy and
its corresponding peer hierarchy.
FIGURE 7: The Component Hierarchy and Its Corresponding Peer Class Hierarchy.
iava.au t.peer
Component Peers
Buttonpeer The peer interface for the Button component.
CanvasPeer The peer interface for the Canvas component.
CheckboxMenultemPeer The peer interface for the CheckboxMenuItem component
CheckboxPeer The peer interface for the Checkbox component.
Choi cePeer The peer interface for the Choi ce component.
ComponentPeer The peer interface for the Component component.
Contai nerPeer The peer interface for the Container component.
Di alogPeer The peer interface for the Di alog component.
Fi leDi alogPeer The peer interface for the Fi 1 eDi alog component.
FramePeer The peer interlace for the Frame component.
Label Peer The peer interface for the Label component.
1 i stPeer The peer interface for the List component.
MenuBarPeer I’he peer interface for the MenuBar component.
MenuComponentPeeг The peer interface for the MenuComponent component.
MenuTtemPeer I he peer interface for the Menuitem component.
MenuPeer The peer interface for the Menu component.
PanelPeer The peer interface for the Panel component.
PopupMenuPeer The peer interface for the PopupMenu component.
Scrol1barPeer The peer interface for the Scrol 1 bar component.
Scrol1PanePeer The peer interface for the Scrol 1 Pane component.
TextAreaPeer The peer interface for the TextArea component.
TextComponentPeer The peer interface for the TextComponent component.
lextFi eldPeer The peer interface for the TextFi el d component.
Wi ndowPeer The peer interface for the Wi ndow component.
Lightweight Component Peer
- ..............................................- .
Li ghtwei ghtPeer The peer interface for components that do not have a native
peer.
A lightweight component is a component that does not have a corresponding native peer.
Instead, it has a lightweight peer. A lightweight peer contains information used by the AWT
system to make lightweight components behave like a native component. See Component for
more information about lightweight components.
24
Font Peer
FontPeer
The peer interface for the Font class.
A font also has a font peer that uses the platform’s native font resources. This is analogous to a
windowing system component’s having a component peer.
Event
ActiveEvent
The interface for an event that dispatches itself.
ActiveEvent is a special type of event that dispatches itself. (Normally, an event is dis-
patched to the event source that is typically an AWT component.) See AWTEvent for a descrip-
tion of events fired by AWT components.
java.beans
The java.beans package contains classes related to Java Beans development. A feu of the
classes are used by beans while tbe> run in an application. For example, the event classes ate
used by beans that fire property and vetoable change events (see PropertyChangeEvent).
However, most of the classes in this package are meant to be used by a bean editor (that is. a
development environment for customizing and putting together beans to create an application).
In particular, these classes help the bean editor create a user interface that the user can use to
customize the bean. For example, a bean may contain a properly of a special type that a bean
26
editor may not know how to handle. By using the PropertyFdi tor interface, a bean devel-
oper can provide an editor for this special type.
lb minimize the resources used by a bean, the classes used by bean editors are loaded only
when the bean is being edited. They are not needed while the bean is running in an application
and therefore not loaded. This information is kept in what's called a bean-info (see Beaninfo).
Feature Descriptors
BeanDescriptor
EventSetDescri ptor
FeatureDescriptor
IndexedPropertyDescriptor
MethodDescriptor
ParameterDescri ptor
PropertyDescri ptor
Contains global information about the bean.
Contains information about the events fired by the bean.
Common superclass of all feature descriptors.
Contains information about the bean s indexed properties.
Contains information about the bean’s public methods.
Contains information about the parameters in the bean's pub-
lic methods.
Contains information about the bean’s non indexed proper-
ties.
A feature descriptor is an object used to hold
information about some part (called a feature) of a
bean. For example, the feature descriptor of a
bean property specifies whether it is bound or
constrained. A bean has six kinds of features:
bean, event set, indexed property, method, param-
eter, and property. Each of these features is repre-
sented by its own feature descriptor class.
The parts of a feature descriptor are called
attributes. All feature descriptors share a common
set of attributes. These are contained in the class
FeatureDescriptor. All feature descriptor
classes extend from this class to inherit the com-
mon attributes.
There are two kinds of feature descriptors:
implicit and explicit. Implicit feature descriptors
are created through the process of introspection. HGCRE8: Implicit and Explicit Descriptors.
Explicit feature descriptors are explicitly supplied
by the bean developer. See Figure X. See the various feature descriptor class descriptions for
details on the default attribute values for implicit feature descriptors. See the Beaninfo class
for information on how to provide explicit feature descriptors.
Introspector
Explicit
Descriptors
Implicit
Descriptors
Bean
Bean-Info
0
Bean Descriptor
Event Set Descriptors
Method Descriptors
Parameter Descriptors
Property Descriptors
java, beans
The Bean-info
Beaninfo
Simp!eBeaninfo
Interface implemented by bean info objects.
A default bean-info that can be customized by subclassing.
When a bean editor loads a bean, it asks the introspector (see Introspector) to construct a
set of feature descriptors (see FeatureDescriptor). These descriptors contain information
used by a bean editor to create an interface for editing the bean. By default, the introspector
uses a process called introspection to discover the feature descriptors for a bean. This process
basically involves detecting signature patterns in the bean's public methods (see Introspec-
tor for more details).
However, some feature descriptors created by introspection may not have the desired val
ues (since there are some things that the introspector cannot determine). In this case, the bean
must provide explicit feature descriptors for the introspector. These explicit feature descriptors
are packaged in an object called a bean-info. See Figure 8.
Introspection
Introspector Used to apply introspection on a bean.
Introspection is a process used by a bean editor to discover information about a bean. The bean
editor uses this information to construct a user interface for customizing the bean. One type of
information discovered through introspection is the bean's set of properties. The bean editor
uses the set of properties (and their types) to create a property sheet that the user can use to
customize the bean.
There are two places in which introspection looks for this information. The first is in the
bean's bean-info, if one exists. The bean-info contains explicit information that a bean devel-
oper has associated with a bean. For example, the developer may have provided localized
names for all of the bean's properties. See Beaninfo for more information about bean-infos.
The second place in which introspection looks for information is the bean's list of public
methods. The bean specification defines conventions for methods that deal with properties and
events. For example, if the methods
public String getFlavorQ
public void setFlavor(String flavor)
are found, it is assumed that the bean has a string property called “flavor," See PropertyDe
scriptor and EventSetDescri ptor for details about the method signature conventions.
28
The Property Change Event
PropertyChangeEvent
propertyChangeListener
PropertyChangeSupport
propertyVetoExcepti on
VetoableChangeListener
VetoableChangeSupport
Hired when bound properties are modified and when constrained
properties are about to be modified.
Interface (hat must be implemented by property change listeners.
Contains convenient methods for beans that fire property change |
events.
Thrown by a listener that is vetoing a vetoable change event.
Interface that must be implemented by vetoable change listeners.
Contains convenient methods for beans that lire vetoable change
events. I
The beans package introduces an event called the property change event. The property change
event behaves very much like all of the other events in the java.awt.event package. For
example, this event is delivered only to objects that have been registered by a call to the bean’s
addPropertyChangeListenerО method.
The property change event is fired when certain bean properties are modified. These prop-
erties are called bound properties. Another type of property, called a constrained property,
causes a property change event to be fired just before the event is modified. Any vetoable
change listener can veto (or cancel) the event, thereby preventing the property from being
modified. A listener vetoes a vetoable change event by throwing PropertyVetoException.
Both the property and vetoable change events are instances of PropertyChangeEvent.
They are distinguishable by the listeners because the events are delivered to the listeners via
different callback methods. See PropertyChangeEvent for more information about the prop-
erty and vetoable change events.
Property Editors
Customizer
PropertyEditor
PropertyEditorManager
PropertyEdi torSupport
A specialized user interface for editing bean properties.
A user interlace for editing a bean property.
Used for locating property editors.
A default implementation of a property editor.
A property editor is essentially a user interface for editing a bean property and hence is used
only by a bean editor. Different property types require different property editors. For example,
in the case of a siring property, the string property editor might provide a text field for editing
the string. In the case of a color, the color property editor might provide knobs for controlling
each of the color’s components.
A customizer is a user interface for editing all of a bean’s properties as opposed to a prop-
erty editor, which is a user interface for editing a single bean property. For example, if the bean
has graphical properties, the customizer may provide a more productive way of editing the
java, beans
bean compared to ways offered by the bean editor’s default property editors. Another use of a
customizer is to prox ide a step-by-step way of customizing a bean. See Customizer for more
details.
The Bean Environment
Beans Contains methods for controlling and querying the bean enx iron-
ment.
Vi si bi 1 i ty Used bv beans that can run with or without a u indow sx stem.
1____ ____________________________________ ______________________________ '
A bean environment is an environment that can load, instantiate, and execute beans. The
Beans class contains methods that apply to a single bean environment. Any changes to the
state of Beans are seen by all beans in that bean environment. Bor example. Beans has a
design-time property that, when set to true, causes all of the beans in the bean environment to
enter design mode.
The Vi si bi 1 i ty interface is implemented by beans that can be run in a server-based bean
environment. The server may or may not have a display and hence a window system. If a bean
implements Visibility, the bean environment will inform the bean whether a window sys-
tern is available.
30
J
ActionEvent
Syntax
public class ActionEvent extends AWTEvent
Description
An action event is typically fired by a component to trigger some high-level activity in an
application. For example, double-clicking a filename in a list component fires an action event
that might cause the application to open a file. Action events are fired by the components But-
ton, List, Menuitem, and TextField. For more general information about events, see
AWTEvent.
Listening for Action Events
To listen for action events from an object, the listener must implement the ActionLi stener
interface. After that, the listener must be registered with the object. It becomes registered by
calling the object’s addActionLi stener() method.
Action Command
When a component creates an action event, it can include a nonlocalized string, called the
action command., that gives a little more detail about what caused the event. The content of the
action command is very specific to the component that fired it. For example, the action com-
mand of a menu item is the menu item’s label, whereas the action command of a list is the cur-
rently selected item. Table 1 shows all the AWT components that fire action events and what
they include as the action command.
Action Event
java.awt.event
Component Action Command _ _
Button A string containing the button’s label or its programmatically sei action command.
List Menuitem TextFi eld A siring containing the list s selected item. A string containing the menu item's label. A siring containing the contents of rhe lexi field.
TABLE к AWT Components That Fire Action Events.
Modifiers
Fhe key modifiers that were pressed at the time the action event was created are available in an
action event. They can be retrieved using the getModi fiersO method. See the InputFvent
class description for more details.
Note: In Java 1.1.2, the modifier state for action events is not yet implemented.
Action Event Flow
Figure 9 shows how action events typically flow
through the system. First, the event is fired by a
component peer in response to some user gesture.
This event is posted on the event queue (see Event-
Queue). When (he event makes its way to the front
of the queue, it is given to the component via its
di spatchEventO method. The main purpose of
this method is to discard the event if the action event
type is not enabled or if there are no action event lis-
teners. Otherwise. di spatchEventO calls
processEvent О, which in turn calls different
methods depending on the event type. Since this is
an action event, processActionEventO is called.
The main purpose of this method is to notify the
action event listeners.
A component can override processAction-
EventO to process action events before they are
delivered to its listeners. The overridden method
should call super .processActionEventO to
ensure that events are dispatched to (he component's
listeners.
Peer
System
Event
Queue
Button
List
Menuitem .
TextF i eld
di spatchEventO
processEventO
I
processActi onFvent()
ActionLi stener
FIGURE 9: Action Event Flow.
Constructor
ActionEventО Constructs an ActionEvent instance.
Property Methods I
getActionComrtiandO Retrieves the action event's action command. 1 в
getModifiersO Retrieves the state of the action event's modifier keys. (
Action Event Ids
ACTION-FIRST Constant specifying the first id in the range of action event ids.
ACTION-LAST Constant specifying the last id in the range of action event ids । 1 h
ACTION-PERFORMED Event id indicating that an action event occurred. । F
Modifier Masks G
ALT_MASK Used to determine the state of the Alt key.
CTRL_MASK Used to determine the state of the Control key. H
META-MASK Used to determine the state of the Meta key. I
SHIFT-MASK Used to determine the state of the Shift key. । j
Debugging Method к
paramStri ng() Generates a string representing the action event's state. L
м
See Also
ActionListener, java.awt.AWTEvent, java.awt.Button,
java.awt.Component.di spatchEvent(), java.awt.Component.processEvent(),
java.awt.Li st, java.awt.Menuitem, j ava.awt.Text Field.
Example
This example shows all the
components that can Tire action
events. When a component
fires an action event, the frame
prints it out. See Figure 10.
N
()
P
Q
R
S
T
u
V
w
X
Y
FIGURE 10: Components That Fire Action Events.
import java.awt.*;
import java.awt.event.*;
public class Main extends Frame implements ActionListener {
Menuitem menuitem new MenuItemC'Menultem");
juva.awi.event
ActionEvent
ЛГПО^FIRST
Button button = new ButtonC'Button”) ;
Li st list - new L i st();
TextField textfield = new TextField("TextPie1d");
MainO {
super("Actiont-vent Example”);
list. addltemC'Li st") ;
// Create menubar and initialize.
MenuBar mb - new MenuBarO;
Menu m - new MenuC'Menu");
m.add(menu i tem);
mb,add(m);
set^enuBar(mb);
// Listen for events
menui tem.addActionl i stener(thi s);
button.addActionListener(thi s):
list.addActionLi stener(thi s);
textfield.addActionlistenet(thi s);
// Layout components
setLayout(new FlowLayout());
add(button);
add(li st);
addftextfi eld);
pack();
show О;
}
public void actionPerformed(ActionLvent evt) {
System.out.print 1n(evt);
}
public static void main(String argsLJ) {
new Mai n();
}
}
ACTION_F1RST
Pl RPOSE Constant specifying the first id in the range of action event ids.
SYNTAX public static final int ACTION_FIRST
P1-SCRIPT1ON All action event ids must be greater than or equal to ACTION-FIRST (\alue 1001).
SEE Л1 SO ACTION__LAST.
LX.AMPl F See j ava.awt.Component.processEvent0.
34
AC 1 IVIN. 1
ACTION_LAST
PURPOSE Constant specifying the last id in the range of action event ids.
SYNTAX public static final int ACTION-LAST
DESCRIPTION All action event ids must be less than or equal to ACTION-LAST (value 1001). И
SEE ALSO ACTION_FIRST. B
EXAMPLE See java.awt.Component.processEventQ. c
D
E
ACTION-PERFORMED
PURPOSE Event id indicating that an action event occurred. q
SYNTAX public static final int ACTION-PERFORMED 14
DESCRIPTION All action events fired by the components Button, Li st. Menuitem, and j TextField have this id (value 1001). j
SEE ALSO ActionEventO. iz
EXAMPLE IS Sec the java.awt .Canvas class example.
L
M
ActionEventO N
purpose Constructs an ActionEvent instance. О
syntax public ActionEventfObject source, int id, String command)
public ActionEvent(Object source, int id. String command, int
modi tiers)
description This constructor creates an action event with source as the object firing this
event. If modifiers is not specified, modifier defaults to 0. At present, there
is only one action event id, so id must be set to ACTION-PERFORMED.
The source object should implement the various methods that support action
event listeners: addActionListenerO, removeActionListenerO,
processEventQ, and processActionEventO. For an example of a compo-
nent implementing these methods, see the Canvas class example.
After the action event is created, the source object can distribute the event to
its listeners by calling AV/TEventMulti caster. actionPerformedf). If the
event is not created by source, the creator can deliver the event to the source
component either by posting the event to the event queue (see Event-
Queue . postEvent ()) or by calling the source component's Component. di s-
patchEventO method directly.
P
Q
R
S
u
V
w
X
Y
Z
ActionEvent
java. awt.c vent
ALT MASK
PARAML 11 RS
command The possibly null action command string.
id Must be ACTION-PERFORMED.
modi f i ers The state of the modifier keys.
source The non-nul 1 object that is Tiring this action event.
see aiso ACTION-PERFORMED, getActionCommandO , getModi fiers() ,
java.awt.AWTEvent.getIDО. java.util, TventObject. getSourceO-
example Seethe java .awt .Canvas and java .awt .Component class examples.
E
. ALT_MASK
G pi-r pose Modifier mask used to determine the state of the Alt key.
H SYNTAX public static final int ALT_MASK
1 J DESCRIPTION This mask (value 8) should be bitwise and’ed with the results ofgetModifi- ersO to determine the state of the Alt key at the time the action event was created. If the result is 0. the Ah key was not pressed; otherwise, the key was
к pressed.
L Note: In Java 11.2. the modifier state for action events is not yet implemented.
M SEE ALSO CTRL_MASK, getModifiers(), META MASK, SHIFT-MASK.
N example Sec also the getModifi ers() example,
boolean isAltDown(ActionEvent evt) {
return (evt. getModi fiersQ & ActionEvent.ALT_MASK) 1- 0;
Q
R
S
T
и
v
w
X
Y
z
CTRL MASK
purpose: Modifier mask used to determine the state of the Control key.
SYNTAX public static final int CTRt_MASK
description T his mask (value 2) should be bitwise and’ed with the results of getModifi-
ersО to determine the state of the Control key at the lime the action event
was created. If the result is 0, the Control key was not pressed; otherwise, the
ke\ was pressed.
Note: In Java 1.1.2, the modifier state for action events is not set implemented.
SEE Also ALT-MASK, getModifiers(), METAJMASK, SHI FT.MASK.
example Sec also the getModifiers() example.
boolean isControlDownfActionEvent evt) {
return (evt.getModifiers() & ActionEvent.CTRL_MASK) != 0;
}
36
I iwiiui /
getActionCommandO
purpose Retrieves the action event's action command.
syntax public String getActionCommandO
description The action command is a nonlocalized string that gives a little more detail
about the cause of the event. For example, the action command of a list com-
ponent is the currently selected item. See the class description for more details
about the action command.
returns The possibly null command action string.
example See the class example.
1
getModifiersO
purpose Retrieves the state of the action event's modifier keys.
SYNTAX
public int getModifiersO
description Stored with an action event is the state of the modifier keys al the time an
action event is fired. This method retrieves the state of all the modifier keys as
a bit set where the state of each modifier key is represented by a particular bit
in the bit set. To determine whether a modifier key was pressed, you must use
the appropriate modifier mask with the bit set. See the various modifier masks
for examples.
Note: In Java 1.1.2, the modifier state for action events is not yet implemented.
returns A bit set containing the state of the modifier keys.
SEE ALSO ALTJ4ASK, CTRL-MASK, META_MASK, SHIFT_MASK.
EXAMPLE
This example demonstrates how to get
action events from a component that fires
them and then determine the event’s
modifiers. The example creates a button
and listens for action events from the but-
ton. In response to an action event, the
specifics of the event are printed. See
Figure 11.
. ActionEvent E x. |Я (< Г j
FIGURE 11:
Act i onEvent.getModifiers О -
import java.awt.*;
import java.awt.event;
class Main extends Frame implements ActionListener {
Main() {
super("ActionEvent Example1');
\
R
C
D
E
F
G
H
1
ActionEvent
META MASK
java.awt .event
Button button - new ButtonC'Button’1) ;
// Listen for action events.
button.addActionLi stener(thi s);
add(button, BorderLayout.CENTER);
pack();
show О ;
}
// Note: modifiers for action events is not yet working in Java 1.1.1.
public void actionPerformed(ActionEvent evt) {
if ((evt.getModifiers() & ActionEvent.ALT_MASK) 1= 0) {
System.out.print("alt ");
} else if ((evt .getModi fiersQ & ActionEvent .Cl R1 .MASK) 1= 0) {
System, out. pri nt(’‘ct rl ”) ;
} else if ((evt.getModifiersQ & ActionEvent.META-MASK) 1- 0) {
System, out .pri nt (’’meta ”) ;
} else if ((evt.getModifiers() & ActionEvent.SHIFT-MASK) !- 0) {
System .out . pri nt ('‘shift r‘);
}
System.out.println(evt.getActionCommandO);
}
J public static void main(String args[]) {
new Mai n();
К }
}
1,
M
N
О
P
Q
R
S
T
i;
v
w
x
METAJV1ASK
purpose Modifier mask used to determine the state of the Meta key
syntax public static final int MEIA_MASK
description This mask (value 4) should be bitwise and'ed with the results of getModi fi-
ers() to determine the state of the Meta key at the time the action event was
created. If the result is 0, the Meta key was not pressed: otherw ise, the key w as
pressed.
Note: In Java 1.1.2, the modifier stale for action events is not yet implemented.
SEE ALSO ALT-MASK, CTRL-MASK, getModifiers(), SHIFT.MASK.
EXAMPLE
boolean isMetaDown(ActionEvent evt) {
return (evt.getModifiersО & ActionEvent.META_MASK) != 0;
}
Y
38
paramstnngt)
paramStringQ_________________________________________________________________
purpose Generates a string representing the action event's state.
syntax public String paramStringO
description The returned string contains the name of the action event and the action com-
mand. A subclass of this class should override this method and return a concat-
enation of its state with the results of super. paramStringO- This method is
called by the AWTEvent.toStringО method and is typically used for debug-
ging.
returns A non-nul 1 string representing the action event s state.
overrides j ava.awt.AWTEvent.paramSt ri ng().
see also java.awt.AWTEvent.toStringO, java.lang.Object.toStringQ.
exampij: See the java. awt. AWTEvent class example.
SHIFT-MASK
purpose:
SYNTAX
DESCRIPTION’
Modifier mask used to determine the state of the
Shift key.
public static final int SHIFT-MASK
This mask (value 1) should be bitwise and’ed
with the results of getModifiersO to deter-
mine the state of the Shift key at the time the
action event was created. If the result is 0, the
Shift key was not pressed; otherwise, the key
was pressed.
Note: In Java 1.1.2, the modifier state for action
events is not yet implemented.
0.8700688792013022
0.5660444695281526
0.5376027810123842
0.6732576250146964
0.22910624408237334
SEEALSO ALT-MASK, CTRL MASK, getModifiersO, MGURE 12:
META_MASK. ActionEvent.SHIFT-MASK.
example This example creates a list of random numbers
in a list. Pressing the Add button adds more random numbers. Pressing
Remove removes the selected number from the list. Pressing Shift-Remove
removes all the numbers from the list. See Figure 12.
ActionEvent
SHIFT MASK
java.awi.event
import java.awt.”';
import java.awt.event.*;
public class Main extends Frame implements Actionlistener {
Button addButton - new Button("Add");
Button removeButton - new Button("Remove");
List list - new L i st();
R Main() {
super("ActionEvent,SHIFT. MASK Example");
C addltemsO;
D // Listen for events
addButton.addActionLi stener(thi s);
I-; removeButton.addActionListener(thi s) ;
Г // Layout components
add(addButton, BorderLayout.NORTH);
G add(removeButton, BorderLayout.SOUTH);
add(list, BorderLayout.CENTER);
H setSize(150, 200);
show();
I }
j public void actionPerformed(ActionFvent evt) {
if ("Add" . equal s(evt. getAct ionCommandO)) {
К addltemsO;
} else if ("Remove" . equal s(evt .getAct ionCommandO)) {
I. // If the shift key is enabled, remove all the items.
if ((evt.getModifiers() A ActionEvent.SHIFT,MASK) != 0) {
M 1ist.removeAl1();
} else if (1 i st.getSel ectedlndexO >= 0) {
X list. remove(li st.getSelectedlndexO);
}
О }
}
P
// Generate some random items.
Q void addltemsO {
for (int i-0; i<5; i i--»-) {
R 1 i st .addItem(,M,+Math. random()) ;
}
S }
T
public static void rrainfString arqs[J) {
t; new Mai n() ;
}
V }
w
X
Y
Z
40
ActionListener
D
E
F
Ci
H
I
J
К
L
M
N
Syntax
public interface ActionListener extends EventListener
P
Description q
When an object (listener) wishes to receive action events from an object that fires them (the R
source object), two things must be done:
1. The listener must implement this interface and (he actionPerformedО method required
by this interface. T
2. The listener must be registered with the source object by making a call to the source t;
object’s addActionLi stener() method. v
An action event is typically fired by a component to trigger some high-level activity in an
application. For example, double-clicking a filename in a list component fires an action event
that might cause the application to open a file. Action events are fired by the components But- x
ton. List, Menuitem, and TextField. See ActionEvent for more details. Y
ActionListener
ja\ a.aw t.e\ cm
A
В
C
1)
r:
i
(i
н
i
.1
к
1
M
N
()
P
Q
R
S
I
U
X
w
X
Y
/.
MEMBER SUMMARY
Action Event Callback Method
actionPerformedO Called when an object fires an action event.
See Also
ActionEvent, java.awt.AWTEventMulticaster, java.awt.Button,
java.awt.Li st, java.awt.Menuitem, java.awt.TextField,
java.util.EventListener.
Example । This example creates a grid of ’ 256 buttons, one button tor each 8-bit Latin-1 (ISO 8859-1 ) character. Sec Figure 13. When you click a button, the program creates a Java Uni- code character (\u00nn) and places it in the system clip- board. \ou can then paste the Java Unicode chaiacter into a text editor. 1 he button label shows the character it it is not an ISO con- trol character. It the character is an ISO control character, the hex value ot the character is 00 Act EB ionl ВЯ Jsti EB anei EB г Ex amp de EQ 08 09 0A 0B ОС 0 1° 0E of]
10 11 12 13 14 15 16 17 18 19 1A IB 1C ID IE IF
1 rr $ % & । ( * + f - /
0 1 2 3 4 5 6 7 8 9 = o
0 A В c D E F 0 H I J К L M N 0
p 0 R 5 T U V W X Y Z [ \ 1 Л
a b c d e f ? h i j k 1 n 0
p 4 r s t u V LT X Y z { 1 } 7F
80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F
90 91 92 93 94' 95 96 97 98 99 9A 9Б 9C 9D 9E 9F
i c £ и ¥ ! § €• a. —i - —
0 rfc £ 3 P SI « i о
A A A A A A Ж E E Ё Ё I i I I
D N 0 6 6 6 0 X 0 U U U U Y P В
a a a a a a ae s ё e e e i 1 i i
8 n 0 0 0 0 0 u u u u Y JL _d
displayed. * The button name is used to | кд KE 13: Liltin-1 Character Selector.
hold the single Latin-1 charac-
ter. When an action event is fiix J. the handler fetches the button's single-character n line and
converts the character into a Java Unicode character
import java.awt;
import java. awt . event. ";
i mport j ava. awt. datat ransfer. ’’;
class Main extends Frame implements ActionListener i
Main О {
super("ActionLi stener Example”') ;
setFontfncw Font("Monospaced' . Font.PlAIN, 12)):
// Create the 256 buttons.
42
Panel p = new Panel (new GridLayout(16, 0));
for (int i=0; i<256; it+) {
Button b = new ButtonC" (char)i);
// If control character, display hex value.
if (Character.isISOControl((char)i)) {
String s = "0" t Integer.toHexString(i).toUpperCase();
b.set Label(s.substring(s.length()-2));
}
b, setName(’,,,+(char)i);
// Listen for events,
b.addActionLi stener(thi s);
// Add to panel.
p.add(b);
}
// Layout and show components.
add(p, BorderLayout.CENTER);
pack();
show О;
}
public void actionPerformed(ActionEvent .evt) {
// Fetch the character.
char c = ((Component)evt .getSourceO) .getNameO charAt (0) ;
// Format the unicode string for Ч1.
String result = "\\u00" * Integer.toHexString(c&0xff);
// Place result in system clipboard.
StringSelection contents = new StringSelectionfresult);
getToolkitO .getSystemCl ipboard().setContents(contents , null) ;
public static void main(String args[J) {
new Mai n();
}
}
actionPerformedf)
PURPOSE- Called when an object fires an action event.
SYNTAX public void actionPerformed(ActionLvent evt)
DESCRIPW\ This method is called when the source object fires an action event.
PARAMETERS evt The non-null action event.
example See the class example.
java.awt.peer
ActiveEvent
^~Act iy^Bvent
Syntax
C public interface ActiveEvent
D
E
1
G
H
1
J
К
I.
M
N
О
P
Description
Normally, when an event reaches the head of the system's event queue (see EventQueue), rhe
AWT system dispatches it to the event source that will fire the event. For example, when the
user presses a key, a key event is created and placed on the system event queue. When the key
event reaches the head of the queue, it is dispatched to the source component that will fire the
key event by invoking the event source's di spatchEvent О method.
An active event is an event that is dispatched to itself. In particular, when the active event
reaches the head of the event queue, the AWT system discovers that it is an active event (b>
noting that it implements the ActiveEvent interface). Instead of calling the event source's
dispatchEventО method, the system will call the active event's dispatchO method. In
short, an active event's source is the active event itself.
Active events are used in situations in which it is necessary to serialize with other events.
For example, an application would post an event into the system's event queue followed by an
active event. When the active event reached the head of the queue, it would inform the poster.
The poster would then know that the event preceding the active event had been dispatched.
At present, no AWT component generates active events.
MEMBER SUMMARY
Peer Method
di spatchQ Dispatches this active event.
T
See Also
java.awt.EventQueue, java.awt.Toolkit.getSystemEventQueueO.
X
Y
Z
44
Example
This example demonstrates how to create an active
event and add it to the system event queue. When dis-
patched, the active event simply displays a message in
the frame. See Figure 14.
' ActiveEvent Exam .
this is a test
FJGl RE 14; ActiveEvent.
import java.awt.peer.ActiveEvent;
import java.awt.*;
class Main extends Frame {
public MainО {
super(“ActiveEvent Example”);
Label label = new Label(““, Label.CENTER);
add(label, BorderLayout.CENTER);
setSize(200, 100);
show();
// Add active event to system event queue.
EventQueue queue = getToolkitO.qetSystemFventQueue();
queue.postEvent(new SampleActiveEvent(“this is a test”, label));
}
public static void main(String[] args) {
new Main();
}
}
class SampleActiveEvent extends AWTEvent implements ActiveEvent {
static final int TESTEVENTMASK - AWTEvent.RESERVED_ID_MAX+100;
Label label;
String msg;
SampleActiveEvent(String msg. Label 1) {
super(msg, TESTEVENTMASK):
this.label = 1;
this.msg = msg;
}
public void dispatchf) {
label.setText(msg);
Pl RPOSE
SYNTAX
1 в c D E F Ci DESCRIPTION
H SEE ALSO
ActiveEvent jaxa.awt.peer
di spate h()
dispatch()
Dispatches this active event,
public void dispatchO
This method is implemented by the active event to perform the tasks associ-
ated with this event. This may include notifying listeners, updating state hold-
ers, and any event-specific tasks.
This method is called by an event-dispatching thread when this event teaches
the head of the event queue.
dispatchO is similar to Component .di spatchEvent О and MenuCompo*
nent .dispatchEventO , except that dispatchO dispatches itself, while
these other two methods dispatch the given AWTEvent argument.
java.awt.Component.di spatchEventO , java.awt.EventQueue,
java.awt.MenuComponent.di spatchEventO.
1
J
К
L
M
N
()
P
Q
R
S
T
U
V
w
X
Y
Z
46
Adjustable
Syntax
public interface Adjustable
D
Description
This interface is typically used by components that maintain an integer value, called the
adjustable value, which can be interactively modified by the user. Such components include F
scrollbars, gauges, meters, and sliders. This interface is currently used by the Scrollbar and G
Scroll Pane classes.
H
The Adjustable Value and Its Range I
An adjustable object has an adjustable value range, which is defined by two integer values:
the minimum and the maximum. The range can be any integer value, positive or negative.
However, the maximum value must be greater than or equal to the minimum value. The range К
can be modified at any time. !
Some adjustable objects are used to scroll around a large document. The adjustable object
has a visible property that indicates how much of the document is visible. The adjustable M
object typically gives a visual indication of this value. For example, the visible value is the size \
of the scrollbar's scroll box. Adjustable objects such as gauges and sliders do not typically
support the visible property. The visible property in these adjustable objects should be 0.
The adjustable object maintains the adjustable value and ensures that it stays within the P
adjustable range. The adjustable object typically has some visual indication of its adjustable q
value. For example, a scrollbar indicates its adjustable value by the position of its scroll box.
When the user moves the scroll box, the adjustable value is automatically updated and an R
adjustment event is fired. S
There are presently no specific rules that the adjustable value must obey with respect to
the minimum, maximum, and visible values. You may implement whatever rules you like. If
possible, however, you should implement the rules used by the AWT scrollbar (see Scroll- L
bar), which at least establishes a precedent. Doing this will make it easier for others to under- V
stand your adjustable object. The AWT scrollbar implements the following rule:
minimum <= adjustable value <= maximum-visible X
The visible value refers to the length of the proportional indicator (or scroll box). Its value Y
must be positive. The minimum and maximum values can be negative.
Adjustable
java.awt
В
С
Г)
Е
F
Cl
II
I
J
К
L
М
X’
О
р
Q
R
S
Г
V
W
X
Y
7.
Block and Unit Increments
Most adjustable components provide a means to increase or decrease the value by a small or
large amount. The small amount is called the unit increment and is typical Iv associated with a
line. The large amount is called the block increment and is typically associated with a page.
The adjustable value can he increased/decreased by a block or unit amount. These incre-
ments must be positive. A block is typically associated with a page and a unit with a line in a
document. Therefore, if the user clicks the adjustable object to view the next page, a
BLOCK-INCREMENT adjustment event is fired. Similarly, if the user clicks the adjustable object
to view a previous line, a UNIT-DECREMENT adjustment event is fired.
The adjustable object's block increment specifies the amount to increase or decrease the
adjustable's value when the user makes a block adjustment gesture. T he same is true for the
adjustable object*s unit increment.
Events
Adjustment events are tired whenever the value maintained by an adjustable object is changed.
See AdjustmentEvent for more details. See the AWTEvent class for general information on
events and how to filter or handle an event.
| MEMBER SUMMARY
Orientation Constants and Method
getOrientationQ HORIZONTAL i 1 VERTICAL Retrieves the adjustable's orientation. The orientation constant specifying a horizontal adjustable object. The orientation constant specifying a vertical adjustable object.
। Property Methods 1 getMaximumO । getMinimumO | getValueO getVi si bl eAmount() I setMaximumO setMinimumQ 1 setValueQ । setVi si bl eAmountO Retrieves the adjustable's maximum value. Retrieves the adjustable's minimum value. Retrieves the adjustable’s adjustable value. Retrieves the adjustable's visible value. Sets the adjustable's maximum value. Sets the adjustable's minimum value. Sets the adjustable's adjustable value. Sets the adjustable's visible value.
| Value Adjustment Methods getBlocklncrementO 1 getUnitlncrement0 setBlocklncrement0 setUni tlncrementO Retrieves the adjustable's block increment. Retrieves the adjustable's unit increment. Sets the adjustable's block increment. Sets the adjustable's unit increment.
48
Listener Methods
addAdjustmentListenerQ
removeAdjustmentListener()
Adds a listener for receiving adjustment events.
Removes a listener from receiving adjustment events.
\
See Also
java.awt.event.AdjustmentEvent, java.awt.event.AdjustmentListener,
Scrollbar, Scroll Pane.
Example
This example creates a slider that implements the
Adjustable interface. The slider maintains a value and
displays an image. Each slider has a round knob whose
position in the slider represents the slider's value. The
slider fires an adjustment event each time the slider's
value changes. See Figure 15.
The slider’s value can be modified in many ways,
including the following:
• Dragging the knob changes the value continuously.
• Pressing the Left, Right, L’p. or Down keys moves
the knob up/left or down/right by a unit.
• Pressing the PageUp or PageDown keys moves the
FIGURE 15: /к Slider.
knob up/left or down/right by a block.
• Clicking above/]eft or below/right the knob moves the pointer by a block.
The example creates a frame with two sliders. The frame draws an oval of a particular
color in its center. The color of the oval is controlled by the two sliders. The vertical slider con-
trols the color's saturation: the horizontal slider controls the color’s hue.
Both components, the frame and the slider, use double-buffering to eliminate flickering.
The visible property of an adjustable indicates the ratio of the visible area with respect to
the size of the total area. Since the visible property does not apply to the slider, it is ignored.
One improvement that can be made to the slider in this example is a visual cue to indicate
that the slider has the focus. With this improvement, you can tell which slider will be affected
when you use the keyboard to move the slider.
import java.awt.*;
import java.awt.event;
class Main extends Frame implements AdjustmentListener {
Slider ver «• new SIider(Adjustable.VERTICAL) ;
Slider hor ~ new SIider(Adjustable.H0RI70NTAL);
В
c
D
R
F
G
H
I
J
К
L
M
N
О
P
Q
R
S
T
U
V
w
X
Y
Z
Adjustable
В
c
D
E
F
Ci
H
I
J
К
L
M
N
О
P
Q
R
s
T
и
V
w
X
Y
Z
floatf] hsb = {1.0fT 0.1f, 0.7f};
// This off-screen image is used for double-buffering.
Image bbuf;
MainO {
super(“Adjustable Example’');
ver.setMaximum(1000);
hor.set Max imum(1000);
// Register listeners.
ver.addAdjustmentl istener(this);
hor.addAdjustmentli stener(thi s);
// Set up the frame
setLayout(new BorderLayoutQ) ;
add(ver, Borderlayout.EAST);
add(hor, BorderLayout.SOUTH);
setSize(200t 200);
setVi si ble(true);
}
// Updates the color of the oval.
public void adjustmentValueChanged(AdjustmentLvent evt) {
Adjustable a = evt.getAdjustable();
if (a.getOrientationQ =- Adjustable.VERTICAL) {
hsbEl] = (float)a.getValue()/(float)a,getMaximum();
} else {
hsb[0] = (float)a.getValueO/Cfloatja.getMaximum();
}
repaintO ;
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
int w - getSize().width;
int h = getSize().height;
Insets insets = getlnsetsO;
// Create or enlarge the double-buffer if necessary,
if (bbuf — null
J bbuf.getWidth(this) < w
I’ bbuf.getHeight(this) < h) {
if (bbuf != null) {
bbuf.flush();
}
bbuf - createlmage(w, n);
}
Graphics bbufG = bbuf.getGraphics();
bbufG. setColor(getBackgroundO);
bbufG.fi11Rect(0, 0, w, h);
// Draw oval.
bbufG.setColor(new Color(Color.HSBtoRGB(hsb[0]. hsb[l], hsb[2])));
50
bbufG.fi11Oval(insets.left, insets.top,
w-insets,right-insets.left -ver.getSize().width,
h-insets.bottom-insets.top -hor.getSize().height);
// Paint double-buffer on screen.
g.drawlmage(bbuf, 0, 0, this);
bbufG.disposeC);
}
public static void main(String argsU) {
new Mai n();
}
}
class Slider extends Canvas implements Adjustable {
// The location of the ball.
Point locPt - new Point(0, 0);
// If non-null, the ball is being dragged and this field
// holds the location of the cursor relative to the ball
// when the mouse was pressed.
Point downPt;
// The image of the ball.
Image image;
// Dimensions of the ball.
int ballW, ballH;
// Off-screen image is used for double-buffering.
Image bbuf;
Slider(int o) {
orient = o;
image = Tool kit.getDefaultToolkit().getlmage(“bal1.gif”);
// Wait for the image to be loaded so that we
// can determine its size.
MediaTracker tracker = new MediaTracker(this);
tracker.addlmage(image, 0);
try {
tracker.wai tForAl 1 ();
} catch (Exception e) {
e.printStackTrace();
1
setSize(ballW = image.getWidth(this),
ballH - image.getHeight(this));
// Register listeners.
addMouseListener(new MouseEventLi stenerO);
addMouseMotionListener(new MouseMotionEventLi stenerO);
} addKeyListener(new KeyEventListener());
public void invalidateO {
super.invalidate();
// The bounds of the slider has changed so recompute
// the ball location.
Adjustable
java.awt
setValues(value, min, max);
}
public void paint(Graphics g) {
update(g);
public void update(Graphics g) {
int w = getSizeO-width;
int h = getSize().height;
// Create or enlarge the double-buffer if necessary,
if (bbuf — null
I bbuf.getWidth(this) < w
I bbuf.getHeight(this) < h) {
if (bbuf != null) {
bbuf.f1ush();
}
bbuf = createlmage(w, h);
}
Graphics bbufG - bbuf.getGraphics();
// Clear the background.
bbufG.setColor(getBackground());
bbufG.fi11Rect(0, 0, w, h);
// Draw the track.
bbufG.setColor(Color.gray);
if (orient == Adjustable.VERTICAl) {
bbufG.fi11RoundRect(w/2-1, ballH/2, 3, h - ballH, 5, 5);
} else {
bbufG.fi11RoundRect(bal1W/2, h/2-1, w - ballWT 3f 5t 5):
}
// Draw the bal1.
bbufG.drawlmage(image, locPt.x, locPt.y, this);
// Paint double-buffer on screen,
g.drawlmage(bbuf, 0, 0, this);
bbufG.disposeQ ;
}
// Returns -1 if above/left of ball;
// 0 i f on bal1.
// 1 if below/right o* ball;
int onRa11(MouseEvent e) {
int x - e.getx();
int у = e.getYQ ;
if (orient == Adjustable.VERTICAL) {
if (y < locPt.y) {
return -1;
} else if (y > locPt.y-bal1H) {
return 1;
}
} else {
if (x < locPt.x) {
return -1:
} else if (x > locPt.x+bal1W) {
return 1;
52
return 0;
}
// Handle the events.
class MouseEventListener extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
switch (onBall(evt)) {
case -1:
i nc(AdjustmentEvent.BLOCK-DFCREMENT, -blocklnc);
break;
case 0:
// Enter dragging mode.
(downPt = evt.getPointO) .translate(-locPt.x, -locPt.y);
break;
case 1:
inc(AdjustmentEvent.BLOCK-INCREMENT, blockinc);
break;
}
requestFocusO;
}
public void mouseReleased(MouseEvent evt) {
downPt = null;
}
public void mouseEntered(MouseEvent evt) {
if (onBall(evt) =« 0) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND CURSOR));
}
}
public void mouseExited(MouseEvent evt) {
setCu rsor(Cu rsor.getPredefinedCursor(Cu rsor.DEFAULT-CURSOR));
}
}
class MouseMotionEventListener extends MouseMotionAdapter {
public void mouseDragged(MouseEvent evt) {
if (downPt != null) {
if (orient == Adjustable.VERTICAL) {
setValues(evt.getY() * (max-min)
/ (getSizeO .height-ballH) + min, min, max);
} else {
setValues(evt.getX() * (max-min)
/ (getSizeQ .width-bal 1W) + min, minf max);
}
inc(AdjustmentEvent.TRACK, 0);
}
}
public void mouseMoved(MouseEvent evt) {
if (onBall(evt) ™ 0) {
setCursor(Cursor.getPredefi nedCursor(Cursor,HAND-CURSOR));
}
}
1
class KeyEventListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
switch (evt .getKeyCodeO) {
Adjustable
java.awt
case KeyEvent.VK_DOWN: case KeyEvent.VK„RTGHT: i nc(AdjustmentEvent.UNIT-INCREMFNT, uni tine); break;
case KeyEvent.VK_PAGF_DOWN: inc(AdjustmentEvent.BLOCK-INCREMENT, blockinc); break; case KeyEvent.VK-UP:
в case KeyEvent.VK_LEFT: inc(AdjustmentEvent.UNIГ-DECREMENT, -uni tine);
c break; case KeyEvent.VK-PACE-UP:
D E i nc (AdjustmentEvent. BLOCK-DECREMENT', -blockinc); break; } }
1- G } // x*5<** Adjustable Get Methods *****
H 1 // The properties, int orient; int min - 0;
J int max - 100; int unitinc = 1;
К int blockinc = 10; int visi ble = 0;
1, int value = 0;
M \ public int getOrientationQ { return orient; }
() public int getValueO { return value;
P }
Q public int getMinimumQ { return min;
R S J } public int getMaximumC) { return max; }
I’ public int getVisi bl eAmount() { return 0;
V }
w public int getlini tlncrement 0 t return unitinc;
X }
V Z public int getBlocklncrementO { return blockTnc; }
// Adjustable Set Methods *****
54
void setValues(int va, int mn, int mx) {
value = va;
min = mn;
max = mx;
if (max <= min) {
max = min + 1;
}
if (value < min) {
value = min;
}
if (value > max) {
value = max;
}
// Update the location of the ball.
if (orient == Adjustable.VERTICAL) {
locPt.y = (value-min) * (getSizeO .height-ballH)
/ (max-min);
} else {
locPt.x = (value-min) * (getSize().width-bal1W)
/ (max-min);
}
// Generate an adjustment event.
inc(AdjustmentEvent.TRACK, 0);
repaint();
}
public void setValue(int v) {
setValues(v, min, max);
}
public void setMinimum(int m) {
setValues(value, mf max):
1
public void setMaximum(int m) {
setValues(value, min, m);
public void setVisi bl eAmount(int v) {
}
public void setUnitlncrement(int u) {
uni tine = u;
}
public void setBlockIncrement(int b) {
blockinc = b;
}
// ***** Adjustable Event Methods *****
protected void processEvent(AWTEvent evt) {
if (evt instanceof AdjustmentEvent) {
processAdjustmentFvent((AdjustmentEvent)evt);
return;
}
super.processEvent(evt);
}
java.awt
Adjustable
add Adjustment Listener!)
В
C
D
E
F
G
H
I
J
К
L
M
N
// Deliver event to listeners.
protected void processAdjustmentEvent(AdjustmentEvent evt) {
if (adjustmentListener !=- null) {
adjustmentLi stener.adjustmentValuethanged(evt);
}
}
void inc(int type, int inc) {
if (inc !- 0) {
setValues(value - inc, min, max);
}
if (adjustmentl istener 1= null) {
processEvent(new AdjustmentEvent(thi s,
AdjustmentEvent,ADJUSTMENT_VALUF_CHANGED, type, value));
}
}
// ***** Adjustable Listener Methods *****
transient AdjustmentListener adjustmentListener;
public void addAdjustmentListener(AdjustmentListener 1) {
adjustmentListener = AWTEventMulticaster.add(adjustmentListener, 1);
}
public void removeAdjustmentListener(AdjustmentListener 1) {
adjustmentListener = AWTEventMulticaster.remove(adjustmentl istener, 1);
}
()
P
Q
R
S
T
и
V
w
X
Y
Z
addAdjustmentListener()
pvrposl Adds a listener for receiving adjustment events.
syntax public void addAdjustmentl istener(AdjustmentLi stener 1)
description Adjustment events are fired whenever the value maintained by an adjustable
object is changed. See AdjustmentEvent for more details. After this method
has been called, the adjustment listener 1 will receive adjustment events fired
by this adjustable object.
PARAMI1 i-.rs
1 The non-nul 1 listener to receive adjustment events.
se.l also j ava. awt. event. Adj ustmentFvent,
java.awt.event.AdjustmentLi stener, removeAdjustmentLi stenerO •
i x xmpi f See the class example.
56
getBlockIncrement()
purpose Retrieves the adjustable s block increment.
SYNTAX public int getBlocklncrementO
DESCRIPTION The block increment determines the amount to increase or decrease the adjust- able value when the user makes a block adjustment gesture. See the class description for more information on blocks.
RETURN’S The non-negative block increment.
SEE ALSO setBlocklncrementO.
EXAMPLE Sec the class example.
getMaximumO
PURPOSE Retrieves the adjustable's maximum value.
SYNTAX public int getMaximumO
DESCRIPTION See the class description for details. The actual maximum that the adjustable value can attain is getMaximumO-getVi si bl eAmount ().
RETURNS The adjustable’s maximum value.
SEE AbSO getMinimumO, getValueO, getVisibleAmountO, setMaximumO.
EXAMPLE See the class example.
getMinimumO
PURPOSE Retrieves the adjustable's minimum value.
SYNTAX public int getMinimumO
DESCRIPTION The adjustable's minimum value is the minimum value that the adjustable can attain. See the class description for details.
RETURNS The adjustable's minimum value.
SEE ALSO getMaximumO , getVal ueO , getVi si bl eAmount О, setMinimumO
EXAMPLE See the class example.
getOrien tat ion()
PURPOSE
Retrieves the adjustable’s orientation.
java.awt
Adjustable
gclL’nitlncrementO
syntax public int getOrientationO
Kf-.n rxs The adjustable's orientation. This value can be cither VERTICAL or HORIZON-
TAL.
SH\IM) HORIZONTAL, VERTICAL.
ex vmple Sec the class example.
c
D E E getUnitIncrement()
Pl RPOSL SVXTAX Retrieves the adjustable's unit increment, public int getllnitlncrement()
G DEM. RIP I KA The unit increment determines the amount to increase or decrease the adjust
П able value when the user makes a unit adjustment gesture. See the class
1 1 description for details.
I RLJT RNS The non-negative unit increment.
J SEE ALSO getBlockTncrementО, setUnitlncrementO *
к
L gelValueO
M
N Pl RPOSL Retrieves the adjustable's adjustable \alue.
О SYNTAX public int getValueO
P DESCRIPTION See the class description for details.
Q RL I I R.XS The current value of the adjustable.
R set: also getMaxi mumQ , getMinimum(), getVisi bl eAmount О.
S EX AMPLE See the class example.
1'
(. getVisibleAmount()
V PURPOSE Retrieves the adjustable's visible value.
w SV X 1 AX public int getVisi bl eAmount О
X DESCRIPTION The adjustable's visible value determines the size of its scroll box. See the
Y class description for details.
z RFTt RXS The non negative visible value.
SEE M SO setVisibleAmountf).
LXAMPl E. Sec the class example.
58
HOKIZUN I AL
HORIZONTAL_________________________________ _
purpose The orientation constant specifying a horizontal adjustable object,
SYNTAX public static final int HORIZONTAL
SEE ALSO getOrientationO , VERTICAL.
example See the class example.
C
D
removeAdjustmentListenerO
purpose Removes a listener from receiving adjustment events. p
syntax public void removeAdjustmentListenerfAdjustnientListener I) q
description Adjustment events are fired whenever the value maintained by an adjustable ц
object is changed. See AdjustmentEvent for more details. After this method
has been called, the adjustment listener 1 will no longer receive adjustment 1
events fired by this adjustable object. J
PARAMETERS К
1 The non-null adjustment listener. L
SEE also addAdjustmentLi stener, java.awt.event.AdjustmentEvent,
java.awt.event.Adj ustmentListener,
example See the usage of removeActionListenerQ in Menuitem.dis- N
ableEventsO. О
P
setBlockIncrement()
purpose Sets the adjustable's block increment.
syntax public void setBlocklncrement(int b)
description The block increment determines the amount to increase or decrease the adjust-
able value when the user makes a block adjustment gesture. See the class
description for more information on blocks.
Most implementations will silently modify the block increment to be at most
the adjustable object's maximum value, although this is not strictly necessary.
parameters
b The non negative block increment.
SEE also getBlocklncrementQ , setUni tlncrement О .
Example See the class example.
Q
R
S
T
i:
v
w
X
Y
z
Adjustable
java.awi
setMaximum()
setMaximumO
purpose Sets the adjustable’s maximum value.
syntax public void setMaximum(int max)
description If max is less than the adjustable's minimum value, the implementation should
В set the maximum value to be equal to the minimum value.
< PARAMETERS
max The maximum value.
see also getMaxiriumO , setMinimumO •
exampi e See the class example.
G
H setMinimumO
I PERPOSE Sets the adjustable’s minimum value.
J SYNTAX public void setMinimumfint min)
к 1. DESCRIPTION If min is greater than the adjustable’s maximum value, the implementation should set the minimum value to be equal to the maximum value.
M PARAMETERS
mi n I’he minimum value.
Nl SEE Al SO getMinimumOt set^laximum().
()
P EXAMPL I; See the class example.
Q
setUnitlncrementO
s T L PURPOSE SYNTAX DESCRIP 1 ION Sets the adjustable’s unit increment. public void setllni tTncrement (i nt u) The unit increment determines the amount to increase or decrease the adjust-
V w able value when the user makes a unit adjustment gesture. See the class description for details. Most implementations will silently modify the unit increment to be at most the
X adjustable object's maximum value, although this is not strictly necessary.
Y PARAMEIERS
z U The non-ncgative unit increment.
SEE Al SO getUnitlncrement(), setBlocklncrement().
1 XAMPLE See the class example.
60
set value!)
setValueO^
PURPOSE Sets the adjustable's adjustable value.
SYNTAX public void setValue(int v)
DESCRIPTION This method sets the adjustable's value. See the class description for details.
PARAMETERS V The new value. Il must be within the range defined by the minimum and maxi- mum values for this adjustable.
SEE ALSO getMaximumO , getMinimumO , getValueO, getVi sibleAmountO .
EXAMPLE See the class example.
setVisibleAmount()
PURPOSE Sets the adjustable’s visible value.
SYNTAX public void setVi sibleAmountO nt v)
DESCRIPTION The adjustable’s visible value determines the size of its scroll box. See the class description for details.
PARAMETERS V The non-negative visible value.
SEE ALSO getVisibleAmountO
EXAMPLE See the class example.
VERTICAL
PURPOSE The orientation constant specifying a vertical adjustable object.
SYNTAX public static final int VERTICAL
SEE ALSO getOrientationO, HORIZONTAL.
EXAMPLE See the class example.
java.awt.event
Adj ustmentEvent
I
Syntax
public class AdjustmentEvent extends AWlEvent
Description
L Adjustment events arc fired by adjustable objects (see Adjustable). An adjustable object
M maintains an integer value and fires adjustment events whenever that value changes. Adjust
able objects are typically used in sliders and for scrolling a document.
In the AWT both the Scrollbar and Scroll Pane components fire adjustment events
О (more accurately, the Scroll Pane component has two adjustable objects that fire the adjust-
P ment events). For more general information about events, see AWTEvent.
Q Listen big for A djustment Events
r To listen for adjustment events from an object, the listener must implement the Adjust
mentLi stener interface. After that, the listener must be registered with the object. It becomes
registered by calling the object's addAdjustmentLi stenerf) method. As with most events.
T an adjustment event is delivered to its listeners after the operation has taken place.
L The Value Property
v The value property of an adjustment event holds the new value of the adjustable object. This
w value wall always be within a range that's associated with the adjustable object. See the
Adjustable interface for more details.
X
Y Adjustment Types
The adjustment type describes how the adjustable's value was changed. The value can be
i nc re a sed/de creased b) a block or unit amount. A block is typically associated with a page and
a unit with a line in a document. Therefore, if the user clicks the adjustable object to view the
62
next page, a BLOCK-INCREMENT adjustment event is fired. Similarly, if the user clicks the
adjustable object to view a previous line, a UNIT-DECREMENT adjustment event is fired.
Finally, an adjustable object may allow the user to continuously adjust the value (e.g., to
smoothly scroll through the document). In this case, the adjustable object fires TRACK adjusb
ment events.
Adjustment Event Flow
Figure 16 shows how adjustment events typi-
cally flow through the system. First, the event
is fired by a component peer in response to
some user gesture- This event is posted on the
event queue (see EventQueue). When the
event makes its way to the front of the queue,
it is given to the component via its dispatch-
EventO method. The main purpose of this
method is to discard the event if the adjustment
event type is not enabled or if there are no
adjustment event listeners. Otherwise, the
dispatchEventO method calls process-
EventQ, which in turn calls different meth-
ods depending on the event type. Since this is
an adjustment event, processAdjustment-
EventQ is called. The main purpose of this
method is to notify adjustment event listeners.
A component can override processAd-
justmentEventO to process adjustment
Adjustable I processEventО
I
^processAd jus tme nt Event C)
I
On
AdjustmentListener /л U
uo
FIGURE 16: Adjustment Event Flow.
events before they are delivered to its listeners. The overridden method should call
super.processAdjustmentEventQ to ensure that events are dispatched to the component's
listeners
SUMMARY
Constructor
AdjustmentEventО
Property Methods
getAdjustableO
getAdjustment!ype()
getValueO
Constructs an AdjustmentEvent instance.
Retrieves the adjustable object that fired this event.
Retrieves the adjustment event's adjustment type.
Retrieves the adjustment event's value.
Continued
AdjustmentEvent
java.au (.event
1 MEMBER SUMMARY
1 Adjustment Event Id Constants । ADJUSTMENT-FIRST Constant specifying the first id in the range of adjustment event ids.
| ADJUSTMENT_l.AST Constant specifying the last id in the range of adjustment event ids.
1 ADJUS7MENT_VAl.Uf-_CHANGED ' Adjustment Types । BLOCK-DECREMENT | BLOCK-INCREMENT TRACK I UNIT-DECREMENT । UNIT-TNCREMENT Event id indicating that an adjustment event occurred. Adjustment type indicating a block decrement. Adjustment type indicating a block increment. Adjustment type indicating a tracking change. Adjustment type indicating a unit decrement. Adjustment type indicating a unit increment.
| Debugging Method paramStringQ Generates a string representing the adjustment event's state
See Also
AdjustmentListener, java.awt.Adjustable, java.awt.AWTEvent,
java.awt.Component.dispatchEventQ, java.awt.Component.processEventQ ,
j ava.awt.Scrol1 bar, j ava.awt.Sc rol1 Pane.
Example
This example demonstrates how to gel adjustment events
from a component that fires them. ITie example creates a
horizontal scrollbar and listens for adjustment events
from the scrollbar. In response to an adjustment event,
the specifics of the event are printed. Sec Figure 17.
For an example of how to create a component that
fires adjustment events, see Adjustable.
< AdjustmentEvent ... BUSES
я I
11ИЙ»Щ||»|Г I I . SMiDimJI .....*.....
FIGI RE 17: AdjustmentEvent.
import java.awt.-;
import java.awt.event;
class Main extends Frame implements AdjustmentListener {
Main О {
super("AdjustmentEvent Example”);
Scrollbar sb = new Scrol1bar(Scrol1 bar-HORIZONTAL);
// Listen for adjustment events.
sb.addAdjustmentListener(thi s);
add(sbt Border!ayout.CENTER);
pack();
лин,э i jvjc.\ i _пкэ i
show();
}
public void adjustmentVal ueChanged(AdjustmentEvent evt) {
System.out .printlnC'adjustable: ”+evt .getAdjustableO);
switch (evt.getAdjustmentlypeO) {
case AdjustmentEvent.BLOCK-DECREMENT:
System.out.pri nt("BLOCK-DECREMENT");
break;
case AdjustmentEvent.BLOCK-INCREMENT:
System, out.printCBLOCK-INCREMENT’1);
break;
case AdjustmentEvent.TRACK:
System.out.print("TRACK") ;
break;
case AdjustmentEvent.UNIT_DECREMFNT:
System.out.print("UNIT.DECREMENT") ;
break;
case AdjustmentEvent.UNIT.INCREMENT:
System, out. print("UNIT_INCREMENT'') ;
break;
}
Systern.out.println(" ("+evt. getVa^ue()+,,),,) ;
}
public static void main(String args[J) {
new Mai л();
}
ADJUSTMENTF1RST
PURPOSE- Constant specifying the first id in the range of adjustment event ids.
SYNTAX public static final int ADJUSTMENT-FIRST
description ЛП adjustment event ids must be greater than or equal to ADJUSTMENT-FIRST (value 601).
SEE Al .SO ADJUSTMENT-LAST.
example See java,awt.Component,processEvent().
ADJUSTMENT. LAST
PURPOSE Constant specifying the last id in the range of adjustment event ids.
SYNTAX public static final int ADJUSTMENT-LAST
description All adjustment event ids must be less than or equal to ADJUSTMENT-LAST (value 601).
AdjustmentEvent java.awt. event
A DJL’STMENl^Al J’EJ.'ll A NG ED
SLI. also ADJUSTMENT-FIRST.
lwmpi l See java.awt.Component.processEventО.
ADJUSTMENT, VALLE CHANGED
pl kpost Event id indicating that an adjustment event occurred.
SYMax public static final int ADJUSTMENT.VALUE.CHANCED
description All scrollable objects in the AWT fire adjustment events with this id (value
601).
sei ai so AdjustmentEvent().
i xampi t See the j ava. awt. Scrol 1 Pane class example.
AdjustmentEventO
J Pl RPOSP Constructs an AdjustmentEvent instance.
к S\ XI \X public AdjustmentFvent(Adjustable source, int id, int adjType,
L M N 0 P Q R S 1 Is DES< RII’TION PARAMETERS adjType int value) This constructor constructs a new adjustment event instance with source as the object firing this event, value is the new value of the adjustable object source. At present, there is only one adjustable event id. so id must be set to ADJUSTMENT_VALUE_CHANGED. After the adjustment event is created, the source object can distribute the event to its listeners by calling AWTEventMulticaster.adjustment- ValueChangedO If the event is not created by source, the creator can deliver the event to the source component either by posting the event to the event queue (see EventQueue. postEvent()) or bv calling the source compo- nent's Component .di spatchEventQ method directly. One of the adjustment types.
V' id Must be ADJUSTMENL VALUE-CHANCED.
w source val ue I‘he non null adjustable object that is firing this adjustment event. fhe new value that must be in the range source.getMinimumO and
X Y SEE ALSO source. getMaximumO. ADJUSTMENT_VALUt_CHANCFD, BLOCK-INCREMENT, BLOCK-DECREMENT,
7. EX AMPLE getAdju stable О , getValueO , java. awt .AWTEvent .getTDO , java.uti1.EventObject.get Source 0, TRACK, UNIT„DECREMENT, UNIT-INCREMENT. See the java .awt. Scrol 1 Pane class example.
66
BLOCKJJECREMENT
PURPOSE Adjustment type indicating a block decrement.
SYNTAX public static final int BLOCK_DECREMENT
description Л block is typically associated with a page in a document. Therefore, if the user clicks the adjustable object to view the previous page, a BLOCK-DECREMENT (value 3) adjustment event is fired. The new value of the adjustable object can be retrieved with getValue().
SEE ALSO BLOCK-INCREMENT, getAdjustmentTypeQ, TRACK, UNIT-DECREMENT, UNIT-INCREMENT.
example-: See the class example.
BLOCK-INCREMENT
PURPOSE Adjustment type indicating a block increment.
SYNTAX public static final int BLOCK^INCREMENT
DESCRIPTION A block is typically associated with a page in a document. Therefore, if the user clicks the adjustable object to view the next page, a BLOCK-INCREMENT (value 4) adjustment event is fired. The new value of the adjustable object can be retrieved with getValueO.
SEE ALSO BLOCK. DECREMENT, getAdjustmentTypeQ , TRACK, UNIT.DECRFMENT, UNIT-INCREMENT.
EXAMPLE See the class example.
getAdjustableO
PURPOSE Retrieves the adjustable object that fired this event.
SYNTAX public Adjustable getAdjustableO
DESCRIPTION This method returns the adjustable object that fired the adjustment event. This is the same object returned by Eventobject .getSource().
RETURNS A non-nul 1 adjustable object.
SEE ALSO java.uti1.Eventobject.getSourceО
example See the class example.
AdjustmentEvent
getAdjustmentTypeO
java. awt.c vent
В
С
D
E
F
G
H
I
J
К
L
M
N
getAdjustmentTypeO
pi rpose Retrieves the adjustment event’s adjustment type.
syntax public int getAdjustmentTypeO
description The adjustment type describes how the adjustable's value was changed. See the
class description for more details.
Rim r\s One of the five adjustment types.
SEI Also BLOCK.DECREMENT, BLOCK.INCREMENT, TRACK, UNIT-DECREMENT,
UNIT-INCREMENT.
exampi i See the class example.
get Value()
purpose Retrieves the adjustment event's value.
svntax public int getValueQ
description The value property of an adjustment event holds the new value of the adjust
able object. This value will always be within a range that's associated with the
adjustable object. See the Adjustable interface for more details.
returns The adjustment event's value.
F.XAMPI f See the class example.
paramStringO
pi rpose Generates a siring representing the adjustment event's state.
syntax public String paramStringO
description The returned string contains the name of the adjustment type and the value. A
subclass of this class should override This method and return a concatenation of
its state with the results of super .paramStri ng(). This method is called by
the AWTEvent.toStringО method and is typically used for debugging.
returns A non-null string representing the adjustment event's state.
overridi s java.awt.AWTEvent.paramStri ngО•
see м so java.awt.AWTEvent.toStri ng(), java.lang.Object.toStri ng О
example. See the j ava. awt. AWTEvent class example.
68
TRACK____________________________
purpose Adjustment type indicating a tracking change.
syntax public static final int TRACK
description An adjustable object may allow the user to continuously adjust the value (e.g..
to smoothly scroll through the document). In this case, the adjustable object B
fires TRACK (value 5) adjustment events. The new value of the adjustable
object can be retrieved with getVal ueQ.
SEE ALSO BLOCK_DECREMENT, BLOCK INCREMENT, getAdjustmentTypeQ,
UNIT-DECREMENT, UNIT-TNCREMLNT. Г
example See the class example. F
G
UNITJJECREMENT
----------- (
purpose Adjustment type indicating a unit decrement.
SYNTAX public static final int UNIT-DECREMENT
К
description A unit is typically associated with a line in a document. Therefore, if the user
clicks the adjustable object to view the previous line, a UNIT-DECREMENT
(value 2) adjustment event is fired. The new value of the adjustable object can M
be retrieved with getValueQ. N
SEEALSO BLOCK-DECREMENT, BLOCK INCREMENT, getAdjustmentTypeQ , TRACK,
UNIT-INCREMENT.
example See the class example. *
Q
R
UNIT INCREMENT
—----=___________ s
purpose Adjustment type indicating a unit increment. T
SYNTAX public static final int UNIT-INCREMENT L’
description A unit is typically associated with a line in a document. T herefore, if the user V
clicks the adjustable object to view the next line, a UNIT_INCREMENT (value 1)
adjustment event is fired. The new value of the adjustable object can be
retrieved with getValueQ. X
SEEALSO BLOCK-DECREMENT, BLOCK-INCREMENT, getAdjustmentTypeQ, TRACK, Y
UNIT_DECREMFNT.
Z
example See the class example.
Syntax
public interface AdjustmentListener extends EventListener
Description
When an object (listener) wishes to receive adjustment events from an adjustable object (the
source object), two things must be done:
1. The listener must implement this interface and the adjustmentValueChangedO
method required by this interface.
2. Fhe listener must be registered with the source object by making a call to the source
object's addAdjustmentLi stener() method.
In the AWT, both the Sc roll bar and Scroll Pane components generate adjustment
events (more accurately, the Scrol 1 Pane component has two adjustable objects that generate
the adjustment events). See AdjustmentEvent for more information about adjustment events
Adjustment Event Callback Method
adj ustmentValueChanged()
Called after the value of an adjustable object changes.
See Also
AdjustmentEvent, java.awt.Adjustable, java.awt.AWTEvent,
java.awt.AWTEventMulti caster, java.awt.Scroll bar, java.awt.Scrol1 Pane,
java.uti1.EventLi stener.
Example
This example implements a happy/
sad face meter. The scroll bar is
used to adjust the happiness/sad-
ness of the face. See Figure 18.
The class Face has a
setSmileO method that takes a
real number from 0 to 1. The higher
the value, the happier (he face. The
lower the value, the sadder the face.
import java.awt.*;
import java.awt.event
FiGVRfc 18: AdjustmentLi stener.
public class Main extends
Frame implements Adjustment!.!stener {
Scrollbar sb ₽ new Scrollbarf
Scrol1 bar.HORIZONTAL, 99, 1, 0t 100);
Face face - new FaceO;
Main() {
superC’AdjustmentListener Example”);
// Listen for events
sb.addAdjustmentListener(this);
// Layout components
addfface, BorderLayout.CENTER);
addfsb, BorderLayout.SOUTH):
setsize(300, 300):
show();
}
// Handle adjustment events.
public void adjustmentValueChanged(AdjustmentFvent evt) {
face.setSmile((evt.getValue()-50)/50.0);
}
Adjustment! Jstener
jax a.awt.eveni
public static void main(String args[j) {
new Mai nO;
}
}
class Face extends Component {
double smile = 1.0;
public void paint(Graphics g) {
int size - getSize().width;
// Keep it square
if (size > getSizeO .height) {
size - getSizeO-height;
J
// Paint yellow.
g.setColor(Color.yellow);
g.fi1lOval(0. 0» size-1, size 1);
// Paint outline
g.setColor(Color.black);
g.drawOval(0, 0, size-1, size-1);
g.drawOval(1, 1, size-2, size-2);
// Paint eyes.
int eyew - (int)(size * .18);
int eyeh Math.abs((int)(size * .36 smile));
g.fi1lOval(size/3-eyew/2, size/3~eyeh/2, eyew, eyeh):
g.fi1lOval(size*2/3-eyew/2, size/3-eyeh/2f eyew, eyeh;
// Paint mouth.
int mouthw - size/3+eyew;
int mouthh = Math.abs((int)(size ’• -4 * smile));
int startAngle - smile < 0 ? 0 : 180;
int mouthy - size'2/3-mouthh/2;
// If frown, move rectangle lower.
if (smile < 0) {
mouthy += mouthh/2;
}
g.drawArc((size-mouthw)/2, mouthy, mouthw, mouthh,
startAngle, 180);
g.drawArc((size mouthw)/2, mouthy+1, mouthw, mouthh,
startAngle, 180);
}
// -1.0 is a frown; 1.0 is a smile.
public void setSmile(double smile) {
this.smi1e = smile;
repai nt();
}
}
72
adjustmentValueChangedO
PURPOSE Called after the value of an adjustable object changes.
SYNTAX public void adjustmentValueChangedfAdjustmentEvent evt)
DESCRIPTION This method is called after the value in the source adjustable object changes. В
PARAMETERS evt В The non-null adjustment event.
EXAMPLE See the class example. D
E
F
G
H
I
J
К
L
M
N
О
P
Q
R
S
T
и
V
w
X
Y
Z
java.applet
Applet
Syntax
G public class Applet extends Panel
H
( Description
J Applets and Applet Contexts
K An applet is basical К a specialized panel (sec Panel) that is embedded in a specialized com-
ponent container called an applet context. An applet context can be a Web browser or other
L type of application that can display applets. It can contain more than one applet. An applet
M implements a number of methods that the applet context calls when it wants to initialize, start,
stop, or destroy the applet. An applet also has access to a number of methods for retriev ing
resources such as images and audio clips based on L'RLs. Although these methods do not pro-
O vide any more functionality that is available by other Java classes, they have been specially
p designed to be convenient to use by an applet. An applet can also access applet context infor-
mation, such as the URL of the document containing the applet and, in some cases, control the
applet context, such as to display a status message.
R
Handling Events and Painting
S An applet is a subclass of Panel, so you handle events in an applet just as you do events in a
T component. See the Component and AWTEvent classes for more information on event han-
L! dling. Similarly, an applet paints itself in exactly the same way that a component paints itself.
That is, it overrides the pal nt О and update () methods. See the Component class for more
v information.
W As a subclass of Panel, an applet can hold embedded components. The default layout
manager of an applet is a flow layout (see FlowLayout).
Y
74
FIGURE 19: Applet Transitions.
States
An applet can be in an active
or inactive state. When the
applet is first loaded, it is in
the inactive state. When the
applet is first displayed on the
screen, it becomes active. The
applet then moves between
the active and inactive slates
until it is destroyed by the
applet context. Exactly what
causes the applet to become
active or inactive is up to the
applet context. For example, the applet context might decide to make the applet inactive if the
applet is scrolled out of view. Or it might make the applet inactive if the user views another
document and leaves the document with the applet. Or it might make the applet inactive if the
user clicks a special button. Figure 19 shows the transitions that an applet can go through.
Creating an Applet
An applet is created by declaring a class that extends from the Applet class. The applet then
overrides one or more methods to implement the behavior. There are only six methods that can
be overridden, any of which are optional: destroyO, irritO. startO. stopO, get-
AppletlnfoC), and getParameterlnfoO. The initO method is called just after the applet
is loaded. The startO method is called just after the applet becomes active. The stop()
method is called just after the applet becomes inactive. The destroy О method is called just
before the applet context destroys the applet. The getAppletlnfoO and getParameter-
lnfoO methods return some textual information about the applet and are typically called by
the applet context when the user wants to display the information.
Serialization of an Applet
An applet can be serialized and reconstituted from its serialized form to create another instance
of the applet. After an applet context reconstitutes an applet, it invokes startO on it. Since
the applet context calls startO directly, the applets initO. startO. and stopO methods
should have been called, in that order, before the applet was serialized, thus ensuring that the
applet is in the stopped state when it gets reconstituted. See the description of the object
attribute in Table 2 for details on serialized applets.
Code and Document Bases
An applet can fetch resources by way of a URL object. If it is desirable to fetch the applet
using a relative URL, (hen there are two prefixes available to the applet: code base and dot io
went base. The code base is the URL prefix that contains the applet code. For example,
suppose an applet were located at http://www.sun.com/applets/Main.class. The
Applet
java.applet
В
C
D
code base would be http://www.sun.com/applets/. The code base is typically used to
fetch resources specific to the applet, such as icons and configuration information.
The document base is the URL prefix that contains the document that contains the applet.
For example, suppose the document containing the applet were located at http:
//www. sun. com/products/sparcstation/index .html. The document base would be
http://www.sun.com/products/sparcstation/. The document base is typically used to
fetch resources specific to the document. For example, if sonic animation was designed for a
particular HTML document, the animation images would typically be located somewhere rela-
tive to that document.
E
F
(i
H
I
J
К
I.
M
N
О
P
Q
R
s
Г
t;
v
w
X
Y
Z
Archives
A single applet may consist of multiple class files and may make use of resources such as
images and audio clips, A network connection is created to download each of these files and
resources when the applet or applet context needs one of these files. To improve download
time, you can package all of the class It les and resources needed by the applet into one or more
archives. An archive is downloaded using a single network connection. Subsequent requests
for files and resources are satisfied by using the contents of the archives. If the flies or
resources are not in (he archives, they are downloaded by creating new netw'ork connections.
Java Archive (JAR) specifies a platform-independent file format for archives. The Java
archive tool, jar. available on Solaris and Windows platforms, allows you to create a JAR
archive using multiple class and resource (such as image and sound) files.
See http://java.sun.eom/products/jdk/l.l/docs/guide/jar/ for details on JAR
and the jar command.
Digests and Signed Applets
JAR allows you not only to package multiple files into a single archive for quicker downloads,
but also to sign or provide a digest of individual files within the archive. This allows the applet
context (either a browser or applet viewer) to verify the integrity of individual files and/or
determine the identity of the supplier of the file.
A message digest algorithm accepts a sequence of bytes and produces a compact represen-
tation of it, called a digest. You cannot reproduce the original stream of bytes from the digest,
but you can use the digest to verify whether a sequence of bytes has been modified (by recal-
culating the sequence’s digest and comparing it with the original digest). Popular message
digest algorithms supported by JAR include MD5 and SHA. A single file can have both MD5
and SHA digests.
Supplying a digest with a file al low's the receiver of the file to verify its integrity. How-
ever. someone could have substituted both the file and its digest, thereby providing to the
receiver information different from what was intended by its supplier. JAR also provides sup-
port for signing individual files within an archive. Signature specifications supported by JAR
include RSA, DSA. and PGP. Using one of these algorithms, the sender can “sign" the file
with a digital signature. The signed file contains information that can subsequently be used to
verify the identity of the signer.
76
Parameters
An apple! context can pass parameters to an applet. Parameters are simply string names associ-
ated with an arbitrary string value. The applet retrieves a parameter using the getParame-
terO method.
The Applet HTML Tag
Two HTML tags are used to embed an applet in an HTML document: <applet> and <param>.
The two tags are typically used as follows:
<applet name=Main codebase-http://www.sun.com code=Main width-300 height-200>
<param name=namel va 1 ue=”valuel,,>
<param name=name2 value-r'val ue2 ">
<param name=name3 value-"value3”>
If you don’t have a lava enabled browser ... get one.
<a href="http://www.sun.com"><IMG SRC=”javacup.gif" height^60 width=60 alt-”get
Java"x/a>
</applet>
A Java-enabled browser recognizes the <applet> tag and interprets everything up to the
</app1et> tags. Between the <applet> and </applet> tags, it recognizes only <param>
tags and ignores every thing else. A non-Java-enabled browser ignores the <appl et>.
</applet>, and <param> tags and interprets everything else. In this way. you can set up an
HTML document that serves up the Java applet in a Java-enabled browser and displays some-
thing else for a non-Java-enabled browser. Table 2 lists the attributes of the <applet> and
<param> tags.
Mandatory Attributes of the <applet> Tag
code Specifies the class name or class filename of the applet. The code tag specifies only
the name of the class file and cannot contain any pan of the path to the class file.
The class file is in the directory specified by the codebase tag or in one of the
archive files specified by the archive tag.
Hither the code attribute or the object attribute must be present. If both attributes
are present, the object attribute is ignored.
height Specifies the initial height in pixels of the applet’s display area.
Continued
TABLE 2: Attributes of the <applet> and <param> Tags.
Applet
java.applet
object Specifies» the filename containing the serialized applet. The browser or applet
viewer runs the applet by first deserializing it and then invoking the startO
method. Note that the initO method will not be invoked on it. so before serial
izing the applet, you must first call initO on the applet and then call start ()
and stopO on it. Any attributes or parameters available to the original applet
before it was serialized are not available to this applet. This applet has access
only to the attributes and parameters available to this instance ot the applet.
The file is in the directory specified by the codebase tag or in one of the archive
files specified by the archive tag.
Either the code attribute ortho object attribute must be present. If both attributes
are present, the object attribute is ignored.
width Specifies the initial width in pixels of the applet's display area.
Optional Attributes of the <applet> Tag
al i gn Specifies the alignment of the applet. Its possible values are left, right, top. lexttop.
middle, absmiddle. baseline, bottom, and absbottom.
al t Specifies the text to display if the browser understands the appl et tag but foi
some reason cannot run Java applets.
archive Specifies a comma separated list of archive files in JAR formal. Each archive file
contains classes and other files (such as images and audio files) used by the
applet. The archive files arc in the directory* specified by the code base attribute.
code base Specifics the applet's code base. T’his base can be either any absolute I RL or a
URL relative to the document containing the applet. This attribute is optional
and defaults to ‘'."(the same directory as the document).
Applets that use the same codebase attribute share the same classloader.
hspace Specifies the horizontal space on the left and right sides of the applet.
name Specifies the name of the applet. An applet can name itself, thereby allowing other
applets to retrieve a reference to it. This attribute is equivalent to specifying a
parameter with the name "name". Therefore an applet can retrieve its name by
calling get Parameter (’'name'1). This attribute is optional and defaults to null.
vspace Specifies the vertical space on the top and bottom of the applet.
Attributes of the <param> Tag
name Specifies the name of the parameter. The name must be different from the names of
other parameters in the same pair of <applet> and </applet> tags. This attribute
is mandatory. A special parameter called "name" is automatically supported by all
applet contexts and is the name of the applet. There are two ways to name an
applet: through the name attribute of the applet tag or by specifying a parameter
called "name".
value Specifies a siring that is associated with the parameter name. T’his attribute is man-
datory.
TABLE 2: Attributes of the <applet> and <param> Tags.
78
Ml IT'”' — —
Methods to Override destroyO initO startO stopO getParameterlnfoO getAppl etlnfoO Called by the applet context to destroy the applet. Called by the applet context just after the applet is loaded. Called by the applet context just after the applet is made active. Called by (he applet context just after the applet is made inac- tive. Retrieves information about parameters that the applet recog- nizes. Retrieves a string containing information about the applet.
State Method isActiveO Retrieves the active state of the applet.
Audio and Image Methods getAudioClipO getlmageO pl ay Q Retrieves an audio clip from a URL. Retrieves an image at a URL. Fetches and plays an audio clip.
Parameter Methods
getCodeBaseO
getDocume nt Base()
getParameterO
Applet Context Methods
getAppletContext()
showStatus()
Locale Method
getLocaleO
Size Method
resizef)
Stub Method
setStub()
Retrieves the applet s code base URL.
Retrieves the applet’s document base URL.
Retrieves the value of a parameter.
Retrieves the applet context.
Displays a message in the applet context.
Retrieves this applet’s locale.
Resizes the bounds of the applet.
Sets the applet’s stub.
Example
This example implements a game. The goal is to catch duke while he’s jumping around. If you
catch him, he plays a sound. You also can drag him around. If the applet is active, the game
plays some background music using the loop() method so that it plays continuously until
stopped. All the images and sounds are fetched relative to the document base. See Figure 20.
Applet
java, applet
A
_______
В
c
D
1:
F
G
H
I
J
К
L
M
\
О
A button is created and embedded in
the applet. If you click the button. getAp-
pletContextO -showDocument () is
called to display the source code. Since the
source code is typically located with the
compiled applet code, getCodeBaseO is
used to locate the source code.
To eliminate flashing, the applet first
paints the duke image into a second buffer
and then displays the second buffer on the
screen. To keep things simple, the applet
paints the entire buffer every time Duke
moves. It is much more efficient to paint
only the parts of the image that have
changed.
The following is the HTML source lor
' Applet Viewer: Main
Applet
Click to see source for this applet |
Applet started.
FIGI KE 20: Gatch Duke Applet.
files, and audit» files.
the applet. It uses an archive file main. jar to store the class files, image
<applet name-’'Appl et Ixample” code-Main archi ve-riai n. jar width-200 height-100>
<param name-image value-duke. gif>
<param name-audio value-oww.au>
<param name-bg-audio value=bgmusic,au>
<param name-delay value=1000>
<param name-source value=Main.java>
</applet>
The following is the source for the applet:
P import java. appl et. ;
import java.awt. ••;
Q import java.awt.event.•;
import java.net.--;
R
public class Main extends Applet implements Runnable, Actionlistener {
S Image backBuffer: // image for double-buffering.
Graphics backBufferG; // graphics context for double-buffer.
T
AudioClip bgAudio;
[J Image image:
int imageX, imageY; // current position of image.
V
// Applet State Methods
W public void init() {
backBuffer = createlmage(400, 200);
X backBufferG - backBuffer.getGraphics();
Y // load resources
image - getImage(getDocumentBase(), get Parameter(“image”));
7 bgAudio - get AudioC 1 ip(getDocurrentBase() , getParameter(“bg-audio”));
Button b - new Button("C1ick to see source for this applet”):
b. addActi onLi stener(t hi s):
80
add(b);
resize(400, 200);
}
public void startO {
startTickThread(true);
bgAudio. loopO;
}
public void stopO {
startTickThread(false);
bgAudio. stopO;
}
public void destroyO {
backBufferG,dispose(); // get rid of the double buffer.
backBuffer.flush();
image. flushQ ;
}
// Paint Methods
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
int w = getSize().width;
int h = getSizeO • height;
// Create the double-buffer if needed or enlarge.
if (backBuffer null
I I backBuffer.getWidth(this) <w
।I backBuffer.getHeight(this) < h) {
backBuffer = createlmage(w, h);
backBufferG = backBuffer.getGraphics() ;
}
backBufferG.clearRect(0, 0, w, h);
backBufferG.drawlmage(image, imageX, imageY, this);
g.drawlmage(backBuffer, 0, 0, this);
}
// Event listeners
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
int x = evt.getXO, у = evt.getYO;
if (x > imageX && x < imageX + image.getWidth(Main.this)
&& у > imageY && у < imageY + image.getHeight(Main.this)) {
startTi ckThreadffalse);
imageX = x-image.getWidth(Main.this)/2;
imageY - y-image.getHeight(Main.this)/2;
getAppletContext О.showStatus(“OWWW! Ya got me! Let go!”);
pl ay(getDocument BaseО, getParamet er(“audio”));
repaintO ;
}
}
public void mouseReleased(MouseEvent evt) {
if (tickThread == null) {
startTickThread(true);
Applet
java.applet
getAppl etContextC). showStatus(“Nah, Nah ! ”) ;
}
}
}
class MouseMotionFventHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent evt) {
int x evt.getXQ, У = evt.getYO;
if (tickThread null) {
imageX = x-image.getWidth(Main.this)/2;
imageY - y-image.getHeight(Mai n. thi s)/2;
repai nt () ;
}
г
// Called when the “See Source'* button is pressed.
public void actionPerformed(ActionFvent evt) {
try {
getAppletContext().showDocument(new URL(getCodeBase(),
getParameter("source”))):
} catch (MaiformedURlExcept ion e) {
e.printStackTraceO;
}
}
// Tick Thread Methods
Thread tickThread;
void startTickThread(bool ean start) {
if (start) {
tickThread -= new Threadfthi s) ;
t i ckThread. startO :
} else {
tickThread null;
}
}
public void run() {
int delay = Integer.parselnt(getParameter(“delay'*));
while (Thread. currentThreadO tickThread) {
try {
imageX - (int)Math.floor(Math.random()*getSize().width);
imageX = Math.min(imageX,
getSi ze().width-image.getWidth(this));
imageY - (int)Math.floor(Math. randomO •getSizeO . height) ;
imageY = Math.min(imageY,
getSize().height-image.getHeight(this));
repaint() ;
Thread.sleep(del ay);
} catch (Interruptedfxception e) {
1
}
}
public String getAppletTnfo() {
return "Patrick Chan and Rosanna Lee (c) 1997”;
}
StringnCl parameterTnfo - {
{"image”, “document-based url”, “image to move around”},
82
{“audio”, “document-based url", “sound to play when image is hit”},
{“bg-audio”, “document-based url”, “background music”},
{“audio", “code-based url", “sound to play when image is hit"},
{“delay”, “integer”, “delay between moves in milliseconds"},
};
public String[][] getParameterlnfoO {
return parameterinfo;
}
}
destroyO ____________________________________________
PURPOSE Called by the applet context to destroy the applet.
SYNTAX public void destroyO
DESCRIPTION lliis method is called by the applet context when it decides to destroy the applet. This may occur if the applet context is low on space or when it exits. A subclass should override this method if it needs to dispose of any resources created by the applet. For example, if the applet creates a thread to do some background work, this method should be overridden so as to destroy the thread. If an applet is active, the applet context will always call the stopO method before calling the destroyO method.
SEE ALSO stopO.
EXAMPLE See the class example.
getAppletContext()
PURPOSE Retrieves the applet context.
SYNTAX public Appletcontext getAppletContextO
DESCRIPTION See the class description for more information about the applet context.
RETURNS The non-null reference to the applet context.
SET Al^() AppletContext.
example See the class example.
getAppletlnfoC)
PURPOSE Retrieves a string containing information about the applet.
Applet
get AudioCI ip()
java.applet
syntax public String get Appl etlnfoO
description This method can be overridden by an applet to return information about itself
This returned string typically includes information about the author, version,
and copyright.
retcrns A possibly nul 1 string containing information about the applet.
ex am pi I- See the class example.
I)
, getAudioClipO
F pl rpc>st: Retrieves an audio clip from a URL.
Ci SYNTAX public AudioClip getAudioClipCURl url)
H public AudioClip getAudioClip(URl url, String name)
1 DESCRIPTION This method retrieves an audio clip at the URL url. If name is specified, the audio clip is fetched from a new URL created by appending name to url.
J PARAMETERS
к name The non-nul 1 name to append to u rl.
L url The non-nul 1 URL at which to fetch the audio clip.
returns The audio clip at url, Returns nul 1 if the audio clip cannot be found.
see ai so AudioClip, java.net.URL,
fxampi f See the class example.
P
q getCodeBasef)
К pl rpose Retrieves the applet's code base URL.
syniax public URL getCodeBaseO
1 nt scripri(in The code base is the URL prefix that contains the applet code. For example.
I suppose an applet were located at http://www.sun.com/applets/
Mai n .class. The code base would be http://www.sun.com/applets/. The
V
code base is typically used to fetch resources specific to the applet, such as
icons and configuration information.
X REII RNS The non-nu 11 applet’s code base URI
Y SEE ALSO getDocumentBaseQ , java.net.URI.
/ EXAMPLE See the class example.
84
11 ДА, U111и I > I onset J
getDocumentBase()
PURPOSE Retrieves the applet's document base URL.
SYNTAX public URL getDocumentBase()
DESCRIPTION The document base is the URL prefix of the document that contains the applet. ® For example, suppose the document containing the applet was located at http://www.sun.com/products/sparcstation/index.html. The docu- ment base would be http://www.sun.com/products/sparcstafion/. The document base is typically used to fetch resources specific to the document. For example, if some animation was to be designed for a particular HTML document, the animation images would typically be located somewhere relative to that document.
SEE ALSO getCodeBaseO, java. net. URL.
EXAMPLE See the class example.
getlmageO
PURPOSE Retrieves an image at a URL.
SYNTAX public Image get!mage(URL url) public Image getImage(URL url, String name)
DESCRIPTION This method retrieves an image at the URL url. If name is specified, the image is fetched from a new URL created by appending name to url. This method returns immediately and does not actually fetch the pixels of the image. The pixels are fetched at the time they are needed (see Image). As long as the image is found, the return image reference will not be null. However, an error may occur while loading the image. To check for errors, use the Component .checkimage0 method call.
PARAMETERS name url The non-null name to append to url. The non-null URL al which to fetch the image.
RETURNS The image at url. Returns nul 1 if the image cannot be found.
SEE ALSO java.awt.Image, java.awt.Component.checklmage(). java.net.URL
example See the class example.
getLocalc()
purpose Retrieves this applet's locale.
Applet
get Parameter )
java.applet
L SYNTAX REILRNS public Locale getLocale() This method returns this applet's locale or the locale of its closest ancestor with a locale. If this applet does not have its own locale and it does not have an ancestor from which to get the locale, the default locale (Locale.getDe-
Л И faultO) is returned.
ГВ RETURNS The applet's non-nul 1 locale.
c OVERRIDES java.awt.Component.getLocaleQ.
D SEE ALSO java.awt.Component.setLocaleO T java.util.1ocale.getDefault().
E EXAMPLE See j ava. awt. Component. getName(.).
G getParameter()
н '
purpose Retrieves the value oi a parameter.
1
syntax public String getParameter(String name)
J
description See the class description about applet parameters and the param HTML tag.
К
PARAMETERS
1 name The non-nul 1 name of the parameter value to retrieve.
M returns Returns the value of the parameter; otherwise» it returns null if the parameter
К does not exist.
О example See the class example.
Q getParameterlnfof)
R
Pt RPOSE c? Retrieves information about parameters that the applet recognizes.
Л SYNTAX T DESCRIPTION L public String[][] getParameterlnfoO This method is called by the applet context when it needs to display informa- tion about the applet parameters. This method returns an array of string arrays
V containing the desired information. Each parameter is described using three
w strings: the name of the parameter, the type of the parameter value (which is an
V¥ X RETURNS Y arbitrary string), and a short description of the parameter. A possibly null array of string arrays containing information about the applet parameters.
Z EXAMPLE The getParameterlnfoO method in this example describes an applet that displays an image and a message under the image:
86
String[][] parameterinfo {
{"location", "x y",
’’the location to display the image"},
{"image", "url",
"the location of the image"},
{"message", "string",
"the message to display under the image"},
public String^] [] getParameterlnfoO {
return parameterinfo;
}
initO
PURPOSE Called by the applet context just after the applet is loaded.
SYNTAX public void initO
DESCRIPTION A subclass should override this method if it needs to implement behavior that occurs before the applet becomes active for the first time. For example, if the applet needs a background thread to do some work regardless of the applet's state, then this method should be overridden to create the thread.
SEE: ALSO destroyO.
EXAMPLE See the class example.
isActive()
PURPOSE Retrieves the active state of the applet.
SYNTAX public boolean isActiveO
description An applet becomes active just before the startO method is called and becomes inactive just before the stopO method is called.
RETURNS true if the applet is active; false otherwise.
SEE ALSO startO.
example This example implements an applet that fetches a list of images. See Figure 21. A fetcher thread is created when the applet is loaded. When the fetcher thread finishes fetching an image, it calls repai nt О to update the display, but only if the applet is active. Otherwise, it avoids calling repai ntO and continues fetching images. The list of images to fetch are supplied through the parameters. The applet looks for parameter names of the form image/V, where N starts at 0. Once a parameter name doesn’t exist, the applet stops looking and assumes that all of the images have been specified.
java.applet
Applet
isActivei)
В
C
L>
E
F
G
fl
I
J
К
L
M
N
О
P
Q
R
S
T
г
V
import java.applet . ;
import java, awt/-;
public class ^ain extends Applet
implements Runnable {
St ring J imagesToFetch;
Image[3 fetchedlmages;
int fetched; // number of fetched images.
Thread fetcherThread;
// Applet State Methods
public void init() {
int i = 0;
while (getParameter(Mimage”+i) 1- null) {
i ♦ +-;
}
imagesIoFetch - new String[i];
fetchodlmages - new Image[i];
if (i >0) {
fetcherThread - new lhread(this);
f etcherThread. startO ;
}
for (i=0; i<imagesToFetch.length; i + + ) {
image$Tof-otch[i 1 =
getParameter(‘‘image”+i);
}
resize(200, imagesToFetch.length 70);
J
public void destroyO {
fetcherThread - null;
}
* Applet Vie .. BUsIlS
Applet
t'-\!
Л’
ЛГ
I-J
dukeO gif
dukel gif
duke2.gif
duke3 gif
Applet started
HGIRE21:
Fetch Image Applet.
// Paint Methods
public void paint(Graphics g) {
int w - getSize().width;
int h - getSize().height;
TontMetrics fm - g.getFontMetrics();
int у - 0;
for (int i-0; icimagesToFetch.length; i4+) {
if (i < fetched) {
g.drawlmage(fetchedlmages[i], 0, y. 50, 50, this):
1
g.drawString(imagesToFetch[i], 60, у * fm.getAscent());
у +- 70;
}
J
X
Y
Z
public void run() {
while (Thread.currentlhreadQ -- fetcherThread
&& fetched < imagesToFetch.1ength) {
try {
fetchedlmages[fetched]= getlmage(
getDocumentBasoO , imagesToFetch[fetched]);
while (!preparelmage(fetchedlmages[fetched;, this)) {
Thread.sleepC?000);
88
}
fetched++;
if (isActiveO) {
repaintО;
}
} catch (InterruptedException e) {
}
playO
purpose Fetches and plays an audio clip.
SYNTAX public void play(URL url) public void playCURL url, String name)
DESCRIPTION This method fetches the audio clip from the URL url and immediately plays the audio clip. If name is specified, the image is fetched from a new URL cre- ated by appending name to url. This method is ignored if the audio clip could not be fetched from url.
parameters name url The non-nul 1 name to append to url. The non-nul 1 URL from which to fetch the audio clip.
example See the class example.
resize()
PURPOSE Resizes the bounds of the applet.
SYNTAX public void resize(Dimension d) public void resize(int width, int height)
DESCRIPTION The bounds of the applet is the area in which it can paint. The resize0 method makes a request to the applet context to resize the bounds of the applet. This request can be ignored by the applet context. 1Ъе new bounds can be specified either as a width and height or as a dimension.
PARAMETERS d hei ght width The non-nul 1 dimension containing the new size in pixels. The height of the new bounds in pixels. The width of the new bounds in pixels.
overrides j ava.awt.Component.resi ze().
java.applet
Applet
setSiub()
SEE ALSO EXAMPL 1, java.awt. Dimensi on. See the class example.
setStubf)
В
c PURPOSE Sets the applet's stub.
n SYNTAX public final void setStubfAppletStub stub)
DESURIPIION The stub is used internally by lhe Applet class. It is called by lhe applet con-
I- text just after the applet is loaded. The stub is part of the implementation of the
F applet context and is not used by the applet programmer.
Ci PARAMI-1 LRS
H stub The non-nul 1 stub.
1 J showStatust)
К PURPOSE Displays a message in lhe applet context.
L SYNTAX public void showStatusfString msg)
M DESCRIPTION This method can be ignored by the applet context. But typically the applet con-
N text displays msg in a status bar. which is often located at the bottom of its win-
() dow.
P PAR AM [fl LRS
1 msg The message to display. If null, the previous message is cleared.
Q EXAMPLE. See the class example.
R
S T start ()
c PURPOSE Called by the applet context just after the applet is made active.
V SYNTAX public void start()
w DESCRIPTION A subclass should oxerride this method if it needs to implement behavior that
x occurs when the applet becomes active. For example, if lhe applet plays back-
ground music only when it is acti\e. this method should be overridden to start
Y the background music.
Z SEE AL.SO stop().
EXAMPLE See the class example.
90
stopO____________________________________________________________________________
purpose Called by the applet context just after the applet is made inactive.
syntax public void stopO
description A subclass should override this method if it needs to implement behavior that
occurs when the applet becomes inactive. For example, if the applet plays
background music only when it is active, this method should be overridden to
stop the background music.
If an applet is active, the applet context will always call this method before
calling destroyO.
SEEALSO destroyO, startO.
example Sec the class example.
java.applet
AppletContext
c
D
E
F
G
H
I
J
К
Syntax
public interface AppletContext
Description
This interface corresponds to an
applet’s environment. It can be used by
an applet to obtain information from
the applet’s environment, which is usu-
ally the browser or the applet viewer
Figure 22 illustrates the relation-
ship between applet contexts and
applets.
FIGURE 22: Relationship Between Applet Contexts and
Applets.
Applet
context
Applet
L
M
N
О
P
Q
R
S
T
U
V
w
X
Y
Z
Audio and Image Methods
getAudioClipO
getlmageQ
Retrieves an audio clip at a URL.
Retrieves an image at a URL.
Applet Methods
getAppletO
getAppletsO
Display Methods
showDocumentO
showStatusO
Retrieves a reference to an applet.
Enumerates the accessible applets in this applet context.
Causes the applet context to display another HTML, document.
Displays a message in the applet context.
See Also
Applet.
Example
This example implements two kinds of applets that communicate with each other through the
applet context. The master applet keeps track of a color, and the bullet applet paints an oval in
the color maintained by the master. See Figures 23 and 24. The master applet has a choice
92
component containing several color names. Changing the selected color in the master causes
all the bullet applets to redisplay their bullets in the selected color. The master applet notifies
all the bullet applets by calling their repai nt О method.
FIGURE 23: Master Applet.
FIGI RE 24; Bullet Applet.
import java.applet.*;
import java.awt.”;
import java.awt.event.*;
import java.uti1. *;
public class Main extends Applet implements ItemListener {
Color color;
public void init() {
Choice c = new ChoiceO;
setLayout(new BorderLayoutO);
c. addltem(“black’');
c.additem C‘red”);
c. addltemC'green”);
c.addltem(“blue”);
add(c, BorderLayout.CENTER);
c.addltemListener(this) ;
}
public Color getColorQ {
return color;
}
public void itemStateChanged(ltemFvent evt) {
Object arg « evt.getltem();
if (“black”.equals(arg)) {
color = Color.black;
} else if (“red”.equals(arg)) {
color = Color.red;
} else if (“green".equals(arg)) {
color = Color.green;
} else if (“blue".equals(arg)) {
color ~ Color.blue;
}
for (Enumeration e^getAppletContextO.getApplets();
e.hasMoreElements(); ) {
java.applet
Appletcontext
ge(Applet()
Applet a = (Applet)e.nextElement();
if (a null && a this) {
a.repai nt О ;
}
import java.applet.Applet;
import java.awt.*;
public class Bullet extends Applet {
Color color - Color.black;
public void paint(Graphics g) {
Main applet =- (Main)getAppletContext().getApplet(“Master");
g. setColor(appl et. getColorO) ;
g.fi 1 lOval (0, 0, getSizeQ .width-1, qetSize().height-1):
}
}
getApplet()
pcrpose Retrieves a reference to an applet.
S^ VI XX Applet gerApplet(String appletName)
DESCRIP ТЮХ This method retrieves lhe applet with the name appletName. It there is more than one applet with the name appl etName. one of them w ill be returned. You cannot predict which one will be returned.
PARAMETERS appletName The name of the applet. See the Applet class for a description of how to name an applet.
RIUTRVS A reference to lhe applet; otherwise, null if lhe applet docs not exist.
St t \LSO Applet.
1 ХЛМР1 F See the class example.
getApplets()
Pl R POM: Enumerates the accessible applets in this applet context.
-SY XT AX Enumeration getAppletsQ
DESCRIP 1 IOX This method returns an enumeration of the accessible applets in this applet context. The enumeration always includes the current applet.
94
Some applet references in the enumeration could be null. This can happen if
applets are being added or destroyed in the applet context during the enumera-
tion.
returns A non-nul 1 enumeration of applet
references. An applet reference in the
enumeration can be null.
example This example creates three identical
applets, each with a different name.
The applets call getAppl ets() to get
a list of all accessible applets. The
applets then display the names of all
the applets, highlighting their names
in red. See Figure 25.
FIGURE 25:
AppletContext.getApplets О•
import java.applet.*;
import java.awt.*;
import java.util
public class Main extends Applet {
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetrics();
int у = fm.getAscentO + 20;
for (Enumeration e=getApplet€ontext().getApplets();
e.hasMoreElementsO ; ) {
Applet a = (Applet)e. nextEl ementO;
if (a == null) {
conti nue;
} else if (a «« this) {
g.setColor(Color.red);
} else {
g.setColor(Color.black);
}
if (a.getParameter(“name”) ’= null) {
g.drawStringCa.getParameterC'name”), 0, y) ;
} else {
g.drawString(“no name”, 0, y);
у += fm.getHeightO;
java.applet
AppletContext
get A udioClip( I
getAudioClipf)
111. Pi RPOSL S> X 1 AX DESCRIPTION Retrieves an audio clip al a URL. AudioClip getAudioClip(URl url) This method retrieves an audio clip at the URI- url. The non-nul 1 URL from which to fetch the audio clip. The audio clip at url. Returns null if the audio clip cannot be found. AudioClip, java.net.URI. See the Appl et class example.
В C D E E I’VR W1ETERS url RE 11 RXs SI I M so IX \MPI I-.
H getlmage()
1 ' ~ ~
pi Rpost; Retrieves an iinane at a URL.
J
svxtax Image getlmaqefURL url)
К
discrihiox This method retrieves an image at the URI, url. It returns immediate!} and
l' does not act nail) fetch the pixels of the image. The pixels are fetched at the
M lime the} arc needed (see Image}.
\ PARAMI IERS
() url The non null URL from which to fetch the image.
p reti rxs 'I'he image at url. Returns null if the image cannot he found.
sh. \i.S() java.awt.Image, java.net.URL.
example; Sec the Applet class example.
S
т showDocument()
l pi RpoSL Causes the applet context to displuj another HTML document.
s'imw public void showDocumentfURL url)
public void showDocument(URL url, String target)
x di s( ripoox This method shows a new document in a target w indow or frame. 'Hie frame is
an H I ML frame, not an AWT frame. If target is not specified, it defaults to
'’.self". This method may be ignored by the applet context.
z Table 3 shows the list of valid target strings.
96
PARAMETERS target url Fhe name of the frame in which to display the document. The non-nul 1 URL containing the document to display.
example See the Applet class example.
_self _parent -top _blank <other> Show in current frame. Show in parent frame. Show in topmost frame. Show in new unnamed top-level window. Show in new top-level window named <other>.
TABLE 3: Appl etContext. showDocumentO Valid Target Strings.
$howStatus()
PURPOSE Displays a message in the applet context.
SYNTAX public void showStatus(String msg)
DESCRIPTION This method can be ignored by the applet context. But typically the applet con- text displays msg in a status bar. which is often located at the bottom of its win- dow.
PARAMETERS msg The message to display. If null, the previous message is cleared.
example: See the Appl et class example.
java.applet
AppletStub
AppletStub
Syntax
C public interface Appletstub
D
Description
This interface is essentially an internal interface used by the applet context. It is not normally
r used by applet programmers. It differs from the Appletcontext interface mainly in that it
G supports methods that set and retrieve information specific for one particular applet. The
applet context, on the other hand, maintains information for all lhe applets that it contains.
f MEMBER SUMMARY
J |---------------
K । Stub Methods
। appletResi?e()
L getAppletContext()
M ! getCodeBaseO
I getDocumentBaseO
M I getParameterО
o ) isActiveQ
P
Resizes lhe bounds of the applet.
Retrieves the applet context.
Retrieves the applet s code base URL.
Retrieves the applet's document base URL.
Retriexes the \ al tie of a parameter.
Retrieves the active state of the applet.
Q
p See Also
Appletcontext.
1 Example
U See lhe Appl et class.
V
U appletResize()
x
pt -rposb Resizes the bounds of the applet.
ьучтах void appletResize(int w, int h)
98
description The bounds of the applet is the area in which it can paint. This request may be
ignored. If the request is satisfied, the new bounds will have the width w and
the height h.
par A mete: RS
h The height of the new bounds in pixels.
w The width of the new hounds in pixels.
example See Applet, resize о. C
I)
getAppIetContext()
-------------------------------- j;
purpose Retrieves the applet context.
G
syntax public AppletContext getAppletContextO
H
description See the Applet class for more information about applet contexts.
returns The non-nul 1 reference to the applet context.
SEE At.so AppletContext.
example See Appl et. getAppl etContextО .
L
M
getCodeBaseO N
purpose Retrieves the applet's code base URL. U
syntax URL getCodeBaseO p
description The code base is the L’RL prefix that contains the applet code. For example, Q
suppose an applet were located at http://www.sun.com/applets/ R
Main, cl ass. The code base would be http://www.sun.com/applets/. The
code base is typically used to fetch resources specific to the applet, such as
icons and configuration information. T
Returns The non-nul 1 applet's code base URL. U
SEE also getDocumentBaseO. java.net.URL. V
example See Applet-getCodeBaseO. w
x
getDocumentBase() Y
purpose Retrieves the applet's document base URL.
Syntax URL getDocumentBaseO
java, applet
AppletStub
getParameter()
□INSCRIPTION
The document base is the URL prefix that contains the document that contains
the applet. For example, suppose the document containing the applet was
located at http://www.sun.com/products/sparcstation/i ndex.html.
The document base would be http://www.sun.com/products/sparcsta-
tion/. The document base is typically used to fetch resources specific to the
document. For example, if sonic animation was to be designed for a particular
HTML document, the animation images would typically be located some-
where relative to that document.
D see also getCodeBaseO. java. net. URL.
1г example See Applet,getDocumentBase().
J getParameter()
н — - — - - - - - —
purpose Retrieves the value of a parameter.
syntax String getParameter(String name)
□escrlpi ion This method returns the value of the parameter identified bv the name name
К
PARAMETERS
L name The non nul 1 name of the parameter value to retrieve.
M returns Returns the value of the parameter: otherwise, returns null if the parameter
N does not exist.
exampl л. See Applet .getParameter О.
v isActive()
R “ ~ ~ ~ —
purpose Retrieves the active state of the applet.
syn'IAx boolean isActive()
j desuripwn An applet becomes active just before the start() method is called and
becomes inactive just before the stop() method is called. See the Applet
V class for more information about applet states.
w RE'IIRNS true if the applet is active; false otherwise.
X SEFALSO Арр 1et.start().
Y EX AM PL in See Applet.isActiveО,
100
AreaAveragingScaleFilter
ArsaAveragi ng Sea LeFi1Ler
Syntax h
public class AreaAveragingScaleFilter extends ReplicateScaleFilter H
G
Description
The area averaging scale filter is an image filter that scales images, producing results that are H
superior to the simpler replicate scale filter (see ReplicateScaleFilter). In both filters, I
when an image is scaled larger, pixels are replicated to achieve "larger’' pixels. However, the j
area averaging scale filter does an extra step of blending the new pixels with adjacent pixels.
The result is an image with less \jaggies.” The trade-off of using an area averaging scale filter K
is that it takes longer to scale the image. If the image is scaled for some animation effect, it l
may be better to use the simpler replicate scale filter since the higher quality scaled images
• , M
may not be noticed.
This image filter is meant to be used in conjunction with a Fi IteredlmageSource object, N
which assumes the responsibility for delivering an image to this image filter to scale. See ()
ImageFilter for more information about the image filtering architecture.
For the scaling algorithm to work, the producer must deliver the pixels to the filler in top- p
down, left-to-right order (see ImageProducer). If the image producer cannot do (his, the area Q
averaging scale filter resorts to (he simple pixel replication algorithm as implemented by the
replicate scale filter.
s
SUMMARY
Constructor
AreaAveragingScaleFilterО Constructs an AreaAveragingScaleFi 1 ter instance.
Image Consumer Methods
setHintsO Called by the image producer to specify how the pixels
will be delivered to this image filter.
setPixelsQ Called by the image producer to deliver pixels to this
image filter.
AreaAveragingScaleFilter
java.awt. image
See Also
ImageConsumer.
в
c
D
E
F
G
H
1
J
К
L
M
N
О
P
Q
R
S
T
и
V
w
X
Y
Z
Replicate Area- Averaging
FIGI RE Images loaded using Repl icateScaleFilter and
AreaAveragi ngScaleFi 1 ter.
Example
This example allows you to compare the effects of AreaAveragingScaleFilter with the
simpler Repl i cateScal eFi Iter. The example creates a windows with two panes. The image
on the left is scaled with Repl icateScaleFiIter, and the image on the right is scaled with
AreaAveragi ngScal eFi Iter. Figure 26 shows two examples of these windows.
import java.awt.*;
import java.awt.image;
import java.net.*;
class Main extends Frame {
Main(String filename) {
super("AreaAveragingScaleFilter Example");
Image image - nul1;
if (filename J- null) {
// Retrieve the image.
image = getToolкit().getlmage(fi1 ename);
// Ensure that the image is completely loaded since we
// need the width and heigth information immediately.
MediaTracker tracker - new Medialracker(this);
try {
tracker.addlmage(image, 0);
tracker.wai tForID(0);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Гуре an X in the image.
Font font = new FontC'Serif", Font.BOLD, 72);
FontMetrics fontM = getFontMetrics(font);
102
addNotifyO ;
image = createImage(fontM.charWidth(1X’), fontM.getHeight());
Graphics g = image.getGraphics();
g.setFont(new Font("Serif”, Font.BOLD, 72));
g.drawStringC’X", 0, fontM. getAscentO) ;
g. disposed);
В
// Layout components.
setLayout(new GridLayout(l, 0)); c
add(new ImageScaler(image, false));
addfnew ImageScaler(image, true)); D
setSize(300, 300);
show(); E
}
F
static public void main(String[] args) {
if (args.length == 1) { G
new Main(args[0]);
} else { H
new Main(null);
} I
}
} J
class ImageScaler extends Canvas { К
Image origlmage;
Image curlmage; L
Dimension curSize - new Dimension(0, 0);
boolean areaAvr; M
ImageScaler(Image image, boolean areaAvr) { N
origlmage = image;
this.areaAvr = areaAvr; О
}
P
public void paint(Graphics g) {
if (!curSize.equals(getSize())) { Q
curSize - new Dimension(getSizeO);
R
// The size has change so create a new scaled image.
if (areaAvr) { S
curlmage *= createlmage(
new FilteredImageSource(origImage.getSource(), T
//new AreaAveragingScaleFi1ter(curSize.width,
// curSize.height))); V
new AreaAveragingScaleFi1ter(-2, curSize.height)));
} else { v
curlmage *= createlmage(
new FilteredImageSource(origImage.getSource(), w
//new ReplicateScaleFilter(curSize.width, curSize.height)));
new ReplicateScaleFiIter(-10, curSize.height))); X
} } Y
g.drawlmage(curImage, 0, 0, this);
} 7
}
AreaAveragingScaleFilter
AreaAveragingScaleFilter()
java.awt. image
AreaAveragingScaleFilterO
Pl RPOSl Constructs an AreaAveragingScaleFilter instance.
Bl . SVXI AX public AreaAveragingScaleFi1ter(int width, int height)
1 л и DESCRIP'IIOX This constructor creates an area a\eraging scale filter that scales an image to width and height. This image filter is meant to be used in conjunction with a
в
с Filtered! mageSource object» which assumes the responsibility for delis et- ing an image to this image filter to scale.
D If width is negative, it defaults to the width of lhe incoming image. Likewise
E P PARAMETERS for height.
G hen ght The new height of the image in pixels. If < 0. ii defaults to the height of lhe incoming image.
H 1 wi dth The new width of the image in pixels. If < 0, it defaults to lhe width of the incoming image.
J SEI ALSO F i1teredlmaqeSource.
К EXAMPLE See the class example.
setHintsQ
IX PURPOSE () Called by the image producer to specify how the pixels will be delivered to this image filter.
P SYNTAX DESCRIP 1 IOS R S public void setHints(int hints) Although this method is public» it is not meant to be called. This method is pan of the image filtering process and is called by an image producer. For more information on image filters, see ImageFi 1 ter.
PARAMETERS 1 hi nts 1 OVERRIDES V SEE ALSO A bit vector specifying how the pixels will be delivered. ImageFi 1 ter. setHintsO • ImageConsumers.setHi nts().
W EXAMP1 E See ImageConsumer.
Y
Z
104
setPixelsO
PURPOSE Called by the image producer to deliver pixels to this image filter.
SYNTAX public void setPixelsfint x, int yr int w, int h, ColorModel model, byte pixels[], int off, int scansize) public void setPixelsfint x, int y. int w, int h, ColorModel model, int pixels[], int off, int scansize)
description Although this method is public, it is not meant to be called. This method is part of the image filtering process and is called by an image producer. For more information on image filters, see ImageFi 1 ter.
PARAMETERS h model off pixels scansize w X У The height of the rectangle in which the pixels are destined. The non-nul 1 color model used to translate the pixel values. The index of the first pixel in the pi xel array. The non-nul 1 array of pixel values. The width to use when extracting pixels from the pixel array. The width of the rectangle in which the pixels are destined. The x-coordinate of the rectangle in which the pixels are destined. The y-coord inate of the rectangle in which the pixels are destined.
OVERRIDES Repli cateScaleFiIter.setPi xels().
SEE ALSO Imageconsumer.setPi xels().
EXAMPLE See ImageConsumer.
java.applet
AudioClip
B Syntax
<' public interface AudioClip
D
L Description
An audio clip is a sample of audio data. This class has minimal support for playing audio clips.
* You can start and stop playing an audio clip, and you can play an audio clip in a repeat loop.
(j
H | MEMBER SUMMARY "1
1 । Play and Stop Methods
J | loopO Starts play ing the audio clip in a loop. j
playO Starts plax ing the audio clip.
ts. | stopO Stops playing the audio elip.
L M
N
Example
() See the Applet class example.
P
Q
к loop!) _
s Pt RPOSt Starts plaxing the audio clip in a loop.
I SYNFAX void loopO
I’ DLSCRIPHOX When this method is called, the audio clip is restarted at the beginning, regard-
V less of whether the audio clip was already playing.
w 1 X \MPI H See the Applet class example.
X
Y play()
z Pl’RPC )SL Starts playing the audio clip.
SX MAX void pl ay О
106
DESCRIPTION The audio clip is played from the beginning, regardless of whether the audio clip was already playing. The audio clip is played once and does not repeat. In particular, if the audio clip was being played in a loop (see loopO). the playO method will terminate the loop and play the audio clip from the start one more time.
EXAMPLE See the Appl et class example.
stopO
PURPOSE Stops playing the audio clip.
SYNTAX void stopO
DESCRIPTION If the audio clip is playing, either in a loop or not, it is immediately stopped.
EXAMPLE See the Appl et class example.
java.awl
AWTError
В
c
D
E
P
G
н Syntax
public class AWTError extends Error
J
К
L
M
N
О
P
Description
This error is raised if the AWT encounters a fatal problem that renders the AWT usable.
MEMBER SUMMARY _: * Jr...
Constructor AWTError() Constructs an AWTError instance. j
Q
R See Also
s Scroll Pane.setLayoutО, Sc roll Pane. setMaximumQ , Scroll Pane. setMinimumO ,
Sc rol1 Pane.setVi si bl eAmount О, Toolki t.getDefaultToolki t ().
T
V
V
w
X
Y
Z
108
Example
The following example generates an AWTError when the program attempts to set a scrol]
pane’s layout (the Scrol 1 Pane class disallows setting of its layout):
import java.awt.Scrol1 Pane;
import java.awt.BorderLayout;
class Main {
public static void main(5tring[] args) {
System.out.println(“AWTError example”);
Scrollpane sp = new Scrol 1 PaneO ;
sp.setLayout(new BorderLayoutO);
}
}
AWTErrorO
PURPOSE Constructs an AWTError instance.
SYNTAX public AWTError(String msg)
DESCR1PI ION This constructor creates a new instance of AWTError with a string msg that describes the details of this particular instance of the error.
PARAMETERS msg A string that gives details about this error.
Syntax
public abstract class AWTEvent extends EventObject
Description
Components interact with a program that uses them through the use of events. For example,
when a user clicks component with the mouse, that component fires a mouse-clicked event.
Ftvents in the AWT are organized into a class hierarchy rooted at the abstract class AWTEvent.
Event Types, Event Subtypes, and Event Class Hierarchy
The AWT event hierarchy organizes the different types of events that AWT components can
fire. A subclass of an event class provides more details on the nature of the event. For exam-
ple, KeyEvent and MouseEvent are subclasses of the more general InputEvent. A KeyEvent
contains information about the key that was pressed or released in addition to general
InputEvent information such as the pressed modifier keys and time of the input.
A single subclass such as KeyEvent can be used to represent different event subtypes.
KeyEvent, for example, has three different event subtypes: KEY-PRESSED, KEY-RELEASED,
and KEY_TYPED, each representing a specific kind of KeyEvent. Each event subtype is identi-
fied by an event id.
There are (wo categories of events: those that represent the low-level, basic manipulations
that a user performs on AWT components and those that represent higher-level concepts. The
low-level events include events such as input events via the keyboard or mouse, changing the
focus of the component, showing and hiding components, adding and removing components
from containers, and opening and closing windows. These events are subclasses of Compo-
nentEvent.
The higher-level conceptual events, or semantic events, are events fired based on semantic
interpretation of the user's actions. For example, when a user click a button, in addition to
mouse events from the mouse press and release being fired, an action event indicating that the
button has been pushed is also fired. Similarly, when a user selects a checkbox, in addition to
mouse events being fired, an item event indicating that the stale of the checkbox has changed is
also fired. These semantic events allow the components and programs to deal with events at a
higher level.
Event Sources, Event Listeners, and Event Adapters
The Java event model is a notification-based system. Objects that fire events are called event
sources. A single event source can fire one or more different types of events. For each type of
event that it fires, the event source maintains a list of event listeners for that event type. The
event source contains methods for adding and removing event listeners for the different types
of events that it fires. An event listener registers with the event source using the registration
methods provided. When an event of the corresponding type is fired by the source, the listener
is notified. In the case of events fired by AWT components, the AWTEventMulti caster class
is used to notify event listeners. The order in which an event is delivered to its listeners is
implementation-dependent and should not be depended upon. A listener that is registered first
may or may not get the event first.
Each subclass of AWTEvent has an associated interface called the event listener interface.
For example, the ActionEvent class has an associated ActionListener interface. Each
interface specifies the methods that a listener of that event type must implement. For example,
the ActionListener interface contains the single method actionPerformedO, which is
invoked on the listener when an action event is fired by the object with which it has registered.
For convenience, the AWT event types with more than one subtype (AdjustmentEvent,
ComponentEvent, ContainerEvent, KeyEvent. MouseEvent, FocusEvent, and Window-
Event) also define event adapter classes. An event adapter class defines empty implementa-
tions for all of the methods in the corresponding event listener interface. This means a subclass
of an event adapter needs only to provide (override) implementations of the methods in which
it wants to handle. For example, if you want the listener to handle only the KEY-PRESSED sub-
type of KeyEvent, you would subclass from KeyAdapter and override keyPressedO- To
achieve the same effect directly using the KeyListener interface, you would need to provide
implementations for all three methods (keyPressedO, keyReleasedO, and keyTypedO).
AWTEvent
java.awt
Peer
AWTEvent
System
Event
Queue
Dispatch
di spatchEvent О
I
Event Source
Fire
On
Event Listeners q U
FIGI KF 27: AWT Event Flow.
Event Flow
Figure 27 shows how events typically flow
through the AWT. First, the e\enl is generated by
у_________ some component peer (either Component or
MenuComponent) in response to some user ges-
ture. This event is posted on the event queue (see
EventQueue). When the event makes its way to
F the front of lhe queue, it is given to the component
p via its dispatchFvent() method. The main pur-
pose of this method is to discard the event if the
event type is not enabled (see the following
F Enabling Events discussion) or if the event source
G has no listeners registered for that event type.
Otherwise, di spatchEventO calls the event
H source's processEventQ method, which calls
1 different methods depending on the event type.
For example, if the incoming event is an Action-
Event, the event sources processAction-
K Event О would be called, rhe main purpose of
L the processSomeFventQ methods is to notify
the registered event listeners for SomeEvent.
With only one exception, when an event is dispatched to a component, that component
N fires the event to its listeners and no one else. The event is not passed up to the event source's
parent regardless of whether the event source has any listeners. This is different from the Java
1.0 event model, where events automatically move up the parent hierarchy unless handled (see
F the deprecated Event class for details). l he only exception is in the case of Acti onEvent gen-
q erated by Menuitem. If a menu item does not have any listeners, the action event is passed up
to its parent menu. If the parent is not a menu component or if the parent does not have any
R registered action listeners, the action event is discarded. See Menuitem for details.
S
Event Notification
AWT components use the AWTEventMulticaster class to register, remove, and notify event
T listeners. Each time an event source updates its listener list, it is in effect using a new' instance
v of an AWTEventMul ti caster with the updated list. This updated multicaster is recorded with
the e\ent source.
Fa ent listeners are notified synchronously in an implementation-dependent order deter-
X mined by the inulticaster. Once an event has started to proceed dow n lhe list of listeners, it will
be delivered to all listeners in this list, even if a listener is removed from the event source. The
next time an event is dispatched to the same event source, the removed listener will not be
z notified (because the event source is. in effect, using a new' multicaster). Consequently, a lis-
tener should be prepared to receive a few more cxents even after it has been removed from the
event source.
112
Consuming Events
Most events are delivered by the event source to its listeners after the operation has taken
place. In other words, the event source s component peer has already performed the operation.
For example, by the time an ItemLi stener receives notification of an ItemEvent from a
checkbox, the checkbox’s state has already been changed to its new stale. Similarly, when a
COMPONENT_RESIZED component event is delivered to a listener, the component peer has
already been resized.
The exception is for InputEvent and its subclasses. An input event is first delivered to
the event source and its listeners before is it processed by the event source s component peen
This allows the event source and its listeners to modify or consume (i.e.. discard) the event
before it is processed by the peen An example of when this could be used is by a text field that
accepts only numbers. Here, when the text field receives a key event that is not a number, it
could emit a beep and then consume the event. The consumed key events would not appear in
the text field. Note that all listeners are notified of the event, regardless of whether the event
has been consumed. Consuming an event affects only whether the peer gels to process the
event. When an input event is consumed, it cannot be “unconsumed/’
Semantic events (ActionEvent. ItemEvent, AdjustmentEvent, and TextEvent) are
consumed automatically because they are fired by the peer in response to some low-level
events (such as mouse clicks). There is no need for the peer to do further processing related to
the semantic events. Hence, they always appear “consumed.”
Enabling Events and Event Masks
Enabling an event type for an event source means that events of that type will be delivered to
the event source’s processEventO method.
An event type is automatically enabled for an event source when an event listener for that
type is registered with the event source. For example, when you register an action listener with
a button component, action events will be enabled for that instance of the button component.
Each event type is enabled individually.
In addition, each event source maintains an event mask for keeping track of the event types
that have been enabled. You can explicitly enable an event type for an event source by invok-
ing the event source’s enableEventsО method with the event type's mask. This technique is
used by subclasses of Component to always deliver events of the specified type to its pro-
cessEventO method, regardless of whether the event source has any event listeners for that
event type. The event source’s di sabl eEvents О is used to disable an event type for an event
source. However, if the event source has event listeners for that event type, processEventO
will always be called, disableEventsO has only the effect of turning off the event type's
mask; it does not preventing delivery of events to the event source’s listeners.
Defining Your Own Event Types
You can define your own event type by subclassing AWTEvent or any of its subclasses. When
you do this, you should define the new event type’s event id to be greater than
AWTEvent
jasa.awt
RESERVED_ID_MAX. The example lor Component. di spatchEventO defines a new subclass
of ActionEvent, SetFontEvent. whose event id is RESERVED_JD_MAX+1.
il
.A
В
c
D
k
F
(j
H
I
J
Events h ired by Components
Events are inherited through the subclassing hierarchy. A component fires all the events fired
by all of its superclasses. When you define new components by subclassing any of the AWT
component classes, those new subclasses will fire all of the events fired by its superclass. You
also can define these new subclasses to fire additional event types.
Note: In Java 1.1.2. components cannot fire predefined event types such as ActionEvent
if its superclass does not already fire it. For example, if you define a subclass of Canvas to
support ActionEvent. you cannot use the normal event dispatching mechanisms in the Com
ponent class (event queue or di spatchEventO ) to dispatch the action event. You can bypass
the event-enabled checking by calling the overridden processEventQ directly. The
workaround is to have the action event contain a different event id that is greater than
RESERVED MAX^ID.
Table 4 lists the AWT components and event types that they fire. See individual class
descriptions of the components for details on the conditions under which the events are fired.
К
L
M
N
()
Q
R
s
T
i:
v
w
X
Y
114
Button X X X X X
Canvas X X X X
Checkbox X X X X X
CheckboxMenuItem X* X
Choice X X X X X
Component X X X X
Container X X X X X
Dialog X X X X X
Frame X X X X X
Label X X X X
List X X X X X X
Menuitem X
Panel X X X X X
Scrollbar X X X X X
Scroll Pane X X X X X
TextArea X X X X X
Textcomponent X X X X X
TextField ’ X X X X X X
Window । X X X X X
TABLE 4: AWT Components and the Event Types They Fire,
a hi Java 1.1.2. CheckboxMenuTtem does noi fire ActionEvent, even though и is a
subclass of Menu Item.
AW'Г Event
java.awt
1 MEMBER SUMMARY ' Constructor
1 AWIEventO Constructs a new instance of AWTEvent.
' Event Mask Constants
в 1 ACTION-EVENT MASK E\ent musk for ActionEvent.
( | ADDUSTMENT_FVENT_MASK Event mask for Ad justmentEvent. । COMPONENT-EVENT.MASK Event mask for Component Event.
D CONTAINER TVFNT. MASK Event mask for Contai nerEvent.
E F 1 FOCUS_EVFN7_MASK Event mask for FocusEvent. | ITEM_EVFN7 MASK Event mask for ItemEvent. KEY, FVENT_MASK Event mask for KeyEvent.
G MOUSE-EVEN!_MASK Event mask for basic mouse events (subtypes of 1 MouseEvent).
H 1 | MOUSE_MOTION_EVENT.MASK Глет mask for mouse motion events (subtypes of । MouseEvent). I EXI-EVENI-MASK Event mask for TextEvent.
J 1 W1NDOW_EV£NT_MASK bem musk for Wi ndowEvent.
К 1 Methods and Field for Consuming Events
L 1 consume() Consumes this event to prevent delivery to peer.
M \ | consumed Indicates whether this event has been consumed. । i sConsumedO Determines whether this event has been consumed. । Event Type Members
() getIDO Retrieves the event id (event subtype) of this event,
' id Contains this event's event id.
P J RESERVED ,ID_MAX Lower limit for user-defined event ids.
Q R S 1 Debugging Methods । 1 paramStri ng() Generates the string representation of this event. 1 toStringO Generates the siring representation of this event. ।
U V See Also
w X Component. di sableEventsQ , Component .di spatchEventO , Component.enab 1 eEvents О, Component,processEvent()» EventQueue, java.uti1.EventListener, java.util.Eventobject,
Y Tool kit .getSystemEventQueueO .
116
Example
This example illustrates how to define a
new event type, ButtonClickEvent.
that subclasses directly from AWTEvent.
The program implements a light-
weight component, ImageButton, that
behaves like an AWT Button. Instead
of its having a label, however, it has an
FIGURE 28: ImageButton Using ButtonCl i ckEvent.
image as the face of the button. A sec-
ond image is displayed while the button is held down. See Figure 28.
When the mouse is released from ImageButton, it creates a ButtonClickEvent and
adds it to the system event queue. ButtonClickEvent is always ‘’consumed” because it is a
semantic event that need not be processed by the component’s peer. ImageButton overrides
processEventO to add support for ButtonClickEvent. It also provides a method addBut-
tonClickListener() for registering a listener for ButtonClickEvent. The program defines
a corresponding listener interface ButtonCl i ckLi stener for the new event.
See the AWTEventMulticaster class example for a similar example, which uses a new
subclass of ActionEvent instead of directly subclassing from AWTEvent.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.uti1.TooManyListenersException;
class Main extends Frame implements ButtonClickListener {
Main(String upFile, String downFile) {
super(“AWTEvent Example”);
ImageButton b = new ImageButton(getToolkit().getImage(upFile),
getToolkit().getlmage(downFile),
“Hello”);
add(b, BorderLayout.CENTER);
try {
b.addButtonClickLi stener(thi s);
} catch (TooManyListenersException e) {
e.printStackTraceO ;
System.exit(-l);
}
setBackground(Color.1ightGray);
pack();
show();
}
public void buttonClicked(ButtonClickEvent evt) {
System.out.pri ntln(evt.toStri ng());
System.out.println(evt.getButtonRequestQ) ;
static public void main(String[] args) (
if (args.length == 2) {
AWTEvent
java.awt
A
al____________
В
c
D
E
I-
G
H
I
J
К
new Мд-j n(args[0], args[l]);
} else {
System.err.println(“usage: java Main <imagel> <image?>”);
}
}
}
// New subclass of AWTEvent
class ButtonClickEvent extends AWTEvent {
String request;
// Event id must be greater than RESERVED_ID_MAX
static final int BUTTON_CLICK_FVENIT - AWTEvent.RESERVED_ID_MAX+10C
ButtonClickEvent(Object source, String request) {
super(source, BUTTON_CLICK1EVFNT);
this.request = request;
consumed =. true; // semantic event need not go to peer
}
String getButtonRequestQ {
return request;
}
public String paramStringO {
return getButtonRequestO + super.paramString();
}
}
L // Interface of listener
interface ButtonClickListener {
M public void buttonClicked(ButtonClickEvent evt);
}
N
// Component that fires ButtonClickEvent
() class ImageButton extends Component {
Image uplmage, downimage;
P transient ButtonClickListener listener;
String cmd;
Q boolean raised = true;
int borderwidth = 5;
R
ImageButton(Image uplmage, Image downimage, String cmd) {
S this.uplmage = uplmage;
this,downimage = downimage;
T this.cmd = cmd;
L
V
W
X
Y
Z
// Load first image to get size of button.
MediaTracker tracker = new Mediairacker(this);
try {
tracker.addlmage(uplmage, 0);
tracker.wai tForAl1(0);
} catch (InterruptedException e) {
e.printStackTraceO ;
}
addMouseListener(new MouseEventHandlerO);
}
public Dimension getPreferredSize() {
return new Dimension(uplmage.getWidthfnull)+2'vborderwidth,
uplmage.getHeight(nul1)+2*borderWidth);
118
}
public boolean contains(int x, int y) {
return (x < uplmage.getwidth(null)+2*borderWidth &&
у < upImage.getHeight(nul1)+2*borderWidth);
}
public void paint(Graphics g) {
Image image = (raised ? uplmage : downimage);
g.drawlmage(image, borderwidth, borderwidth, this);
// Draw border around image
int x = 0, у = 0;
int w = image.getWidth(this)+2*borderWidth;
int h = image.getHeight(this)+ 2*borderWidth;
w -= 1; // draw inside the rectangle.
h -= 1; // draw inside the rectangle.
g. setColor(getBackgroundO);
for (int i=0; i<borderWidth; i+ч) {
g.draw3DRect(x++, y++, w, h, raised);
w 2;
h -= 2;
}
}
// Method for registering ButtonClickEvent listener
public synchronized void addButtonClickListener(ButtonClicklistener 1)
throws TooManyListenersException {
if (listener != null) {
throw new TooManyListenersExceptionO;
}
listener = 1;
}
// Override processEventO to handle new event type
protected void processEvent(AWTEvent evt) {
if (evt instanceof ButtonClickEvent) {
processButtonClickEvent((ButtonClickEvent)evt);
return;
}
super.processEvent(evt);
}
// Method for processing new event type
protected void processButtonClickEvent(ButtonClickFvent evt) {
if (listener != null) {
listener.buttonClicked(evt);
}
}
// Mouse handler for presses and releases inside this button
// When mouse is released, fire ButtonClickEvent
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
raised ~ false;
repaint ();
}
public void mouseReleased(MouseEvent evt) {
raised = true;
repaintO ;
AWTEvent
java.awt
ACTION „EVEN Г_М ASK
ButtonClicktvent bd = new ButtonClickEvent(ImageButton.this, cmd):
Tool ki t.getDefau1tToolki t().getSystemEventQueueO.postEvent(bd);
}
}
C ACTION. .EVENT_MASK
D Pl RPOSP Event mask for ActionEvent.
E SY N 1 AX public final static long ACTION_FVENT_MASK
E DESCRIPTION This constant is passed to Component .enableEventsO and Compo-
(i nent .di sableEventsQ to enable and disable action events, respectively.
H See the class description for details on event masks. The value of this constant
1 is 0x80.
i SET ALSO Component .di sableEventsQ , Component. enabl eEventsO .
J java.awt.event.ActionEvent.
К EXAMPLE See MenuItem.di sableEventsО.
L
M ADJUSTMEM _EVENT_MASK
N О ptrpose Event mask for AdjustmentEvent.
p syntax public final static long ADJUSTMENT„FVENT_MASK
description This constant is passed to Component.enableEventsO and Compo-
Q nent .di sableEventsQ to enable and disable adjustment events, respec-
R tively. See the class description for details on event masks. The value of this
S constant is 0x100.
T see also Component .di sableEventsQ , Component. enableEventsO ,
i U j ava.awt.event.AdjustmentEvent. example See the similar usage of ACTION_EVENT_MASK in Menuitem.disable-
V EventsQ .
w X AWTEventf)
Y pi rpose Constructs a new instance of AlATTEvent.
Z symax public AWIEvent(Object source, int id)
public AVfTEvent(Event event)
120
description The first form of this constructor creates an AWTEvent instance with event id
id for the event source source. See the class description for details on event
sources and event ids (event subtypes).
The second form of this constructor is for supporting Java 1.0 event model —
events (Event). The target and id fields from event are used to construct |
the new AWTEvent instance. B
When an AWTEvent is created, its “consumed” slate is fal se, except when i d
is one of the following:
Act i on Even t. ACTION-PERFORMED,
AdjustmentEvent.ADJUSTMENT-VALUE-CHANCED,
ItemEvent.ITEM_STATE_CHANGED, F
TextEvent.TEXT-VALUE„CHANGED.
F
For these event ids, the consumed state is true. See Consuming Events in the
class description for details. G
parameters h
event Java 1.0 event, whose target and id fields will be used for constructing the j
new AWTEvent.
id The event id of the new event,
source The event source that fired the new event. К
EXCEPTIONS L
111egalArgumentExcept i on M
If source is null.
N
SEE also consume(), getlDQ, i sConsumed() ,
java.util.Eventobject.getSourceO. О
example See the class example (ButtonClickEvent’s constructor calls the AWTEvent p
constructor).
R
COMPONENT E VENT MASK s
purpose Event mask for ComponentEvent. 1
SYNTAX public final static long COMPONENT_EVENT_MASK 1
v
description This constant is passed to Component.enableEvents() and Compo-
nent.disableEventsО to enable and disable component events, respec- w
lively. See the class description for details on event masks. The value of this x
constant is 0x01.
Y
SEE also Component.disabletventsО, Component.enableEvents(),
java.awt.event.ComponentEvent. Z
example See the similar usage of ACTION-EVENT-.MASK in Menuitem.disable-
V Events().
L
AWTEvent
consumeO
ja\a.IBM
consume()
PURPOSE. Consumes this event to prevent delivery to peer.
SYNTAX protected void consumeO
DESCRIPTION Onl) the following event subtvpes can be consumed:
в KeyEvent.KEY-PRESSED, KeyEvent.KEY-RELEASED, MouseEvent.MOUSE-PRESSED, mouseEvent.MOUSE-RELEASED,
c mouseEvent.MOUSE-MOVED, mouseEvent.MOUSE-DRAGGED, mouseEvent.MOUSE_ENTERED, mouseEvent.MOUSE-EXITED.
D Invoking consumeO on events with any other event id does not do anything.
к See class description for details on consuming events.
F SEI; Al SO consumed, isConsumedO, java.awt.event.InputEvent.
Ci H EX AM PI I See the java.awt.event. InputEvent class example.
1 consumed
J К PURPOSE Field indicating whether this event has been consumed.
L SYNTAX protected boolean consumed
DESCRIPI ION This field is set by the consumeO method and used for determining the result
M of isConsumedO. See the class description for details on consuming events.
N SEE ALSO consumef), i sConsumedO.
О P EXAMPLE See the class example.
Q R s CONTAINER EVENT_MASK
Pl RPOSL Event mask for ContainerEvent.
T SYNTAX public final static long CONTAINER EVFNT MASK
и 1)1 SCRI PTION This constant is passed to Component.enableEvents О and Compo- nent .di sableEventsO to enable and disable container events, respectively.
V See the class description for details on event masks. T he value of this constant
w is 0x02.
X X/ SIT AL SO Component.di sabletvents(), Component. enabl eEventsQ. j ava.awt.event.Componenttvent.
Y EXAMPLE See the similar usage of ACTION_EVENT_MASK in MenuTtem.disable-
z EventsQ .
122
FOCUS EVENT MASK
PURPOSE Event mask for FocusEvent.
SYNTAX public final static long FOCUS.EVENT-MASK
description This constant is passed to Component.enableEventsO and Compo- nent, di sabl eEventsO to enable and disable focus events, respectively. See the class description for details on event masks. The value of this constant is 0x04.
SEE ALSO Component.disableEvents О, Component.enableEventsO < java.awt.event.FocusEvent.
EXAMPLE See the similar usage of ACTION_EVENT_MASK in Menuitem.disable- EventsO.
getlDQ
PURPOSE Retrieves the event id (event subtype) of this event.
SYNTAX public int getID()
DESCRIPTION This method returns the event id with which this event was created. See the class description for details on event ids.
SEE ALSO AWTEventО, id, RESERVED-ID_MAX.
EXAMPLE See the java.awt.event. KeyEvent class example.
id —
PURPOSE Field containing this event’s event id.
SYNTAX protected int id
DESCRIPTION This field is set by the AWTEvent constructor and used for determining the result of getlDQ. See the class description for details on event ids. This field should not be used directly.
SEE ALSO AWTEventf), getlDO-
isConsumed()
PURPOSE Determines whether this event has been consumed.
SYNTAX protected boolean isConsumedO
AWTEvent _____
ITEM-EVENT MASK
java.awt
LMSCkiniOS See Consuming Events in the class description for details.
REI IRNS true if this event has been consumed: fal se otherwise.
S EL ALSO consumeQ , consumed.
В ITEM_EVENT .MASK
c PURPOSE Event mask for ItemEvent,
I) SYNTAX public final static long I7EM_EVENT_MASK
к DESCRIPTION This constant is passed to Component.enableEvents() and Compo-
F nent .disableEventsQ to enable and disable item events, respectively. See
G the class description for details on event masks. The value of this constant is
H 0x200.
see: ALSO Component.disableEventsQ, Component.enableEventsQ,
1 java.awt.event.ItemEvent.
J example: See the ItemSelectable class example.
К L M N KEY_EVENT_MASK
PURPOSE Event mask for KeyEvent.
0 SYNTAX public final static long KEY-EVENT .MASK
p DESCRIPTION This constant is passed to Component.enableEventsQ and Compo-
Q nent .di sableEventsQ to enable and disable key events, respectively. See the class description for details on event masks. The value of this constant is
R 0x08.
s SEE ALSO Component.di sableEventsQ , Component. enabl eFventsO ,
T EXAMPLE java.awt.event.KeyEvent. See the similar usage of ACTION-EVENT.. MASK in Menuitem.disable-
и EventsQ .
V w v MOUSE, EVENT MASK
Л Y PURPOSE Event mask for basic mouse events (event subtypes of MouseFvent).
Z SYNTAX public final static long MOUSE.EVENT-MASK
description This constant is passed to Component .enableEvents О and Compo-
nent. di sabl eEvents О to enable and disable basic mouse events, respec-
124
SEE AIM)
EXAMPLE
lively. The basic mouse event subtypes are mouse pressed, mouse released,
mouse clicked (when the mouse is pressed and released at the same coordi-
nates), mouse entered, and mouse exited. See the class description for details
on event masks. See the MouseEvent class for details on these mouse event
subtypes. The value of this constant is 0x10.
Component.disableEvents(), Component.enableEvents(),
j ava.awt.event.MouseEvent.
See the similar usage of ACTION_EVENT_MASK in Menuitem, di sable-
Events О.
MOUSEJMOTION^EVENT^ MASK
------------------------------------------------- (
purpose Event mask for mouse motion events (event subtypes of MouseEvent). f
SYNTAX public final static long MOUSE__MOTION_EVENT_MASK
description This constant is passed to Component.enableEvents() and Compo-
nent .di sabl eEvents () to enable and disable mouse motion events, respec-
tively. The mouse motion event subtypes are mouse moved and mouse
dragged. See the class description for details on event masks. See the Mou- l
seEvent class for details on these mouse event subtypes. The value of this
constant is 0x20.
b
SEE also Component.disableEvents(), Component.enableFventsО,
java.awt.event.MouseEvent. C
example See the similar usage of ACTIONLEVENT_MASK in Menuitem.di sable- p
EventsО.
R
paramStringO s
purpose Generates the string representation of this event. r
syntax public String paramStringO L
description The default implementation of this method returns the empty string Sub- v
classes of AWTEvent should override this method to return the concatenation w
of its string representation with super. paramStri ng(). Illis method is called
by toStringC) and is typically used for debugging.
Y
Returns A non-nul 1 string representing the component event's state.
SEE also toStringO, java. 1 ang .Object. toStri ng() . Z
Example See the class example.
AWTEvent
RESERVED Jd"MAX
java.awt
В
C
D
E
F
G
II
I
J
К
L
M
N
()
P
Q
R
S
T
L
V
W
X
Y
Z
RESERVED_ID_MAX __________________________________
purpush Lower limit for user-defined event ids.
syntax public final static int RFSERVED_ID_MAX
description This constant defines the maximum value for reserved AWT event ids. Any
user-defined events should use event ids greater than RESERVED_ID_MAX. Its
value is 1999.
she also AWTEventO, getID().
fxampll See the class example.
TEXT_EVENT MASK _________________ __________________
purpose The event mask for selecting text events.
syntax public final static long TEXT-EVEN I.MASK
description This constant is passed to Component.enableEvents() and Compo-
nent »disableEventsO to enable and disable text events, respectively. See
the class description for details on event masks. The value of this constant is
0x400.
shhaiso Component.disableEvents(), Component.enableEventsO,
java.awt.event.TextEvent.
example See the similar usage of ACTION_EVENT_MASK in Menuitem.di sable
EventsC)•
toStringO
puppose Generates the string representation of this event.
s\nu\x public String toStringO
description The string representation of this event consists of the event source's class
name, the result of paramStri ngO« and the event source's component name
(Component.getNameО or MenuComponent.getNameО).
overrides java.util.Eventobject.toStringO.
see also Component. getNameO, MenuComponent.getNameО,
java.lang.Cl ass.getNameО, java.util.Eventobject.getSourceO.
example See the class example.
126
Wl.'MJUW nvn^
WINDOW^EVENT.MASK
PURPOSE Event mask for Wi ndowEvent.
SYNTAX public final static long WINDOW_EVENT_MASK
DESCRIPTION This constant is passed to Component.enableEvents0 and Compo- И1 nent .di sableEventsQ to enable and disable window events, respectively. В See the class description for details on event masks. The value of this constant f is 0x40. p
SEE ALSO Component.disableEventsQ , Component.enableFventsQ, java.awt.event.WindowEvent. t
EXAMPLE See the similar usage of ACTION_EVENT_MASK in Menuitem.di sable- F Events Q. G
н
I
J
к
L
M
N
(>
P
Q
R
S
T
U
V
w
X
java.awt
AWTEventMulticaster
К
I Syntax
public class AWTEventMulticaster implements ComponentListener,
M Contai nerLi stener, FocusLi stener,KeyLi stener, MouseLi stener,
К Мои seMotionLi stener, WindowLi stener, ActionLi stener,
ItemListener, AdjustmentLi stener, TextL istener
О
p Description
q The AWTEventMulticaster class implements a thread-safe event dispatcher for the AWT
events defined in the java. awt. event package. Each multicaster consists of two event listen-
ers. each of which can itself be a multicaster. When an event is dispatched to the top-level mul-
S ticaster. it is propagated to the multicaster's two event listeners, which in turn propagate the
T event to their event listeners, and so on. thereby, creating a multicast effect.
fhe data structure maintained by each multicaster is immutable. So it is safe to use lhe
I methods in this class to add and remove listeners during the process of an event dispatch oper-
v ation. "Updating" a multicaster basically generates a new instance of the multicaster with lhe
updated list of listeners.
w
X Event Notification in the AWT Event Model
When an event listener is registered with an AWT component (the event source}, the compo-
nent records the listener’s reference using an AWTEventMulticaster. As other listeners are
z registered with or removed from the event source, the multicaster is updated and recorded w ith
the event source.
128
Event listeners are notified synchronously in the order in which they are found in the list
maintained by the multicaster. Once an event has started down the list of listeners, it will be
delivered to all listeners in this list, even those that have been removed from event source. The
next time an event is dispatched to the same event source, the removed listener will not be
notified (because the event source is, in effect, using a new multicaster).
See AWTEvent for details on event dispatching and the event model in general.
ВМйит. summary 1 r
Constructor AWTEventMulti caste r() Constructs an AWTEventMul ticaster instance. 1 r [-
Action Event Method r;
acti onPerformed() Invokes actionPerformedO on this multicaster \ listeners. 1 V J
H
Adjustment Event Method adjustmentValueChangedО Invokes ad justmentValueChangedO on this multicastcr's 1
listeners. 1 J
Component Event Methods к
componentHiddenQ Invokes componentHiddenO on this multicaster’s listeners. L
componentMoved 0 Invokes componentMovedO on this multicaster's listeners. 1 M
componentResizedO Invokes componentResizedO on this muhicasier\ listen- 1
ers. N
componentShown О Invokes component Shown О on this multicaster’s listeners. 0
Container Event Methods componentAddedO Invokes componentAddedO on this multicaster’s listeners. P
componentRemoved() Invokes componentRemovedO on this multicaster's listen- Q
ers. R
Focus Event Methods focusGainedQ Invokes focusGai ned() on this multicaster's listeners. S
focusLostO Invokes focusLostO on this multicasier's listeners. T
Item Event Method i temStateChanged() Invokes 1 temStateChanged() on this muhicaster's listen- | 1 t; V
ers. w
Key Event Methods X
keyPressedO Invokes keyPressedO on this multicaster's listeners. Y
keyReleased 0 Invokes keyRel easedO on this muhicaster’s listeners.
keyTypedO Invokes keyTypedO on this multicaster's listeners. z
Continued |
AWTEventMulticaster
java.awt
MEMBER SUMMARY
В
C
D
E
F
G
11
I
J
К
L
M
N
О
P
Q
R
S
T
V
V
w
Mouse Event Methods
mouseFnteredO
mouseExitedO
mousePressedO
mouseReleasedO
Mouse Motion Event Methods
mouseDraggedO
mouseMovedQ
Text Event Method
textVal ueChangedO
Window Event Methods
wi ndowActi vated О
wi ndowClosedO
windowClosi ng()
wi ndowDeactivatedО
wi ndowDei coni fied()
wi ndowlconi fi ed()
wi ndowOpenedO
Listener Fields and Methods
a
add()
addTnternal()
b
remove О
removelnternalО
Serialization Methods
saveO
savelnternal()
Invokes mouseEnteredO on this multicaster's listeners.
Invokes mouseExi ted О on this multicaster's listeners.
Invokes mousePressedO on this multicaster's listeners.
Invokes mouseReleasedO on this multicaster's listeners.
Invokes mouseDraggedO on this multicaster's listeners.
Invokes mouseMovedO on this multicaster's listeners.
Invokes textVal ueChangedO on this multicaster's listen-
ers.
Invokes wi ndowActi vatedО on this multicaster's listeners.
Invokes wi ndowClosedO on this multicaster's listeners.
Invokes windowClosi ng О on this multicaster's listeners.
Invokes windowDeacti vated() on this multicaster's listen-
ers.
Invokes wi ndowDei coni fiedО on this multicaster's listen
ers.
Invokes windowlconified() on this multicaster's listeners.
Invokes windowOpenedO on this multicaster's listeners.
Contains an event listener.
Combines two listeners into a multicaster.
Combines two listeners into a multicaster.
Contains an event listener.
Removes a listener from a multicaster.
Removes one listener from a multicaster.
Writes an event listener to an object stream.
Writes this multicaster to an object stream.
See Also
java.awt.event.ActionListener, java.awt.event.AdjustmentListener,
java.awt.event.ComponentI istener, java.awt.event.ContainerListener,
java.awt.event.FocusListener, java.awt.event.ItemListener,
130
java.awt.event.KeyListener, java.awt.event.MouseListenert
java.awt.event.MouseMotionListener, java.awt.event.rextListener,
java.awt.event.WindowListener, java.util.EventListener.
Example
This example illustrates how to use rhe
AWTEventMulticaster to implement a
lightweight component. ImageButton. that
behaves like an AWT Button. However,
instead of its having a label, it has an image
as the face of the button. A second image is
displayed while the button is held down.
See Figure 29.
ImageButton overrides getPre-
ferredSizeO to be the size of the image
within the bounds of the button.
FIGURE 29: ImageButton Using ActionEvent.
its borders and overrides contains() to be
See the AWTEvent class example for a similar example, which defines a new subclass of
AWTEvent instead of using ActionEvent and ActionLi stener.
Note: mouseRel eased О calls processEventO to dispatch the event instead of calling
Component .di spatchEventO or using the system event queue. This is because in Java
1.1.2, components cannot lire a predefined event type such as ActionEvent if its superclass
does not already fire it.
import java.awt.*;
import java.awt.image;
import java.awt.event;
class Main extends Frame implements ActionListener {
Main(String upFile, String downFile) {
super(“AWTEventMuiticaster Example”);
ImageButton b - new ImageButton(getloolkit().getImage(upFile),
getToolki t().getImage(downFile),
‘Hello’1);
add(b, BorderLayout.CLNTER);
b.addActionLi stener(thi s);
setBackground(Color.li ghtCray);
pack();
show();
}
public void actionPerformed(ActionFvent evt) {
Sy stem, out. pri ntln(evt. getActionCommandO) ;
static public void mainCStringfl args) {
if (args, length == 2) {
new Main(args[0], argsflj);
} else {
System.err.println(“usaqe: java Main <imagel> <image2>”);
AWTEventMulticaster
java.awt
class ImageButton extends Component {
Image uplmage, downimage;
transient ActionListener actionListener;
String cmd;
boolean raised = true;
int borderWidth - 5;
C ImageButton(Image uplmage, Image downimage, String cmd) {
this.uplmage = uplmage;
D this.downimage = downimage;
this.cmd = cmd;
E
// Load first image to get size of button.
F MediaTracker tracker - new Medialracker(this);
try {
G tracker.addimage(uplmage, 0);
tracker .wai tForAl1(0);
H } catch (InterruptedFxception e) {
e.printStackTraceO ;
I }
addMouseLi stener(new MouseEventHandlerQ);
J }
К public Dimension getPreferredSizeO {
return new Dimension(uplmage.getWidth(null)*2*borderWidth,
L uplmage.getHeight(nul1)+2*borderWidth);
J
M
public boolean contains(int x, int y) {
N return (x < uplmage .getWidth(nul 1) i-2*borderWi dth &&
у < uplmage.getHeight(null)+2*borderwidth);
О }
P public void paint(Craphics g) {
Image image = (raised ? uplmage : downimage);
Q g.drawlmage(image, borderwidth, borderwidth, this);
R // Draw border around image
int x = 0, у = 0;
S int w - image.getWidth(this)+2*borderwidth;
int h = image.getHeight(this)+ 2*borderWidth;
T w -= 1; // draw inside the rectangle,
h 1; // draw inside the rectangle.
i; g. setColor(getBackground());
for (int i-0; i«borderwidth; i <-+) {
V g.draw3DRect(x*+, y<-+, w, h, raised);
w -- 2;
W h — 2;
}
X }
Y // Action listener management
public synchronized void addActionListener(ActionListener 1) {
Z actionListener AWTEventMulticaster.add(actionListener, 1);
}
public void removeActionListener(ActionListener 1) {
actionListener AWTEventMulticaster.remove(actionListener,
132
}
protected void processEvent(AWTEvent evt) {
if (evt instanceof ActionEvent) {
processActionEvent((ActionEvent)evt);
return;
}
super.processEvent(evt);
}
protected void processActionEvent(ActionEvent evt) {
if (actionListener != null) {
actionLi stener.actionPerformed(evt);
}
}
// Mouse handler for presses and releases inside this button
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) { (
raised = false;
repai nt О; I
}
public void mouseReleased(MouseEvent evt) {
raised = true;
repaint();
ActionEvent aevt = new ActionEvent(ImageButton.this,
Acti onEvent.ACTION_PERFORMED, 1
cmd);
processEvent(aevt); L
}
} N
}
\
(
F
a (.
purpose Field containing an event listener R
syntax protected final EventListener a $
description A multicaster consists of two event listeners, each of which can itself be a mul- 1
ticaster. This field contains one of this multicaster\ two event listeners. It is L
set by the AWTEventMulticaster constructor This field is typically not
accessed directly,
w
SEEALso AWTEventMulti casterO , b.
X
Y
actionPerformed() ?
purpose Invokes actionPerformedO on this multicaster's listeners.
java.awt
AW ТЕ ven t M ul ti caster
add()
и SYNTAX DESCRIPTION PARAMETERS public void actionPerformed(ActionEvent evt) This method is typically invoked inside a component's processAction- EventO method to dispatch the action event evt to this muhicaster's listen- ers.
в evt The non-nul 1 action event to pass on to the listeners.
с: SEE Al SO java.awt.event.ActionEvent, java.awt.event.ActionListener.
i) E EXAMPLE See the class example.
F add()
G — —- • .
H PURPOSE Combines two listeners into a multicaster.
SYNTAX public static ActionListener addfAction!istener a,
I ActionListener b)
J public static Adjustment!.!stener add(AdjustmentListener a,
к AdjustmentListener b) public static ComponentListener add(ComponentListener a,
L M ComponentListener b) public static Containerlistener add(ContainerListener a, ContainerListener b)
N public static FocusListener add(FocusListener a, FocusListener b) public static KeyListener addfKeyListener a, Keylistener b)
0 P public static Itemlistener addfltemListener a, Itemlistener b) public static MouseListener addfMouseListener a, MouseListener b) public static MouseMotionListener addCMouseMotionListener a,
Q MouseMotionListener b) public static TextListener add(TextListener a, TextListener b)
R public static WindowListener add(WindowListener a, Windowlistener b)
S DESCRIPTION This method combines two listeners, a and b, into a inulticaster and returns the
T resulting multicaster (multicast listener). If either a or b is nul 1. the other non-
U null listener is returned unmodified. If both a and b are null, null is
V w returned. Neither listeners a nor b are modified as a result of addO. Proper usage of add О requires that the result of add О be recorded and used subsequently as
X the new listener.
Y PARAMEI ERS
Z a An event listener to use. Il can be nul 1.
b An event listener to use. It can be null.
RETURNS The result of combining listeners a and b.
134
addlntemaio
SEEALSO addinternal O, AWTEventMulticasterO , removed-
example See the definition of ImageButton.addActionListener() in the class
example to see how to add an ActionLi stener to a multicaster. Addition of
the other types of listeners works in exactly the same way as in this example. ।
I
addlnternalQ(
purpose Combines two listeners into a multicaster. Г
syntax protected static EventListener addinternal(EventListener a, I
EventListener b)
description This method is the worker method used by add(). It is not typically used
directly.
F
PARAMETERS
a An event listener to use. It can be nul 1. 1
b An event listener to use. It can be nul 1. j
returns The result of combining listeners a and b.
SEEALSO add(), AWTEventMulticasterO, removelnternal(). L
К
adjustment ValueChanged() >
purpose Invokes adjustmentVal ueChangedO on this multicaster’s listeners. *
syntax public void adjustmentValueChanged(AdjustmentEvent evt) f
description This method is typically invoked inside a component’s processAdjustment-
Event () method to dispatch the adjustment event evt to this multicaster’s lis- Я
teners.
parameters
evt The non-nul 1 adjustment event to pass on to listeners.
see also j ava.awt.event.Adj ustmentEvent,
java.awt.event.Adj ustmentLi stener. V
example This example shows a typical definition of processAdjustmentEvent(): v
transient AdjustmentListener adjustmentListener; *
protected void processAdjustmentEvent(AdjustmentEvent evt) {
if (adjustmentListener ’= null) {
adjustmentListener.adjustmentValueChanged(evt); *
}
AWTEventMulticaster
AWTEventMulticaster()
jaxa.aut
AWTEventMulticasterO
Pl RPO.SL SYNTAX DESCRIPTION C onstructs a new instance of AWTEventMulticaster. protected AWTEventMulticaster(EventListener a, Eventlistener b) This constructor creates a new instance of AWTEventMulticaster using the
В two event listeners a and b. lhe constructor is typically not called directly.
c D PARAMETERS Instead, add() and remove() are called to create new instances of AWTEvent- Multicaster as needed.
E a An event listener to use. It cannot he nul1.
E b An event listener to use. h cannot be null.
G SEE Al SO add(), removeO-
К [ b
J К PI’R POSE- Field containing an event listener.
SYNTAX protected final EventListener b
L DESCRIPTION A multicaster consists of two event listeners, each of which can itself be a niul-
M ticasler. T his field contains one of this multicaster's two event listeners. It is
N set by the AWTEventMulticaster constructor. T'his field is typically not accessed directly.
\ j P Q SEE ALSO AWTEventMulticasterO, b.
R componentAd<led()
S PLRPOSL Invokes component Added О on this multicaster's listeners.
T SYNTAX public void componentAdded(ContainerEvent evt)
U DESCRIPTION This method is typically invoked inside a component's processContainer-
V w PARAMETERS EventO method to dispatch the container event evt to this multicaster's lis- teners.
X evt The non-nul 1 container event to pass on to the listeners.
Y SEE Al,SO java.awt.event.ContainerAdapter. java.awt.event.ContainerEvent,
z java.awt.event.Container.1i stener.
EXAMPLE This example shows a typical definition of processContai nerEventО:
136
transient ContainerListener containerListener;
protected void processContainerEvent(ContainerEvent evt) {
if (containerListener != null) {
swi tchfevt .getIDO) {
case ContainerEvent.COMPONENT_ADDED:
containerListener.componentAdded(evt);
break;
case ContainerEvent.COMPONENT„REMOVED: В
contai nerListener.componentRemoved(evt);
break; C
}
} D
}
E
F
componentHiddenQ G
purpose Invokes componentHiddenO on this multicaster's listeners.
syntax public void componentHiddenCComponentEvent evt)
J
description This method is typically invoked inside a component’s processCompo-
nentEventO method to dispatch the component event evt to this multi- K
caster’s listeners. L
PARAMEIERS M
evt The non-nul 1 component event to pass on to the listeners.
see also java.awt.event.ComponentAdapter, java.awt.event.ComponentEvent r
java. awt. event. Component!.! stener.
example This example shows a typical definition of processcomponent Event (): p
Q
transient Component!.!stener component!.!stener;
R
protected void processComponentEvent(ComponentEvent evt) {
if (component!.!stener >= null) { S
swi tch(evt.getlDO) {
case ComponentEvent-COMPONENT_RESIZED: T
component!.! stener.componentResized(evt);
break; ц
case ComponentEvent.COMPONENT_MOVED:
component!.! stener.componentMoved(evt) ; V
break;
case ComponentEvent.COMPONENT_SHOWN: W
component!.! stener. componentShown(evt) ; .
break; X
case ComponentEvent.COMPONENT.HIDDEN:
component!.!stener.componentHidden(evt) ; Y
break;
}
java.awt
AVVTEventMulticaster
coniponemMovcd()
componentMovecU)
PURPOSE SV MAX DESCRIP'l ION Invokes componentMovedO on this multicasterX listeners. public void componentMoved(ComponentEvent evt) This method is typically invoked inside a component's processcomponent-
В Event () method to dispatch the component event evt to this multicasicr's lis-
c teners.
D PARAMETERS
i: evt Phe non-nul 1 component event to pass on to the listeners.
SEE A [.SO java.awt.event.ComponentAdapter, java.awt.event.ComponentEvent,
1 java.awt.event.Component!i stener.
G EX A MP 1 L. See componentHiddenf).
H 1 componentRemovedl)
.! к PURPOSE Invokes componentRemovedO on this multicaster's listeners.
I S1! M AX public void componentRemoved(ContainerEvent evt)
M DESCRIPTION T his method is typically invoked inside a component's processContainer-
Event () method to dispatch the container event evt to this mu hi caster’s lis-
N teners.
() PARAMETERS
P evt The non-nul 1 container event to pass on to the listeners.
SIT- Al SO java.awt.event.ContainerAdapter, java.awt.event.ContainerEvent,
Q java.awt.event.Contai nerLi stener.
R EXAMPLE See componentAdded().
S I t * componentRc'sizedO
I. V Pl RPOSF invokes componentResizedQ on this multicaster's listeners.
w SYM AX public void componentResized(ComponentEvent evt)
X DESCRIPTION This method is typically invoked inside a component's processComponent-
Y EventO method to dispatch the component event evt to this multicaster\ lis- teners.
z PAR A METERS
evt The non-nul 1 component event to pass on to the listeners.
138
' LUJIipiHlL-IUOJKJW Щ J
SEE ALSO j ava.awt.event.ComponentAdapteг, j ava.awt.event.Componen t Event,
java.awt.event.ComponentLi stener.
example See componentHidden().
componentShown()
purpose Invokes component Shown О on this multicaster's listeners.
syntax public void componentShown(ComponentEvent evt)
description This method is typically invoked inside a component's processcomponent-
EventO method to dispatch the component event evt to this multicaster’s lis-
teners.
parameters
evt The non-nul 1 component event to pass on to the listeners.
see: also j ava. awt. event. ComponentAdapte r, j ava. awt. event. Component Event,
java.awt.event.ComponentLi stener.
example See componentHidden().
focusGainedO
purpose Invokes focusGai ned() on this multicaster’s listeners.
(
syntax public void focusGained(FocusEvent evt)
description This method is typically invoked inside a component's processFocus-
EventO method to dispatch the focus event evt to this multicaster’s listeners. (
PARAMETERS !
evt The non-nul 1 focus event to pass on to the listeners.
see also java.awt.event.FocusAdapter, java.awt.event.FocustEvent,
java.awt.event.FocusListener.
example This example shows a typical definition of processFocusEvent():
transient FocusListener focusListener;
protected void processFocusEvent(FocusEvent evt) { *
if (focusListener null) {
switch(evt .getlDO) {
case FocusEvent.FOCLS_GAINED:
focusListener.focusGained(evt);
break;
case FocusEvent.FOCUS_LOST:
focusListener.focusLost(evt);
break;
|h
AW ТЕ ven tMulticaste г
focusLostO
java.awt
Л
в focusLost()
c PURPOSE Invokes focusLostO on this multicaster's listeners.
D SYNTAX public void focuslost(FocusEvent evt)
E DESCRIPTION This method is typically invoked inside a component's processFocus-
F EventQ method to dispatch the focus event evt to this multicaster’s listeners.
PARAMETERS
и evt The non-nul 1 focus event to pass on to the listeners.
H SEE ALSO java.awt.event.FocusAdapter, java.awt.event.FocustFvent,
I java.awt.event.FocusListener.
J EXAMPLE See focusGai ned().
к
L itemStateChanged()
м
purpose Invokes i temStateChangedO on this multicaster's listeners.
N
syntax public void itemStateChanged(ItemEvent evt)
description This method is typically invoked inside a component's processItemEventO
P method to dispatch the item event evt to this multicaster's listeners.
Q
R
S
T
PARAMETERS
evt The non-nul 1 item event to pass on to the listeners.
see also java.awt.event.ItemEvent, java.awt.event.ItemListener.
example This example shows a typical definition of processItemEventO:
transient ItemListener itemListener;
V protected void processItemEvent(ItemEvent evt) {
if (itemListener 1= null) {
W i temLi stener.itemStateChanged(evt);
}
X }
Y
Z
140
keyPressedO
PUB POSE Invokes keyPressedO on (his multicaster's listeners.
SYNTAX public void keyPressed(KeyEvent evt)
description This method is typically invoked inside a component's processKeyEventO method to dispatch the key event evt to this multicaster's listeners.
PARAMETERS evt The non-nul 1 key event to pass on to the listeners.
SEE ALSO java.awt.event.KeyAdapter, java.awt.event.KeyEvent, java.awt.event.KeyL i stener.
EXAMPLE This example shows a typical definition of processKeyEventO:
transient KeyListener keyListener;
protected void processKeyEvent(KeyEvent evt) {
if (keyListener 1= null) {
} } switch(evt.getlDQ) { case KeyEvent.KEY_TYPED: keyListener.keyTyped(evt); break; case KeyEvent.KEY_PRESSED: keyListener.keyPressed(evt); break; case KeyEvent.KEY-RELEASED: keyListener.keyReleased(evt); break; }
keyReleasedO
PURPOSE- Invokes keyReleasedO on this multicaster's listeners.
SYNTAX public void keyReleased(KeyEvent evt)
DESCRIPTION This method is typically invoked inside a component's processKeyEventO method to dispatch the key event evt to this multicaster's listeners.
PARAMETERS evt The non-nul 1 key event to pass on to the listeners.
SEE А1ЛО java.awt.event.KeyAdapter, java.awt.event.KeyEvent t java.awt.event.KeyL i stener.
example See keyPressedO.
AWTEventMu Iticaster
keyTypedO
java.awt
keyTypedO
в
c
D
E
F
G
H
I
J
К
L
M
N
О
P
Q
R
S
T
u
V
w
X
Y
Z
purpose Invokes keyTypedO on this multicasler’s listeners.
syntax public void keyTyped(KeyEvent evt)
description This method is typically invoked inside a component's processKeyEvent()
method to dispatch the key event evt to this multicaster’s listeners.
PARAMETERS
evt The non-nul 1 key event to pass on to the listeners.
see also java.awt.event.KeyAdapter, java.awt.event.KeyEvent,
java.awt.event.Keyli stener.
example See key Pressed О.
mouseClickedO
purpose Invokes mouseCl i ckedO on this multicaster’s listeners.
syntax public void mouseClicked(MouseEvent evt)
description This method is typically invoked inside a component's processMouse-
EventO method to dispatch the mouse event evt to this multicaster’s listen-
ers.
PARAMETERS
evt The non-nul 1 mouse event to pass on to the listeners.
see also java.awt.event.MouseAdapter, java.awt.event.MouseEvent,
java.awt.event.MouseLi stener.
example This example shows a typical definition of processMouseEventO:
transient MouseListener mouseListener;
protected void processMouseEvent(MouseEvent evt) {
if (mouseListener ’= null) {
switch(evt.getlDQ) {
case MouseEvent.MOUSE-PRESSED:
mouseListener.mousePressed(evt);
break;
case MouseEvent.MOUSE_RELEASED:
mouseLi stener.mouseReleased(evt);
break;
case MouseEvent.MOUSE-CLICKED:
mouseLi stener.moused i eked(evt);
break;
case MouseEvent.MOUSE-EXITED:
mouseLi stener.mouseExi ted(evt);
break;
case MouseEvent.MOUSE-ENTERED:
mouseLi stener.mouseEntered(evt);
142
break;
}
}
}
I
mousePraggedQ
purpose Invokes mouseDraggedO on this multicaster's listeners.
syntax public void mouseDraggedfMouseEvent evt)
description This method is typically invoked inside a component’s processMouse-
Moti onEvent О method to dispatch the mouse motion event evt to this multi-
caster’s listeners.
PARAMETERS
evt The non-nul 1 mouse event to pass on to the listeners.
SEE also java.awt.event.MouseMoti onAdapter, j ava.awt.event.MouseEvent,
j ava.awt.event.MouseMotionLi stener.
example This example shows a typical definition of processMouseMoti onEvent():
transient MouseMotionListener mouseMotionListener;
protected void processMouseMotionEvent(MouseEvent evt) {
if (mouseMotionListener != null) {
switch(evt .getIDO) {
case MouseEvent.MOUSE-MOVED:
mouseMotionLi stener.mouseMoved(evt);
break;
case MouseEvent.MOUSE-DRAGGED:
mouseMotionLi stener.mouseDragged(evt);
break;
}
}
}
mouseEn teredO
PURPOSE Invokes mouseEntered() on this multicaster’s listeners.
SYNTAX public void mouseEntered(MouseEvent evt)
DESCRIPTION This method is typically invoked inside a component's processMouse- Event() method to dispatch the mouse event evt to this multicaster’s listen- ers.
AWTEventMulticaster
mouscExiledO
java.awt
PARAMETERS
evt The non-nul 1 mouse event to pass on to the listeners.
SEE ALSO java.awt.event.MouseAdapter, java.awt.event.MouseEvent, java.awt.event.MouseListener.
EXAMPLE See moused i eked О.
В
mouseExitedQ
C
D
E
Г
G
H
I
J
К
1,
M
Pt rpose Invokes mouseExi ted О on this multicaster’s listeners.
syntax public void mouseExitedfMouseEvent evt)
descrip non This method is typically invoked inside a component's processMouse-
EventO method to dispatch the mouse event evt to this multicaster's listen-
ers.
PARAMETERS
evt The non-nul 1 mouse event to pass on to the listeners.
see also java. awt. event. Mouse.Adapter, java, awt. event. MouseEvent,
java.awt.event.MouseListener.
example See mou seC 1 i eked О.
mouseMoved()
P purpose Invokes mouseMovedO on this multicaster's listeners.
Q SYNTAX public void mouseMoved(MouseEvent evt)
R DESCRIPTION This method is typically invoked inside a component's processMouse-
s MotionEventO method to dispatch the mouse motion event evt to this multi-
T PARAMEIERS caster's listeners.
i: evt The non-nul 1 mouse event to pass on to the listeners.
V SEE ALSO java.awt.event.MouseMotionAdapter, java.awt.event.MouseEvent ,
w java.awt.event.MouseMotionti stener.
X EXAMPLE See mouseDraggedO.
z mousePressedO
pi rposi Invokes mousePressedO on this multicaster's listeners.
144
syntax public void mousePressed(MouseEvent evt)
। пои лч i\uiua.KU \ /
description This method is typically invoked inside a component’s processMouse-
Event О method to dispatch the mouse event evt to this multicaster’s listen-
PARAMETERS “
evt The non-nul 1 mouse event to pass on to the listeners. B
see also java.awt.event.MouseAdapter, java.awt.event.MouseEvent, c
java.awt.event.MouseLi stener.
example See moused i eked ().
F
mouseReleasedO о
PURPOSE Invokes mouseReleasedO on this multicaster’s listeners. H
SYNTAX public void mouseReleased(MouseEvent evt) I
DESCRIPTION This method is typically invoked inside a component’s processMouse- J
Event() method to dispatch (he mouse event evt to this multicaster’s listen- К
ers. L
PARAMETERS M
evt The non-nul 1 mouse event to pass on to the listeners.
SEE ALSO java.awt.event.MouseAdapter, java.awt.event.MouseEvent, N
java.awt.event.MouseLi stener, 0
EXAMPLE See moused i eked(). P
Q
removeO R
— $
purpose Removes an event listener from this multicaster.
T
syntax protected EventListener remove(EventListener target)
public static ActionListener remove(ActionListener me,
ActionListener target) v
public static Adjustmentsstener remove(AdjustmentListener me,
AdjustmentListener target) W
public static ComponentListener remove(ComponentListener me,
ComponentListener target) X
public static ContainerListener remove(Containerlistener me, у
ContainerListener target)
public static FocusListener remove(FocusListener me, FocusListener Z
target)
java.awt
AWTEventMulticaster
removelnternah)
public static Itemlistener removeCltemListener me. TtemListener
target)
public static KeyListener remove(Keyl istener me, KeyListener
target)
public static wouseListener remove(MouseListener me. ^ouseListener
target)
public static MouseMotionListener remove(MouseMotionListener me,
MouseMotionListener target)
public static TextListener remove(TextListener me, lextlistener
target)
public static Windowlistener remove(Windowl istener me,
WindowListener target)
description The first form of this method removes the event listener, target, from this
muhicaster. If target is not in the list of listeners managed by this muhicaster.
this multicaster is returned. If target is being managed by this muhicaster. a
new muhicaster is created and returned using the rest of the listeners with
target removed.
The rest of the forms of this method remove the event listener, target, from
the muhicaster me. If target is not in the list of listeners managed by me. it is
ignored and me is returned. Otherwise, a new muhicaster of the same type as
me is created and returned using the rest of the listeners with target removed.
Neither me nor target are modified as a result of remove() . Proper usage of
remove () requires that the result of remove О be recorded and used subse-
quently as the new lisiener/multicaster.
PARAMLILRS
me The muhicaster from which to remove target. It can be null.
target The non-nul 1 listener to be removed.
retlrns A muhicaster with target removed.
see also add(), removelnternal().
example See the definition of ImageButton. removeActionLi stener() in the class
example for removing an ActionLi stener from a multicusicr. The removal
of the other types of listeners works in exactly the same way as in ibis exam-
pie.
removelnterrialO
plrpose. Removes a listener from a muhicaster.
syxiax protected static EventListener removelnternal(EventListener me,
Fventl istener target)
146
suvei}
description This method is the worker method used by remove О. It is typically not used directly.
para met lrs me target The multicaster from which to remove target. It may be null. The non-nul 1 listener to be removed.
RETURNS A multicaster with target removed.
SEE ALSO add(), remove().
save()
PURPOSE Writes an event listener to an object stream.
SYNTAX protected static, void save(ObjectOutputStream out, String key, EventListener target) throws TOFxception
DESCRIPI'ION This method writes the serialized forms of key and target to the object out- put stream out. Because a listener can implement multiple listener interfaces, key is a string (e.g., "actionL’') that identifies the interface of interest. When the listener object is subsequently deserialized, key is used by the deserializing code to identify whether the interface is one of interest.
PARAMETERS key out target A non-nul 1 string identifying the listener interface of the target of interest. The non-nul 1 object output stream to which to write. The listener to serialize. It can be null, in which case, nothing is written out.
SEE ALSO java.io.lOException, java.io.ObjectOutputStream, java.io.Seri alizable, java.util.FventLi stener, savelnternal().
EXAMPLE This code fragment illustrates how a serialization routine would typically use save().
final static String actionListenerK - “actionL";
transient ActionListener actionListener;
private void writeObject(ObjectOutputStream s)
throws lOException {
s.defaultWri teObject();
AWTEventMulticaster.save(s, actionListenerK, actionListener);
s.wri teObject(nul1);
AW ТЕventM u 1 ti caster
java.awt
savelntemaK)
savelnternalO
PURPOSE Writes this multicaster to an object stream.
SYNTAX protected void saveinternal(ObjectOutputStream out, String key)
throws lOException
в INSCRIPTION This method writes the serialized forms of key and this multicaster to the
Г’ object output stream out. Because this multicaster can be used for multiple lis-
tener interfaces, key is a string (e.g., "actionL”) that identifies the interface of
D interest. When this multicaster is subsequently deserialized, key is used by the
I: deserializing code to identify whether the interface is one of interest.
F This method is a worker method used by save О and is not intended to be used directly.
G PARAMETERS
H key A non-nul 1 siring identifying the listener interface of the target of interest.
1 out The non-nul 1 object output stream to which to write.
J SE.L ALSO java.io.lOException, java.iо.ObjectOutputStream, java.io.Serializable, java,util.EventListener, save().
К
L M N text ValueC hanged ()
PURPOSE Invokes textValueChangedO on this multicaster's listeners.
() SYNTAX public void textValueChanged(TextEvent evt)
P DESCRIPTION This method is typically invoked inside a component s processTextEvent0
Q method to dispatch the text event evt to this multicaster's listeners.
PARAMETERS
К evt rhe non-nul 1 text event to pass on to the listeners.
S SEE ALSO java.awt.event.TextEvent, java,awt.event.TextListener.
1 EX AMPLE This example shows a typical definition of processTextEventО:
L transient protected TextListener textListener;
V protected void processTextEvent(TextEvent evt) {
W if (textListener != null) {
X textLi stener.textValueChanged(evt); }
}
Y
148
window Activated()
PURPOSE Invokes windowActi vatedO on this multicaster's listeners.
SYNTAX public void windowActivated(WindowEvent evt)
description This method is typically invoked inside a component’s processWi ndow- Event () method to dispatch the window event evt to this multicaster’s listen- ers.
PARAMETERS evt The non-nul 1 window event to pass on to the listeners.
SEE ALSO java.awt.event.WindowAdapter, java.awt.event.WindowEvent, java.awt.event.WindowLi stener.
example This example shows a typical definition of processWi ndowEvent():
transient WindowListener windowListener;
protected void processWindowEvent(WindowEvent evt) {
if (windowListener null) {
} switch(evt.getID()) { case WindowEvent.WINDOW-OPENED: wi ndowLi stener.windowOpened(evt); break; case WindowEvent.WINDOW-CLOSING: windowLi stener.windowClosing(evt); break; case WindowEvent.WINDOW-CLOSED: windowLi stener.windowClosed(evt); break; case WindowEvent.WINDOW.ICONIFIED: windowLi stener.windowlconified(evt); break; case WindowEvent.WINDOW-DEICONIFIED: wi ndowLi stener.windowDei conified(evt); break; case WindowEvent.WINDOW_>CTIVATED: windowLi stener.windowActivated(evt); break; case Wi ndowEvent.WINDOW-DEACTIVATED: wi ndowLi stener.windowDeactivated(evt); break; }
windowClosedO
PURPOSE Invokes windowClosedO on this multicaster’s listeners.
SYNTAX public void windowClosed(WindowEvent evt)
AWTEventMulticaster
windowClosingO
java.awt
DESCRIPTION This method is typically invoked inside a component's processWindow- EventO method to dispatch the w indow event evt to this multicaster's listen- ers.
PAR AMI; 1 LRS evt The non-nul 1 window event to pass on to the listeners.
В SEE ALSO java.awt.event.Wi ndowAdapter, java.awt.event.WindowFvent,
c java.awt.event.Wi ndowLi stener.
D EX AM PI 1 See wi ndowActi vated().
f windowClosingO
pirposp Invokes wi ndowClosi ngO on this multicaster's listeners.
syntax public void windowClosing(WindowEvent evt)
1 description This method is typically invoked inside a component's processwindow
J Event () method to dispatch the window event evt to this multicaster's listen-
J PARAMETERS
evt The non-nul 1 window event to pass on to the listeners.
M
see also java.awt.event.WindowAdapter, java.awt.event.WindowEvent,
N java.awt.event.WindowLi stener.
ex ample See wi ndowActivated().
P
Q windowDeactivatedO
R PURPOSE Invokes windowDeactivatedO on this multicaster's listeners.
S SYN'I AX public void windowDeactivated(WindowEvent evt)
T DESCRIPTION This method is typically invoked inside a component's processWindow-
и EventO method to dispatch the window event evt to this multicaster’s listen-
V ers.
w PARAMETERS
x evt The non-nul 1 window event to pass on to the listeners.
SLL A1,S() java.awt.event.Wi ndowAdapter, java.awt.event.WindowFvent,
Y j ava.awt.event.Wi ndowLi stene r.
Z EX AM PI E See wi ndowDeacti vated О.
150
windowDeiconified()
PURPOSE Invokes windowDeiconified() on this multicaster’s listeners.
SYNTAX public void windowDeiconified(WindowEvent evt)
DESCRIPTION This method is typically invoked inside a component’s processWindow- EventO method to dispatch the window event evt to this multicaster’s listen- ers.
parameters evt The non-nul 1 window event to pass on to the listeners.
SEE Al^SO java.awt.event.WindowAdapter, java.awt.event.Wi ndowEvent, j ava.awt.event.Wi ndowLi s tener.
EXAMPLE See wi ndowActivated().
windowIconifiedO
PURPOSE Invokes windowIconifiedO on this multicaster s listeners.
SYNTAX public void windowlconified(WindowEvent evt)
DESCRIPTION This method is typically invoked inside a component's processWindow- EventO method to dispatch the window event evt to this multicaster’s listen- ers.
PARAMETERS evt The non-nul 1 window event to pass on to the listeners.
SEE ALSO java.awt.event.WindowAdapter, java.awt.event.WindowEvent, j ava.awt.event.Wi ndowLi stene г.
EXAMPLE See wi ndowActi vated().
windowOpenedO
PURPOSE Invokes windowOpened() on this multicaster's listeners.
SYNTAX public void windowOpened(WindowEvent evt)
DESCRIPTION This method is typically invoked inside a component's processWindow- EventO method to dispatch the window event evt to this multicaster's listen- ers.
paramefers evt The non-nul 1 window event to pass on to the listeners.
AWTEventMulticaster
windowOpened()
java.awt
see also j ava.awt.event.Wi ndowAdapter, j ava.awt.event.Wi ndov
java.awt.event.Wi ndowLi stener.
example See wi ndowActi vat ed О.
В
c
D
E
F
G
H
i
J
К
L
M
N
О
P
Q
R
S
T
c
V
w
X
Y
Z
152
AWTException
В
с
г>
<*! . f Г -,П <г ГН'Г jj,d:X.} К»! Pot i •>»' ;-iV<3 .<1Г>Э Kxc'-pt.' tri ' < >3 •' I <- 1
F
Syntax g
public class AWTException extends Exception
Description AWTException is an exception that is thrown when the program encounters an exception in , J
the AWT. It currently is not thrown by any method in the Java runtime or its libraries. К
L
Member summary M
Constructor N
AWTExceptionO Constructs an AWTException instance. О
AWTException() P Q R
purpose Constructs an AWTException instance. S
syntax public AWTExceptionfString msg) T
description This constructor creates a new instance of AWTException. The string msg и
describes this particular instance of the exception. V
PARAMETERS w
ms9 A string that gives details about this exception. X
Y
Z
java, beans
BeanDescriptor
/X
c
D
E
F
G
H
I
J
К
L
M
N
О
P
Q
R
S
T
u
V
w
Syntax
public class BeanDescriptor extends FeatureDescriptor
Description
A bean descriptor contains global information about
a bean, such its localized name and a localized
description. The bean descriptor can be retrieved
through the introspector by calling Introspec-
tor .getBeanJ nfo().getBeanDescr i ptor О.
For Bean Editors Only
The information contained in a bean descriptor is
meant for programs such as bean editors (programs
that help connect together beans into an application)
and is not used by the bean itself. The bean descrip-
tor. along with other descriptor types, essentially
allows a bean editor to construct a meaningful user
interface for editing the bean. When the bean is actu-
ally running in an application, the bean descriptor is
never used.
Introspector
Implicit
Descriptors
Explicit
Descriptors
Bean
Bean Descriptor I
Event Set Descriptors i
Method Descriptors |
Parameter Descriptors
Property Descriptors
BeanJnfo
X
Y
Z
FIGURE 30: BeanDescriptor
Implicit and Explicit Bean Descriptors
When retrieving the bean descriptor, the introspector
first looks in the bean's bean-info (see Beaninfo) for a bean descriptor that the bean has
explicitly supplied. This is called an explicit bean descriptor. If one is not found, the introspec
tor creates an implicit bean descriptor with some default values. See Figure 30. Table 5 shows
the attributes of a bean descriptor and what they contain. Also shown are the default \alues for
an implicit bean descriptor.
154
Attribute Contents Implicit Default Value
Bean class Customizer class The bean’s Class object The bean's customizer Cl ass object. The bean’s Class object ‘ null |
Name Display name if any. The beans nonlocalized name. The bean's localized name. i The bean's class name with- out the package name. 1 The bean's class name with-
Short description Expert Л localized description of the bean. true if the bean is considered for use out the package name. The bean's class name with- out the package name. ( false j
Hidden by experts only. true if the bean is meant to be used by a tool; fal se if it is meant to be use by a person. false 1
TABLE 5: Bean Descriptor Attributes and Their Default Values. I
(
KfHBI SUMMARY 1
Constructor (
BeanDescri ptor() Constructs a BeanDescri ptor instance. I
Attribute Methods 4
getBeanClassO Retrieves this bean descriptor's bean Cl ass object.
getCustomizerClassO t Retrieves this bean descriptor's customizer Class object. I
V
See Also
Beanlnfo.getBeanDescri ptor О » Customi zer, java.lang.Cl ass. >
Example
This example demonstrates how io use the information in a bean descriptor. For an example of
how to associate a bean descriptor with a bean, sec the BeanDescri ptor constructor example
Bean Descriptor
java.beans
FlGURE 31: A Bean Customizen
When given the filename of a class file containing a bean with a customizes this program
creates an instance of the bean and its customizer. It then displays a frame containing a full}
functional customi/er. Figure 31 shows the frame when the program is run on the bean in the
Customizer class example. You can run this example b\ executing the command (assuming
you have the example files for this book):
Windows java ..\Customizer\Bean.class
Un|x java Main ../Customizer/Bean.class
The program uses a simple class loader that can load the bean from a file. The simple class
loader requires that the bean-info class file be in the same directory as the bean class file. One
improvement that could be made to this program is to allow the user to serialize the bean after
it has been modified with the customizer.
This example uses the FileClassLoader class. The source code for FileClassLoader
is in the Introspector class example.
import java.awt.*;
import java.beans.*;
class Main {
public static void main(String[] args) {
if (args, length { = 1) {
System, err. printlnC'Usage: java Main <name of bean class filo”):
System.exi t(l);
}
try {
// Get the bean class and customizer class.
156
Dean i jescnpioru
// (See the Introspector class example for FileClassLoader
// source code.)
Class beanClass = FileClassLoader.load(args[0]);
Beaninfo beaninfo = Introspector.getBeanlnfo(beanClass);
BeanDescriptor beanDesc ~ beaninfo.getBeanDescriptor();
Class customizerClass = (Class)beanDesc.getCustomizerClassO;
Л
if (customizerClass != null) {
try { П
// Instantiate the bean and customizer.
Object bean = beanClass.newlnstanceО; C
Customizer customizer •
(Customi zer) customi zerClass.newlnstance(); D
// Initialize the customizer. E
customizer.setObject(bean);
F
// Create a frame for the customizer.
Frame frame - new FrameC’BeanDescriptor Example"); G
frame.add((Component)customi zer);
frame, pack (); 11
frame.show();
} catch (InstantiationException e) { I
e.printStackTraceO;
} catch (IllegalAccessException e) { J
e.pri ntStackTrace();
} К
}
L
} catch (IntrospectionException e) {
e.printStackTraceO; M
}
} N
О
P
BeanDescriptor() Q
r
purpose Constructs a BeanDescri ptor instance.
s
syntax public BeanDescriptor(Class beanClass)
public BeanDescriptor(Class beanClass, Class customizerClass) T
description This constructor creates a bean descriptor for bean specified by beanClass. If
the bean has a customizer (see Customizer), the customizer's Class object v
should be supplied as customi zerCl ass.
If the bean does not have a customizer, it can set customizerClass to be
nul 1. If customi zerCl ass is not specified, it defaults to nul 1. x
A bean descriptor also has attributes that are inherited from FeatureDe- Y
scriptor. The default values for these attributes in a new constructed bean
descriptor is show in Table 5.
java, beans
A
В
C
Г)
r:
r
G
н
i
j
к
I.
M
N
()
I5
Q
R
S
T
I1
V
w
X
Y
Z
Bean Descriptor
Bean Descriptor)
PARAMI-'l kRS
beanClass The bean's non-nul 1 Class object.
customi zerClass
The possibly null customizer's Class object.
sr-т. also Beaninfo.getBeanDescriptor(), Introspector.getBeanlnfo().
lxampi l This example implements a simple bean. It is a canvas component that paints
the color red. The bean provides a bean-info that overrides all the default val-
ues. The example also demonstrates the use of resource bundles to help local-
ize the display name and short description.
Figure 32 shows a picture of the Beanbox's toolbox w ith the example bean
loaded. Notice that it displays the localized bean name.
A bean-info is necessary to
associate the new bean
descriptor information vv ith
the bean. The bean-info
must be defined in a class
with the bean's unqualified
class name appended with
"Beaninfo". which in this
case, is BeanBeanlnfo.
For an example of a bean
descriptor where the cus-
tomizer Class object is not
null, see the Customizer
class example.
Bean.java
•import java.awt.-;
public class Bean extends Canvas {
public Bean() {
setSize(50, 50);
setboreground(Color.red);
}
public void paint(Graphics g) {
g.fillRect(0, 0, getSize().width,
}
« BeanBox RI-TB3
Fite Edit View Help
. ToolBox ИИЕЗ|
BeanBox
Rouge Bean
FKiLRH 32: A Simple Bean.
getSi ze().hei ght);
}
/-••
mani fest.txt:
Name: Bean.cl ass
Java-Bean: True
jar command:
jar cfm bean, jar manifest.txt “.class ’’.properties
158
gCLDUdlJV ШМЦ }
BeanBeanlnfo.java
import java.beans.*;
import java.util
public class BeanBeanlnfo extends SimpleBeaninfo {
public BeanDescriptor getBeanDescriptor() {
BeanDescriptor bd = new BeanDescriptor(Bean.class): '
bd.setName("Red Bean"); Ц
bd.setExpert(true);
bd.setHidden(true); <
// Pretend we're in the French locale. Г
ResourceBundle bundle = ResourceBundle.getBundle("redbean",
Locale.FRENCH); 1
// Get the localized color name. 1
String name = bundle.getStringC'red");
// Modify the name by capitalizing it and then appending ” Bean”;
name = Character.toUpperCase(name.charAt(0)) + name.substring(l)
+ " Bean";
bd.setDi splayName(name);
// Get the localized short description.
bd.setShortDescription(bundle.getString("descri ption"));
return bd;
b
red bean, properties.java
red=red
description=This bean is very red!
(
redbean. fr.properties.java }
red=rouge
descri pti on=Cest bean est tres rouge! (
F
getBeanClassQ n
purpose Retrieves this bean descriptor’s bean Cl ass object. i
syntax public Class getBeanClassQ \
description This method is typically called by a bean editor when it needs to instantiate the v
bean. This method returns the bean Class object as supplied in the construe- *
tor.
returns The non-nul 1 Class object of the bean.
example See the class example.
BeanDescriptor
getCustomizerClass()
java.beans
getCustomizerClass()
PURPOSE Retrieves this bean descriptor's customizer Class object.
SYNTAX public Class getCustomizerClass()
DESCRIPTION This method is typically called by a bean editor when it needs to instantiate the bean's customizer. This method returns the customizer Class object as sup- plied in the constructor. If the bean does not have a customizer, this method returns null.
RETURN’S The possibly null Class object for the beans customizer.
EXAMPLE See the class example.
160
Syntax
public interface Beaninfo
Description
When a bean editor loads a bean, it asks the introspec-
tor (see Introspector) to construct a set of feature
descriptors (see FeatureDescriptor) that contain
information used by a bean editor to create an inter-
face for editing the bean. By default, the introspector
uses a process called introspection to discover the fea-
ture descriptors for a bean. This process basically
involves detecting signature patterns in the bean's pub-
lic methods (see Introspector for more details).
However, some feature descriptors created by this
process may not have the desired values, since there
are some things (hat the introspector cannot deter-
mine. In this case, the bean must provide explicit fea-
ture descriptors for the introspector. For example,
since the introspector cannot tell if a property is
bound, it creates property descriptors whose bound
attributes are set to false. If the property is indeed
bound, the bean must supply an explicit property
descriptor in which the bound attribute is set. These explicit feature descriptors are packaged
in an object called a bean-info. See Figure 33.
There are four categories of feature descriptors in a bean-info, as follows:
1. Bean
2. Event set
3. Method
4. Property
When explicit feature descriptors are available in any of these categories, the introspector uses
those feature descriptors and does not apply introspection to discover those feature descriptors.
However, if a category does not contain any explicit feature descriptors (that is, it has the value
null), the introspector applies introspection to discover those feature descriptors. For exam-
ple, if a bean-info contains only a few explicit property descriptors, the introspector uses them
and then applies introspection to discover the feature descriptors in the other three categories.
Introspector
Explicit
Descriptors / \
- o>__________________t
Bean Descriptor
Event Set Descriptors
Method Descriptors
Parameter Descriptors
Property Descriptors
Bean-Info
FIGURE 33: Bean-info.
Beaninfo
java, beans
The SimpleBeaninfo class is a convenient class with which to build a bean info. See
SimpleBeaninfo for more details.
The Name of the Hean-bifo
A bean-info is an object defined by a class. The name of the bean-info class must be the name
of the bean class name appended with "Beaninfo". For example, if the bean class name is
"SpreadSheetCel 1 ", the bean info class name must be "SpreadSheetCelIBeanlnfo".
When the introspector looks for a bean's bean-info, it assembles the bean-info class name
and then uses a class loader to locate the bean info class file, hi some cases, a bean-info class
tile is located in the same directory as the bean class file. However, you can give the introspec
tor a path to search for a bean's bean-info.
Default Property and Event Set
One of bean s properties can be designated the default property. which means that it is the most
commonly used property Likewise, one of the bean’s event sets can be designated the default
event set.
A bean editor may use the default designation in different ways. For example, in the case
in w'hich some action causes a list of properties to be displayed, the bean editor can select the
default property by default.
1 MEMBER SUMMARY l LU
I Descriptor Methods getBeanDescriptorO gettventSetDescri ptorsf) getMethodDescri ptors О getPropertyDescri ptorsО Retrieves the bean-info's bean descriptor. [ Retrieves the bean-info's event set descriptois. Retrieves the bean-info’s method descriptors. Retrieves the bean-info's properly descriptors. ।
Additional Info Method getAddi tionalBeaninfo() Retrieves a set of additional bean info objects.
Default Methods getDefaul tEventlndexQ getDefault PropertyIndex() Retrieves the index of the bean-info's default event set. Retrieves the index of the bean-info's default properly.
Icon Constants and Methods I getlconQ 1 ICON COLOR,16x16 ICON_COLOR_32x32 ICON—MONO, 16x16 ICON „MONO., 32x32 Retrieves the bean-info’s icon. Icon type for a 16-x 16 color image. Icon type for a 32-x 32 color image. I Icon type for a 16-х-16 monochrome image. Icon type for a 32 x-32 monochrome image.
162
See Also
BeanDescriptor, FventSetDescriptor, TndexedPropertyDescriptor,
Introspector, MethodDescriptor, PropertyDescriptor, SimpleBeanTnfo.
Example
See the Simpl eBeaninfo class example.
getAdditionalBeanInfo()
PURPOSE Retrieves a sei of additional bean-info objects.
SYNTAX Beanlnfof] getAdditiona1 BeanInfo()
DESCRIPTION A bean may provide additional bean-info objects in addition to its own. This gives a bean editor more information for editing the bean. In practice, lhe addi- tional bean-info objects are typically of lhe bean’s superclasses. For example, if a bean extends from Component, it may include the component's bean-info in the list of additional bean-info objects. In this way. the user will be able to edit not only the bean’s features (properties, methods, and so on), but also the component's features. If additional bean info objects are available, this method should return them in an array. If there are any conflicts between the bean-info objects in the returned array, the bean-info object with the highest index takes precedence (for exam- ple, one property descriptor says a property is bound, while the other says it is not). However, the descriptors in the bean s main bean-info information take precedence over the bean-info objects in the returned array.
RETURNS A possibly null array of bean-info objects. The length of the array indicates the number of bean-info objects.
example See the SimpleBeaninfo class example.
getBeanDescriptorf)
PURPOSE- Retrieves the bean-infos bean descriptor.
SYNTAX BeanDescriptor getBeanDescriptor()
DESCRIPTION If an explicit bean descriptor is available, this method should return it. Other- wise. it should return null. This method is typically called by the introspector (see Introspector). When this method returns null, the introspector determines the bean descriptor through introspection.
java, beans
Beaninfo
getDetaultl:ventlndex()
retvrns A possibly null bean descriptor, si im so BeanDescri ptor.
A i:\ampi i See the BeanDescri ptor class example. getDefaultEventIndex()
. — — — — —
1) U‘ pvrposl Retrieves the index of the bean-info’s default event set. syntax int getDefau 1 tFventlndexO
b G descripiion One of bean's event sets can be designated the default event \et. This means that it is the most commonly used event set. If a default event set exists, this method should return the index of the event set descriptor for the default event
H ( set within the array returned by getEventSetDescr i ptorsQ- If getEventSetDescri ptorsO returns null, this method must return -1.
J retirxs The index of the default event set in the getEventSetDescriptors() array or -1 if no event set exists.
К sit also getEventSetDescriptors(), EventSetDescriptor.
L M example See the Simpl eBean Info class example.
N 0 get Default Property I ndex()
P pi. rposi- Retrieves the index of the bean-info's default property.
Q syxjax int getDefaul tPropertyfndexQ
R description One of bean's properties can be designated the default propc n\\ This means
S that it is the most commonly used property If a default property exists, this method should return the index of the property descriptor for the default prop-
T и erty within the array returned by getPropertyDescriptorsO If getPropertyDescri ptorsO returns null, ihis method must return -1.
V reitrxs The index of the default property in the getPropertyDescri ptorsO array.
w or -1 if no default property exists.
vv v see also getPropertyDescriptorsO. PropertyDescriptor.
Л Y 7 example Sec the Si mpl eBeaninfo class example.
164
getEventSetDescriptors()
purpose Retrieves the bean-info's event set descriptors.
syntax EventSetDescriptor[] getEventSetDescriptors()
description If the bean-info has any explicit event sei descriptors, this method should
return them in an array. Otherwise, it should return null.
This method is typically called by the introspector (see Introspector). When
this method returns null, the introspector determines the bean's event sets
through introspection.
returns A possibly null array of event set descriptors. The length of the array indi-
cates the number of event set descriptors.
SEE also EventSetDescri ptor.
example See the EventSetDescri ptor class example.
getlconO
purpose Retrieves the bean-info's icon.
SYNTAX Image getlconfint iconKind)
description This method should return an image that a bean editor can use to represent the
bean. It should return null if no image is available. If the requested icon is a
color image but is not available, the method may return a monochrome image
in the requested size.
The background pixels of the returned image should be transparent.
parameters
iconKind The desired icon type. Must be one of IC0N_C0L0R_16xl6.
ICON_COLOR_32x32. ICON_MONO_16xl6. orICON_MONO^32x32.
returns A possibly nul 1 image representing the bean’s icon.
seealso java.awt. Image.
example See the class example.
getMethodDescriptors()
purpose Retrieves the bean-info's method descriptors.
MethodDescriptor[] getMethodDescriptors()
7
I
(
I
r
F
c
I-
I
F
I
X
\
(
I
(
F
1
I
\
V
SYNTAX
Beaninfo
java.beans
getPropertyDcscriptors()
DESCRIPTION If the bean-info has any explicit method descriptors, this method should return them in an array. Otherwise, it should return null. This method is typically called by the introspector (see Introspector). When this method returns null, the introspector determines the bean's methods through introspection.
REII’RNS A possibly null array of method descriptors, rhe length of the array indicates lhe number of method descriptors.
SH ALSO MethodDescri ptor.
ex am pi e: See the MethodDescri ptor class example.
getPropertyDescriptors()
Pl R POSE Retrieves the bean-info's property descriptors.
S>N1'AX PropertyDescr iptor[] getPropertyDescriptors()
DESCRIPTION If the bean-info has any explicit property descriptors, this method should return them in an array. Otherwise, it should return null. Any indexed property descriptors should also be included in the returned array. The caller can determine which property descriptors arc indexed property descriptors by using the instanceof operator. This method is typically called by the introspector (see Introspector). When this method returns null, the introspector determines the beans properties through introspection.
RETURNS A possibly null array of property descriptors. The length of the array indi- cates the number of property descriptors.
SEE ALSO PropertyDescr!ptor.
EXAMPLE See the PropertyDescr!ptor class example.
ICON COLOR. 16x16
Pl RH )SE Icon type for а 16-х-16 color image.
SVVI .AX final static int TCON_COLOR .16x16
DESCRIPTION This constant (value 1) is used by a bean editor in a call to get I con () to fetch an icon’image from the bean-info.
SEE ALSO getlconO
EXAMPLE See the SimpleBeaninfo class example.
166
ICON COLOR 32x32
PURPOSE Icon type for a 32-X-32 color image.
SYNTAX final static int ICON_COLOR_32x32
DESCRIPTION This constant (value 2) is used by a bean editor in a call to getlcon() to fetch an icon image from the bean-info.
SEE ALSO getlconO.
example See the Simpl eBeaninfo class example.
ICON MONO 16xl6
PURPOSE Icon type for a 16-x-16 monochrome image.
SYNTAX final static int ICON_MONO_16xl6
DESCRIPTION This constant (value 3) is used by a bean editor in a call to getlconO to fetch an icon image from the bean-info.
SEE ALSO getlconO.
EXAMPLE See the SimpleBeanlnfo class example.
ICON MONO32x32
PURPOSE Icon type for a 32-X-32 monochrome image.
SYNTAX final static int ICON_MONO_32x32
description This constant (value 4) is used by a bean editor in a call to getlconO to fetch an icon image from the bean-info.
SEE ALSO getlconO.
EXAMPLE See the SimpleBeaninfo class example.
java.beans
Beans
c Syntax
О public class Beans
L
Description
1 The Beans class contains methods that apply to the bean environment. A bean environment is
<i an environment that can load and instantiate beans. Any changes to the state of this class are
H seen by all beans in the bean environment.
1 GUI Available
j The bean environment may or may not support a window system. If it does support a window
system, the bean can create and show ?\WT components such as buttons and dialog boxes. An
K example of a bean enviionment that does not support a window system might be a server
L machine or a batch job.
M
Design Time
N A bean environment may or may not be in design-time. When in design-time, the beans can be
edited and configured by the user. When not in design-time, the beans cannot be edited, but the
user can still interact with the beans.
p Some bean environments can only instantiate beans. In such environments, the design-
q time flag is always false. Other bean environments, such a bean editor, allow the user to edit
and configure its beans. In these environments, the state of the design-time tlag can be con-
trolled by the user.
S
T MEMBER SUMMARY
и V InstanceOf Methods getlnstanceOfО Casts the bean object into a superclass.
w i slnstanceOf() Determines if a bean is a subclass of another class.
X Y Instantiate Method instantiateO Creates a new instance of a bean.
Z ' Design Time Methods IsDesignlimeO Retrieves the environment's design-time flag.
setDesignTimeO Modifies the environment’s design-lime flag.
168
SUMMARY _________________________________________
GUI Available Methods
isGuiAvai lableO Determines if the environment supports a window system.
setGuiAvallable() Indicates whether the environment supports a window system
See Also
Visibility.
Example
This example implements a bean that animates an image by
shrinking and growing it. In design-time mode, the bean allows
the user to change the location of the image by clicking any-
where on its bounds. In normal-use mode, the bean goes into its
animation loop.
The main program instantiates the bean and initializes itself
in design-time mode. It provides a checkbox for changing the
state of the design-time mode. See Figure 34.
. Beans Ex. f-b
import java.awt.*;
import java.awt.event.*;
import java.beans;
class Main extends Frame implements ItemListener {
static Bean bean;
Checkbox designTimeCb =
new CheckboxCDesignTi me" , true);
P" :Des ignTirhe
FIGURE 34: Design-time
and Normal-use Modes,
Main О {
superC'Beans Example1’);
// Listen for action events.
designTimeCb.addltemLi stener(thi s);
// Layout components.
add(bean, BorderLayout.CENTER);
add(designTimeCb, BorderLayout.SOUTH);
setSize(200, 200);
show();
// We are responsible for starting the bean.
bean.start();
public void itemStateChanged(ItemEvent evt) {
Beans .setDesignTime (designTimeCb. getStateQ) ;
((Component)bean).repai nt();
}
Beans
java.beans
public static void main(String[] args) {
// Initialize the environment in design-time mode.
Beans.setDes i gnTime(t rue);
try {
// Create the bean.
bean - (Bean)Beans.instantiate(Main.с 1 ass.getClassLoader(
new Main();
} catch (Exception e) {
e.printStackTraceO ;
System.err.print 1n(”Fai1ed to create bean.”);
System.exi t(l);
}
}
}
Bean.java
import java. appl et . ;
import java.awt.*;
import java.awt .event . ••;
import java.beans;
public class Bean extends Applet implements Runnable {
Image image;
Thread thread;
Point curLoc - new Point(0, 0);
int scale - 1;
// This method is automatically called by Beans.instantiateC).
public void initO {
image - getImage(getDocumentBaseO, "duke.gif”);
// Make sure the entire image is loaded so that we can safe'
// call getWidthO and getHeightO on it.
Medialracker tracker - new Medialracker(this);
try {
tracker.addlmage(image. 0);
tracker.wai thorAl1(0);
} catch (Lxception e) {
e.printStackT race();
}
// Listen for mouse pressed events.
addMouseListener(new MouseEventHandler());
}
public void startO {
// Start the animation thread.
(thread - new Thread(this)).start();
}
public void stopO {
// Stop the animation thread,
thread = null;
}
public void palnt(Graphics g) {
170
if (Beans.isDesignl imeQ) {
g.drawlmage(image, curLoc.x, curLoc.y, this);
} else {
g.drawlmage(image, curLoc.x, curLoc.y,
image.getWidth(nu11)/scale, image.getHeight(nul1)/scale, this);
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
// Ignore mouse events unless in design-time Tode.
if (Beans. i sDesignTimeO) {
curLoc = evt.getPointO;
repaint();
}
}
}
// Thread that constantly changes the scale value.
public void run() {
int inc = 1;
while (thread == Thread.currentThreadQ) {
try {
if (! Beans. isDesignTimeO) {
if (scale == 1) {
inc 1;
} else if (scale =- 5) {
inc = -1;
}
scale += inc;
repaintO ;
}
Thread.sleep(300);
} catch (Exception e) {
}
}
}
}
PURPOSE Casts the bean object into a superclass.
SYNTAX public static Object getlnstanceOf(Object bean, Class targetType)
description This method casts a bean into an object of type targetType. If the target- Type Class object is not a superclass of bean, then bean is returned.
parameters bean targetType A non-nul1 bean. A non-nul 1 Class object.
RETURNS This method currently returns bean. It will be implemented in a f uture release.
SEE ALSO i slnstanceOf().
example See PropertyDescriptor.getReadMethod().
Beans
instantiatet)
java.beans
instant iate()
bi rposl Creates a new instance of a bean.
syntax public static Object instantiate(Classloader cloader, String
beanName) throws lOException, ClassNotFoundException
description This method is used to load a bean from a serialized object or a class file. The
string beanName must consist of dot-separated names such as "candys-
tore. jelly. Bean". This method first looks for a serialized object with
beanName. It converts beanName into a resource pathname by rep lac mg the
dots with file separators and then appending the string ” .set". It then calls
deader. getResourceQ to see if it yields a serialized object.
If not, the bean is assumed to be a class file. The beanName is interpreted as a
package-qualified class name and the cloader class loader is used to help
locate the bean.
If cloader is nul 1, the default system class loader is used instead.
If the bean is a subclass of Applet, it is given some special initialization. First,
it is supplied with a default AppletStub and Appletcontext. This means
that getDocumentBaseO and getCodeBaseO returns valid values. If the
bean was loaded from a class file rather than from a serialized object, the
bean’s init() method will be called. However, it is the caller's responsibility
to call the bean's start () method. The start О method should be called
after the bean has been added to a showing AWT container.
Note that applets created with this method run in a different environment (han
applets running inside browsers. In particular, bean applets cannot call
Appl et .getParameterQ. Л bean applet must provide another way of setting
parameters. It is advisable to test your applet in both a bean editor and a
browser.
PARAMET I RS
beanName The non-nul 1 bean class name.
cloader A possibly null class loader.
rfti’rns A new instance of a bean loaded using cloader.
EXCEPTIONS
Cl assNotFoundExcept! on
If the bean class file could not be found.
lOException If an error occurred while trying to read the bean file or serialized object.
see als<) java.applet.Applet, java.io.lOException,
java.1ang«ClassNotFoundExcept!on.
example See the Vi si bi 15 ty class example.
172
isDesignTimeO
PURPOSE Retrieves the environment s design-time flag.
SYNTAX description public static boolean isDesignTimeO Д When the bean environment is in design-time, the beans in the environment
returns can be edited by a user. At present, when a bean editor changes the design-time Ц flag, it repaints (see Component. repai nt0) all (he beans. Hence, a bean c should check for changes in the environment's design-time mode in its Compo- nent , update 0 method. D true if lhe environment is in design-time; fal se otherwise. E
SEE ALSO setDesignTimeO.
EXAMPLE See lhe class example. ( ь
isGuiAvailableO
purpose Determines if the environment suppons a window system.
syntax public static boolean isGuiAvailableO
description When a bean is loaded and instantiated in a bean environment, the environ-
ment may or may not support a window system. If it does support a window
system, the bean can create and show AWT components such as buttons and
dialog boxes. An example of a bean environment that does not support a win-
dow system might be a server machine or a batch job,
returns true if the environment supports a window system.
SEE also setDesignTimeO . Visibility.
I
J
К
I
X
\
(
I
(
I
PURPOSE Determines if a bean is a subclass of another class.
SYNTAX public static boolean islnstanceOf(Object bean, Class targetType)
DESCRIPTION Essentially, this method returns true if bean is an instance of targetType. The instanceof operator cannot be used because the bean and targetType ' class object may have been loaded with different class loaders (instanceof would always return fal se in this case). If this method returns true, the bean can be cast to the target type by calling getInstanceofО.
Beans
setDesignTimeO
java.beans
PARAMETERS bean targetType A non-nul 1 bean. The class object of a type.
RETl’RNS true if the bean is a subclass of targetType.
SHE ALSO EXAM PI E getlnstanceOfО - See PropertyDescriptor .getReadMethodO*
setDesignTimeO
Pl RPOSE Modifies the environment's design-time flag.
SYNTAX public static void setDesignTimefboolean isDesignTime) throws Securi tyExcepti on
DESCRIPTION When the bean environment is in design-time, the beans in the environment can be edited by a user. To set the bean environment to be in design-time, isDesignTime should be true. To sei the bean environment to be not in design-time, isDesignTime should be false. At present, when a bean editor changes the design-time flag, it repaints (see Component. repai ntO) all the beans. Hence, a bean should check for changes in the environment’s design-time mode in its Component .updateO method.
PARAMETERS
i sDesignTime
true if the environment is in design-time.
EXCLPIIONS
Securi tyExcepti on
If the method call is disallowed by the security manager.
Si l ALSO i sDesignTimeO , java.awt.Component, java.lang.SecurityException, java.lang.SecurityManager.
EX A MP! E See the class example.
setGuiAvailableO
PVRPOSE Indicates whether the environment supports a window system.
S'! MAX public static void setGuiAvailable(boolean isGuiAvailable) throws SecurityException
174
description When a bean is loaded and instantiated in a bean environment, the environ-
ment may or may not support a window system. If it does support a window
system, the bean can create and show AWT components such as buttons and
dialog boxes. An example of a bean environment that does not support a win-
dow system might be a server machine or a batch job.
The isGui Avail able parameter should be true if the bean environment sup-
ports a window system and false otherwise.
PARAMETERS
isGuiAvaiTable
true if the environment supports a window system; false otherwise.
EXCEPTIONS
SecurityException
If the method call is disallowed by the security manager.
SEE also isGuiAvailableO .
Border La ye'j г
Syntax
public class BorderLayout implements LayoutManager2, Serializable
Description
I'he border layout manager has exactly fi\e locations at
which it places its components. Figure 35 shows a con-
tainer w ith a border layout manager and fiye buttons, one
each occupying each of the five locations. The locations
are north, south, east, yyest. and center, identified by the
constants NORTH. SOUTH. EAST. WEST and CENTER,
respectively (see Table 6). When a component is added
to a container with a border layout manager, one of these
five locations must be used..
1^BorderLayout Ex.. ЯИЕЗ
North j
West Center East
South |
I IGl R! 35: The Five Border
Layout Locations.
NORTH Place the component at the northern border of (he container and make it as wide as the container and as tall as the component's pre 1 erred height.
SOUTH Place (he component al the southern bordei ot the container and make it as wide as the container and as tall as the component's prclciied height.
WES1 Place the component at the western bordei of the container and make it as wide as the component's preferred width and as tall as the space between the bottom of the north and south components (it any ) minus twice (he ver- tical gap.
EAST Place the component at the eastern border of the conlainci and make it as w ide as the component’s preferred w idth and as tall as the space between the hot tom of the north and south components (if any ) minus twice (he vertical u;in
CENTER Place (he component as wide as (he space between the west and east compo nents (if any ) minus twice (he horizontal gap and as high as the space between (he north and south components (if any ) minus twice the vertical gap
TABLE 6: BorderLayout Locations.
Not all fixe locations must be tilled. It a location is not used, the space is distributed
among the other locations. Figure 36 shows a north and west component, with the center com-
ponent claiming all remaining space. An invisible component in a location is ignored during
the layout, so the location is treated as it it is not occupied. Also notice (hat the border layout
manager does not always fill up all available space.
For example, in Figure 37. although there is space
between the north and south components, the border lay-
out manager does not attempt to stretch the two compo-
nents to fill up this space. Finally. the border layout
manager places the components in a particular order.
First, the north and south components are placed. Next,
the west and east components are placed. Finally, the cen-
ter component takes up al) remaining space. Note that
opposite-facing components are placed simultaneously. In
^BorderLayout Ex... Д0ЕЗ
North
West
Center
other words, it is not the case that one component is
placed first and the other lakes up the remaining space.
FIGI RE 36: Buttons at Three
Locations.
Figure 38 shows a container that is shorter than the com-
bined widths of the west and east components. Notice that the two components overlap. You
cannot control which one will appear on top.
You must always identify the location of any
components added to a container by using a border
layout manager. You also should he careful to use
the correct location. The border layout manager
does not warn you if you use a location more than
once. If this happens, the components simply won't
be laid out correctly.
FIGI RE 37: Buttons at Two Locations.
Gaps
The border layout manager allows you to separate
the locations by gaps. The vertical gap specifies the
space between the bottom of the north component,
the top of the south component, and the components
in between. The horizontal gap specifies the space
between the west, center, and east components.
BorderLayout Example BBS
W e s t E a s t
FIGI RE 38: Overlapping Locations.
Note that if there are no components between the north and south components, the gap
between them is two times the vertical gap. This is also true of the west and east components.
This means that it you have a container with only two opposite-facing components and you
pack the container to its minimum si/e. the gap may be larger than you want. If your gap si/e
is even, you can simply set a gap that’s half the si/e. If your gap si/c is odd. you’ 11 have to sub-
class the border layout manager and implement vour own gap rules.
BorderLayout
|a\ a.awt
C
D
E
E
G
H
I
J
К
L
M
N
О
P
Q
R
S
T
I’
MEMBER SUMMARY
Constructor
BorderLayout()
Location Constants
CFNTFR
EAST
NORTH
SOUTH
WtSI
Layout Manager Methods
addt ayoutComponent()
getLayoutAli gnmentXQ
getl ayoutAlighmentYO
i rival idateLayout ()
1ayoutContai nerQ
maximumLayoutSi ze()
minimumLayoutSi ze()
preferredLayoutSi ze()
removeLayoutComponent()
Gap Methods
getHgapO
getVgapO
setHgapO
setVgapO
Debugging Method
toStri ng()
Constructs a BorderLayout instance.
Specifies the center location.
Specifics lhe cast location.
Specifics lhe north location.
Specifies the south location.
Specifies the west location.
Places a component al a location.
Retrieves this las out manager's л-alignment.
Retrieves this layout manager's у alignment.
Invalidates this layout manager's stale.
Lays out lhe container's components based on the settings of
this layout manager.
Calculates the maximum dimensions for laying out the compo
ncnls.
Calculates the minimum dimensions needed to lay out lhe com
portents.
C 'a leu I ales the preferred dimensions needed to lay out lhe com-
ponents.
Removes a component from a location.
Retrieves the horizontal gap between components.
Retrieves the vertical gap between components.
Sets the horizonlal gap between components.
Sets the vertical gap between components.
Generates a string representation of this layout manager's state
w
X
See Also
LayoutManager, LayoutManager?, java.io.Serializable.
178
ackii .ayoull oinponenu )
Example
Thi4* example demonstrates the t\pical xx u\ a border lax -
out manager is used (see Figure 39). I he center location
is assigned a component that can stretch with the frame
(in this ease, just a blank canxasi. The cast location is
assigned a scrollbar that controls the center component.
The south position contains a window that displays sta-
tus information. The north location contains buttons.
BorderLayout Ex... ДИЕЗ
Ready
Quit
import java.awt.' ;
HGl Rk 39: BorderLayout.
class Main {
public static void main(String[] args) {
Frame f = new Frame(“BorderLayout Example"):
f.setLayout(new BorderLayout());
f.add(new Button("Quit"), BorderLayout.NORTH);
f.add(new CanvasO, BorderLayout.CENTER) ;
f.add(new ScrollbarO, BorderLayout. EAST);
f.add(new Label("Ready"), BorderLayout.SOUTH);
f.setSize(200, 200);
f.pack();
f s hnv/ i ;
}
}
addLayoutComponent( I
purpose Places a component at a location. p
syxiax public void addLayoutComponent(Component comp, Object location) q
hn>RK\ш> public void addLayoutComponent(String location. Component comp)
R
descrip i io\ This method places comp at the location location, which can be one of
NORTH. SOUTH. WEST. EAST. CENTER, or nul 1. nul 1 ь equixalent to CENTER. S
The use of any other value for location results in an II 1 egal Argument- I
Exception. (.
PAR Wlf TLRS
comp The non-nul 1 component that has just been added to the container. Table 6
details the resizing rules for each location in the border layout.
1 ocati on The location al w hich to place the component. Il must be one of the border lay - \
oul locations or nul 1. nul 1 is equivalent to CENTER
LX( 1-p’l К )\s
Ill egal ArgumentExcept i on
II local ion is not one of the valid border layout locations.
BorderLayout
BorderLayouK)
java.awl
deprecaiion addLayoutComponent() now has a more generic form that can accept an
arbitrary Object as a location instead of a St ring. Replaces the usage of the
deprecated form:
addt ayoutComponent(“North", component);
with
addLayoutComponent(component, BorderLayout.NORTH);
MT Al so CENTER, EAST, LayoutManager?, NORTH, SOUTH, WEST.
examh I See the LayoutManager class example.
r.
BorderLayoutf)
Ci Pl RPOSE Constructs a new BorderLayout instance.
Fl SYMAX public Borderlayout()
1 DESCRIPTION public BorderLayout(int hgap. int vgap) this constructor creates a new BorderLayout manager instance with lhe gaps
.1 hgap and vgap. If the gaps are not specified, they both default to 0. The gaps
К can be changed using setHgapO and setVgapO-
L The association between a location and a component is maintained in the bol-
M der layout manager, so each container requires its own BorderLayout instance. That is, \ou cannot use the same BorderLayout instance in more
\ than one container. Also, a container can be set to use a border lax out only
() when the container has no components.
P PARAMETERS hgap A non-negative integer specifying the horizontal gap in pixels.
Q vgap A non-negative integer specifying the vertical gap in pixels.
R StЛ: ALSO setHgapO. setVgapO •
S T EXAMPLE See the class example.
1 CENTER V Pl RI’OSE w SV MAX X DESCRIPTION Y Z Constant specifying the center location. public static final String CENTER This constant specifies that lhe component is to be laid out as wide as the space between the west and east components (if any) minus twice the horizontal gap and as high as the space between the north and south components (if any) minus twice the vertical gap. Its value is ’"Center".
ixo
SEEALSO addLayoutComponentf), Container.add(), EAST, getHgapO, getVgapO, NORTH, SOUTH, WEST.
example See the class example.
EAST
PURPOSE Constant specifying the east location. c
SYNTAX public static final String EAST [
DESCRIPTION This constant specifies that the component is to be placed at the eastern border F
of the container, as wide as the component’s preferred width and as tall as the F
space between the bottom of the north and south components (if any) minus f
twice the vertical gap. Its value is “East”.
SEEALSO addLayoutComponentO , Container.addО, CENTER, getVgapO, NORTH, SOUTH, WEST. F 1
EXAMPLE See the class example. J
F
getLayoutAlignmentX() L
PURPOSE Retrieves this layout manager’s x-alignment. N к
SYNTAX public float getLayoutAlignmentX(Container cont) г
DESCRIPTION This method returns Component ,CENTER_ALIGNMENT. See LayoutManager2
for more information about alignments. F
PARAMETERS
cont The non-nul 1 container using this layout manager instance. F
RETURNS This layout manager’s x-alignment, which must be in the range 0.0f to 1.0f. 5
SEEALSO Component. getAl i gnmentXO, Container. getAl i gnmentXO , 1
getLayoutAlignmentYO r LayoutManager2.
EXAMPLE See the LayoutManager2 class example. I
X V
getLayout Alignment Y() >
PURPOSE Retrieves this layout manager’s v-alignment.
SYNTAX public float getLayoutAlignmentY(Container cont) 2
description This method returns Component-CENTER^ALIGNMENT. See LayoutManager2 for more information about alignments.
BorderLayout
gelHgapt)
java.awt
PARAMETERS
A
coni I’he non-nul 1 container using this layout manager instance.
reivrns This layout manager's у alignment, which must be in the range 0.0f to 1.0f.
sei- al so Component .getAl ignmentYO , Container.getAl ignmentYO ,
getLayoutAlignmentXO, LayoutManager?.
example See the LayoutManager2 class example.
C
D
F.
F
G
II
1
J
К
L
M
N
()
P
Q
R
S
T
u
V
w
X
Y
Z
getHgapQ __________ _____________________________
pi rpose Retrieves the horizontal gap between components,
syntax public int getHgapO
description The horizontal gap specifies the space between the west, center, and cast com-
ponents. Note that if there are no components between the west and cast com-
ponents, the gap between them is two times the horizontal gap. See the class
description for more details on the use of gaps in the layout. The horizontal
gap is initialized by the BorderLayout constructor and changed using setH-
gapO.
riterns A non-negativc integer specifying the horizontal gap in pixels.
see also getVgapO , setHgapO
exampl e This example creates a frame
(with the default border lay-
out) with vertical and horizon-
tal gaps initialized to 0, Hour
buttons labeled V+, V-. H+,
and H- control the vertical and
horizontal gaps of the border
layout. A status burton in the
center is used to display the
current vertical and horizontal
gaps in effect. See Figure 40.
ELGLRE 4ft: Border Layout’s Horizontal and
Vertical Gaps.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ActionListener {
Button status;
BorderLayout layout;
Main() {
super("BorderLayout Gaps Example’);
// The default layout for Frame is BorderLayout
182
layout = (BorderLayout)getl ayoutO ;
Button b;
add(b *= new Button(“V+"), Border!ayout.NORTH);
b.addActionListenerCthis);
add(b - new Button(“H+"), BorderLayout.WEST);
b.addActionlistenerCthis); Л
status = new Button(“Vgap=’'^-1 ayout.getVgapO *
Hgap^"+layout.getHgapO) ; и
addCstatus, BorderLayout.CENTER); C
add(b = new Button(“H-"), BorderLayout.EAST); D
b.addActionli stenerCthi s);
add(b *= new ButtonC“V-”), BorderLayout.SOUTH); E
b.addActionListenerCthis);
E
setSizeCIGO, 200);
showO; G
}
II
public void actionPerformedCActionEvent evt) {
String what * evt.getActionCommandC); I
if C“H+".equals(what)) { J
layout .setHgapCl ayout .getHgapO + 5);
} else if (“H-”. equalsCwhat)) { К
layout.setHgap(Math.maxCO, layout.getHgapO-5));
} else if C“V+”.equal sCwhat)) { L
layout.setVgapClayout.getVgapO+5);
} else if (“V-”.equals(what)) { M
1ayout.setVgap(Math.max(0, 1ayout.getVgapО -S));
} N
// Update status button
status. setLabel C‘,Vgap=”+layout.getVgapO * °
”, Hgap=”^layout. getHgapO) ;
invalidateO; E
validateO ;
} Q
public static void main(String[J args) { R
new MainО;
} s
}
T
и
getVgapO v
purpose Retrieves the vertical gap between components. .
syntax public int getVgapO
description The vertical gap specifies the space between the north, center, and south com-
ponents. Note that if there are no components between the north and south z
components, the gap between them is two times the vertical gap. See the class
description for more details on the use of the gaps in the layout. The vertical
BorderLayout
invalidate!.ayout()
java.awt
gap is initialized by the BorderLayout constructor and changed using setV- gapO.
RFTIRNS A non-negative integer specifying lhe vertical gap in pixels.
SEE ALSO getligapO , setVgapO
EXAMPLE See getHgapQ.
invalidateLayout()
Pl'RP( )S1- Invalidates this layout manager's state.
SYNTAX public void irivalidateLayout(Container cont)
DI SC RIP! ION This method is called by the layout manager's container to discard any cached information associated with this layout for the container cont. For Border- Layout. this method by default does not do anything.
PARAMETERS cont The non-nul 1 container using this layout instance.
SEE ALSO 1ayoutManager2.
EXAMPLE See the LayoutManagerZ class example.
layoutContainer()
PURPOSE Lays out the container's components based on the settings of the layout man- ager.
SYNTAX public void 1ayoutContainer(Container container)
DESCRIPTION This method is called by container when the layout is invalidated and needs to be redone. It uses a component's preferred size when determining the dimensions of its location. Lhe locations are also dependent on the current size of the container.
PARAMETERS container The non-nul 1 container using this layout instance.
EXAMPLE See I ayoutManager.
maximumLayoutSizef)
PURPOSE Calculates the maximum dimensions for laying out the components.
184
SYNTAX public Dimension maximumLayoutSize(Container container)
DESCRIPTION Fora border (ayout. the default maximum layout is the largest dimension avail able (Integer.MAX_VALUE by Integer. MAX „VALUE).
PARAMETERS cont The non-nul 1 container using this layout instance.
returns A new non-nul 1 Dimension instance containing the maximum size of the border layout.
SEE ALSO Component.getMaximumSizeO, Container, minimumLayoutSize(), LayoutManager2, preferredLayoutSizeO.
EXAMPLE See the LayoutManage r2 class example.
minimumLayoutSizet)
PURPOSE Calculates the minimum dimensions needed to lay out the components.
SYNTAX public Dimension minimumtayoutSize(Container container)
DESCRIPTION The minimum dimension is calculated by determining each visible compo- nent’s minimum size and then laying out the components using just enough space so that they do not overlap. The minimum size also adds enough space for the gaps.
PARAMETERS container The non-nul 1 container using this layout instance.
RETURNS A new non-nul 1 Dimension instance containing the minimum size of the bor- der layout.
SEE ALSO Component .getMinimumSize() , maximumt.ayoutSi ze() , preferredLayoutSizeO.
EXAMPLE See LayoutManager.
NORTH
PURPOSE Constant specifying the north location.
SYNTAX public static final String NORTH
description This constant specifies that the component is to be placed at the northern border of the container, as wide a.s the container, and as tall as the component's preferred height twice the vertical gap. Its value is “North".
BorderLayout
preferredLayoutSizet I
java.awt
SEE A I.SO addLayoutComponent 0 . Container.add(), CENTER, EAST, getHgapQ. getVgapQ , SOUTH, WEST.
E.XA.MPl I See (he class example.
preferredLayoutSize()
C PERPOSE Calculates the preferred dimensions needed to lav out the components.
D SYNTAX public Dimension preferredLayoutSizefContainer container)
E DESCRIPTION The preferred dimension is calculated by determining each visible compo-
E nent's preferred size and then laying out the components using jusi enough
space so that they don't overlap. The preferred si/e also adds enough space for
(j the gaps.
H PARAMETERS
1 contai ner The non-nul 1 container using this layout instance.
J RFTt’RNS A new non-nul 1 Dimension object containing the preferred size of the border
К layout.
SFF ALSO Component.get PreferredSizeO » maximumLayoutSize(),
L mi nimumLayoutSizeО.
M EXAMPLE See LayoutManager.
N
removeLavoutComponent()
i> --------------- -----------------------
Q Pl RPOSE Removes a component from a location.
R SVNT AX public void removeLayoutComponentfComponent comp)
s DESCRIPTION This method removes the component comp from the border lav out manager's
list of components. The border layout manager will no longer place comp. If
T comp does not have a name, the method call is ignored. This method is nor
и mally called by the container in response to the removal of anv component
V from the container.
PAR A MF IFRS
w comp T he non-nul 1 component about to be removed from the container.
X Y EXAMPLE See LayoutManager.
186
setHgapO___
PURPOSE Sets the horizontal gap between components.
SYNTAX public void setHgap(int hgap)
DESCRIPTION This method sets the horizontal gap of this layout to be hgap. See the class A
description for details on the use of gaps in border layout. и
parameters c
hgap A non-negative integer specifying the horizontal gap in pixels. D
SEL ALSO getHgapO, setVgapO - E
exampit: See getHgapO. V
G
set V gap () H
PURPOSE Sets the vertical gap between components. 1
SYNTAX public void setVgapfint vgap) J
DESCRIPTION This method sets the vertical gap of this layout to be vgap. See the class К
description for details on the use of gaps in border layout. L
PARAMETERS M
vgap Л non-negative integer specifying the vertical gap in pixels. N
SEE ALSO getVgapO , setHgapO . О
EXAMPLE See getHgapO. P
Q
SOUTH R
PURPOSE Constant specifying the south location. S
SYNTAX public static final String SOUTH T
description This constant specifies that the component is to be placed at the southern border L
of the container, as wide as the container and as tall as the component's preferred V
height twice the vertical gap. Its value is ’‘South". w
SEE ALSO addLayoutComponent О , Contai ner. add(), CFNTER, FAST, getHgapO, * v
getVgapO. NORTH, WEST.
example See the class example. Y
z
ja\ a.awt
BorderLayout
toStringf)
toString()
— _ — .. .— „ — - — _
Pl'RPOSL Generates a string representation of this layout manager's state.
SYNIAX public String toStringO
DESCRIPTION The string representation of a layout manager contains the layout manager’s class name, the size of the two gaps» and which locations are occupied. This method returns this string representation. This method is typically used for debugging.
RETURNS A non-nul 1 string representing the layout manager's state.
OVERRIDES java.lang.Object.toStringО .
EXAMPLE See java. 1 ang.Object.toStri ng0.
WEST
— —- - -
PURPOSE Constant specifying the west location.
SYNTAX public static final String WFSI
DESCRIPTION This constant specifies that the component is to be placed at the western border of the container, as wide as the component's preferred width and as tall as the space between the bottom of the north and south components (it any) minus twice the vertical gap. Its value is “West".
SEE ALSO addLayoutComponentO , Container.add(), CENTER» FAST, getHgapO, getVgapO, NORTH, SOUTH.
EXAMPLE See the class example.
188
Button
A
и
с
D
E
F
G
H
I
J
Syntax
public class Button extends Component
Description
A button is a component that has a label and that
fires an event when pressed. A button is typically
used when a command needs to be invoked. For
example, a stopwatch application is shown in Figure
41 with three buttons to operate the stopwatch.
Events
An action event is fired when the mouse is pressed
and released inside the button. See the Action-
Event class for details. The action event contains an
FIGURE 41: A Simple Stopwatch with
Three Buttons.
action command that indicates the command issued by this button. By default, the action com-
mand is the label of the button unless it is set using setActionCommandO.
In addition to the action event, a button fires all the events fired by the Component class.
See the Component class for details. See the AWTEvent class for general information on events
and how to filter or handle events.
See Also
AWTEvent, java.awt.event.ActionEvent, java.awt.event.Acti onL i steneг.
К
1.
M
N
О
P
Q
R
S
T
и
V
w
X
Y
z
Button
java.awt
G
II
J
J
К
I.
M
N
О
P
Q
R
S
T
L
V
W
X
Y
Z
MEMBER SUMMARY
Constructor Button О Constructs a new Button instance.
Label Methods get!abel() setLabelО Retrieves this button's label. Sets this button’s label. |
Event Methods addActionLi stenerО getActionCommandO 1 processActionFventQ 1 processEventО removeActionl i stener() 1 setAct ionCommandO Adds a listener to receive action events from this button. : Retrieves the command name of action events fired by this but- | ton. Processes an action event enabled for this button. । Processes an event enabled for this button. Removes a listener from receiving action events from this but ton. Sets the command names of the action events fired by this but | ton.
Peer Method | addNotifyO Creates this button’s peer.
Debugging Method | paramString() Generates a string representing this button's state.
Example
For a simple example using a button, see the Button О constructor. This is a more elaborate
example of an application that uses buttons. The application is a (not very accurate) stopwatch
with three buttons: Reset, Start, and Stop. Figure 41 shows a screen shot of the example.
Depending on the mode of the stopwatch, certain buttons will be enabled or disabled to indi
eate which operations are currently appropriate. For example, if the stopwatch is stopped, the
Stop button will be disabled.
A thread is created whenever the stopwatch is ticking and killed when no longer needed.
import java.awt.1-;
import java.awt.event.*;
public class Main extends Frame implements Runnable {
Label timeDisp = new Label(“ 0:0 Label.CENTER);
Thread timerThread;
int time = 0; // The time in seconds.
Button btReset = new Button("Reset”);
Button btStart = new ButtonC‘§tart");
190
Button btStop = new Button("Stop”);
Main О {
super(“Button Example”);
// Use a grid layout manager for the 3 buttons.
Panel p = new Panel(new GridLayout(l, 0));
btReset.setEnabled(false);
btStop.setEnabled(false);
// Set listeners for each button
btReset.addActionListener(new ResetLi stener());
btStop.addActionListener(new StopListenerO);
btStart.addActionLi stener(new StartLi stener());
p.add(btReset);
p.add(btStart);
p.add(btStop);
add(p, BorderLayout.SOU1H);
// Make the time display very large.
timeDisp.setFont(new Font(“Courier”, Font.BOID, 60));
add(timeDisp, BorderLayout.CENTER);
pack();
show();
}
// Returns only when the timerThread has terminated.
void stop() {
Thread t = timerThread;
if (t != null) {
timerThread = null;
try { t.joinO; } catch (Exception e) {}
}
}
public void run() {
while (timerThread ~ Ihread.currentThreadO) {
timeDisp.setText(““ 4 time/10 4- ♦ time%10 + "0
time++;
try { Thread.sleep(100); } catch (Exception e) {};
}
}
// Inner class definitions for listeners
class ResetListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Main.this.stopO;
timeDisp.setText(“0:0”);
time = 0;
btReset.setEnabled(false);
btStart.setFnabled(true);
btStop.setEnabled(false);
btStart.setLabel("Start”);
}
Button
java.awt
addActionListenerf)
C
D
E:
F
(i
El
I
J
К
I.
M
N
О
P
Q
R
S
T
ll
class StopListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Main.this.stopO;
btReset.setEnabled(true);
btStart.setEnabled(true);
btStop.setEnabled(false);
btStart.setLabel(“Conti nue”);
}
}
class StartListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
// Create and start the timer thread.
timerThread = new Thread(Main.this);
timerThread.start();
btReset.setEnabled(false);
btStart.setEnabled(false);
btStop.setEnabled(true);
btStart.setLabel(“Continue");
}
static public void main(String[] args) {
new Main();
}
}
addActionListenerO
purpose Adds a listener to receive action events fired by this button.
syniax public synchronized void addActionListener(ActionListener
listener)
description An action event is fired when the mouse is pressed and released inside this but-
ton. See ActionEvent for more details. After calling this method, the action
listener listener will receive action events fired by this button. If listener
is nul 1. this method does not do anything.
PARAMETERS
1 i stener The possibly nul 1 action listener to add.
see also java.awt.event.ActionEvent, java.awt.event.ActionListener,
removeActi onLi stener().
example See the class example, Button(), and setLabel ().
192
addNotifyt)
. • — _ . _ .— —
PURPOSE Creates this button's peer.
SYNTAX public void addNotifyO
DF-SCRIHION This method creates the peer if it does not yet exist. The peer is created by a call to the Tool к i t .createButtonQ method. The addNotifyO method should never be called directly. It is normally called by the parent.
OVERRIDES Component.addNoti fу0.
SEK ALSO Component, Toolkit.
EXAMPLE See Component.setVi si ble().
Button()
PURPOSE Constructs a new Button instance.
SYNTAX public ButtonO public Button(String label)
DESCRIPTION These constructors create a new Button instance with the label label. 11 label is not specified, it defaults to
PARAMETERS label The non-nul 1 string specifying the button's label.
EXAMPLE This is the simplest example of a complete СЖМЯМ""— program that uses a button. A button labeled 1а1МН1И1Д|Ы ‘'Button" is created and added to a frame. The Button | frame s action event handler prints *kButton pressed" whenever the button is pressed. See figure 42: Simple Button. Figure 42.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends Frarre implements Actionl istener {
Button b = new Button(“Button”);
MainQ {
super(“Button Example"):
add(b, Border!ayout.CENTER);
b.addActionLi stener(this);
pack();
show();
}
public void actionPerformed(ActionEvent evt) {
Button
get ActionConunandt)
java.awt
System.out.print 1n("Button pressed");
}
static public void main(StringLJ args) {
new Mai n() ;
}
A }
C
get ActionCommandO
fl b tn rposl SV ST AX Retrieves the command name of action events fired by this button, public String getArtionCommand()
G 1 )F SCR If'TION An action event is fired when lhe mouse is pressed and released inside this but-
I J ton. That action even! contains an uriion command indicating the command
11 issued by this button. By default, lhe action command is the label of the button.
1 The command action can be modified by using setActionCommand().
J RLTTRNS The command name of action events fired by this button. The button's label is
к returned if no command name was set.
L Sl.F. ALSO getLabel(), setActionCommandO.
EXAMPU This example creates a button and a text ।
M field. Pressing Return in the text field
\ causes the button's action command to be 1
() set to the contents of lhe text field. Notice Hello
that this does not allcct the button s label.
P Pressing the button will display the action H<;1 45: < hanging a Button s
Q command associated with lhe button. See Action Command.
R Figure 43.
S import java.awt.
import java.awt.event.Acti onLi stener;
T import java.awt.event.Actiontvent;
U class Main extends Frame implements ActionListener {
Button bt - new ButtonC'Button");
V TextField tf - new TextField(40);
W Main О {
super("getActionCommand Example”);
X add(bt5 BorderLayout.NORTH);
add(tf, Border! ayout .SOUTH);
Y
tf.setText(bt.getAct ion€ommand());
Z
// Set listener for text field and button
tf.addActionListener(this);
bt. addActi onListener(thi s) *,
194
раск();
show();
}
public void actionPerfonred(ActionEvent evt) {
Object src = evt .getSourceQ ;
if (src instanceof TextField) {
bt. set Actioncommand (tf. getTextO);
} else {
Sy stem, out .pri ntl n (evt .getActionCommandO) ;
}
1
static public void rain(String[? args) {
new Mai n();
}
)
getLabeU)
PURPOSE Retrieves this button's label.
SYNTAX public String getlabelO
RETURNS A non null string containing this button s label.
SEE ALSO setLabel().
EXAMPLE See setLabel ().
paramStringf)
PURPOSE Generates a string representing this button's state.
SYNTAX protected String paramString()
DESCRIH к )N The returned string includes this button's label. A subclass of this class should override this method and return a concatenation of its state with the results of super.paramString(). This method is called by the toStringO method and is typically used for debugging.
RETURNS A non-nul 1 string representing the button's state.
OVERRIDES Component.paramStri ng().
SEE A I.SO java.lang.Object.toStri ng().
example See Component.paramString().
Button
java.awt
processActionEvenK)
process Action Event ()
purpose Processes an action event enabled for this button.
s'iViAX protected void processActionEvent(ActionEvent evt)
description /\n action ex ent is fired when the mouse is pressed and released inside this but-
ton. See ActionEvent for more details. This method processes action events
for this button hy calling any registered ActionListener. This method is
invoked only if action events have been enabled for this button. This can hap
pen either when an action listener is added to this component or when action
events are explicitly enabled via the use of Component. enableEventsQ.
Typically, a program controls how action ex cuts for a button are processed. It
does this by adding or removing action listeners. It oxerrides procesS’-
Ас ti on Event () only if it needs to do extra processing in addition to the pro-
cessing performed by the registered listeners.
When a subclass does override processActionEvent(). it should call
super.processActionEvent() to perform the processing intended by its
base class (such as dispatching the listeners).
PAR AMI. ТЕ RS
evt The event to be processed.
see also java.awt.event.ActionEvent, java.awt.event.Actionl istener,
processEventO.
example See Component. di spatchEventO- The class MainButton overrides pro-
cessActionEventO to handle a new subclass of ActionEvent (SetFont-
Event).
processEventO
PURPOSE Processes an event enabled for this button.
SYNTAX protected void processEvent(AWTEvent evt)
DESCRIPTION This method extends Component. processEvent() by adding support for ActionEvent. This method cun be overridden to handle new types of events for this button. The subclass that overrides this should always invoke super.processEventO to ensure proper processing is performed (such as dispatching listeners).
PARAMEIERS evt The ex ent to be processed.
OVERRIDES Component. processEventO .
196
SEEALSO AWTEvent, processActiontvent().
example See the Component class example.
remove ActionListener() '
------------------------- _
purpose Removes a listener from receiving action events from this button. "
syntax public synchronized void removeActionLIstener(ActionListener
listener)
description An action event is fired when the mouse is pressed and released inside this but- *
ton. See ActionEvent for more details. After calling this method, the action f
listener listener will no longer receive action events from this button. If
1 i stener is nul 1, this method does not do anything.
f
parameters
listener The possibly nul 1 action listener to remove. I
SEE also addActionLi stenerQ, java.awt.event.ActionEvent, J
java.awt.event.Actionl istener.
К
example See Menuitem.di sableEventsQ.
L
N
set ActionCom mand()
purpose Sets the command name of action events fired by this button. (
SYNTAX public void setActionCommand(String command) F
description An action event is fired when the mouse is pressed and released inside this but- C
ton. That action event contains an action command indicating the command p
issued by this button. By default, the action command is the label of the button.
This method sets the action command of this button to be command. If
command is null, the action command of this button becomes the label of this 7
button. In any case, this method does not affect the label of this button.
parameters v
command The command name of the action events fired by this button. It can be null.
seealso getActionCommandQ, getlabelQ, setLabel ().
X
example See getActionCommandQ.
V
7
Button
set Labe 1()
java.awl
setLabeK)
PI’RPOSE
Sets this button's label.
C
D
E
F
<i
H
I
J
К
L
M
N
<)
P
syntax public void synchronized setLabel(String label)
description This method sets this button’s label to be label. If the action command of this
button has not been explicitly set (via setActionCommand()) or if the action
command has been set to null, the action command of this button becomes
label.
As a result of the label’s being set. the minimum and preferred sizes of the but
ton may change, so resizing the button may be necessary. The example shows
how to cause the button’s parent to resize the button.
PARAMETERS
label
SLl. a I.so
EXAMPLE
The non-nul 1 string specifying the button's new label.
get Act ionCommandO , get Label () .
This example creates a button and a text
field. Pressing Return in the text field
causes the button label to be set to the
contents of the text Held. Changing the
label does not automatically resize the
button in the layout. This needs to be
done explicitly. To do this, the button
must first be invalidated and then its
setLabel Example FJ:
KIGl RE 44: Changing a Button's
Label.
parent validated (this will resize the invalidated button). See Figure 43.
Q
R
S
T
u
V
w
X
Y
Z
A blank canvas is inserted in the center location of the border layout to force
the button to be as small as possible.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class Main extends Frame implements ActionListener {
Button bt = new Button(“Button”);
TextField tf - new TextField(40);
Main() {
super(“setLabel Example”);
add(new CanvasO, BorderLayout. CENTER) ;
add(bt, BorderLayout.WEST);
add(tf, BorderLayout.SOUTH);
tf.setText(bt.getLabel()); // Initialize with current label
tf.addActionListener(this); // Set listener for updating label
pack();
show();
}
public void actionPerformed(ActionEvent evt) {
198
setLabel()
bt.setLabel(tf.getText());
// Invalidate this button because of
bt.i rival idate();
// Validate parent to resize button
bt.getParent О.validate() ;
static public void main(String[] args) {
new Main О;
}
size change
A
I
(
c
к
i
G
H
I
J
К
I.
M
N
О
p
Q
R
s
T
и
V
w
X
Y
Z
java.awt.peer
ButtonPeer
Syntax
public interface ButtonPeer extends ComponentPeer
N
О
P
Q
R
S
T
U
V
Description
The button component (see the Button class) in the AWT uses (he platform's native imple-
mentation of a button. To make the AWT button component behave the same on all platforms,
the button is assigned a peer whose task is to translate the behavior of the platform’s nati\ e but-
ton to the behavior of the AWT button.
AWT programmers normally do not directly use peer classes and interfaces. Instead they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
j ava. awt counterparts.
See Component and Toolkit for additional information about component peers.
w
X
Y
Z
MEMBER SUMMARY
Peer Method
setLabel () Sets the button’s label.
200
See Also
j ava.awt.Button, j ava.awt.Component, j ava.awt.Tool kit.
setLabelO a
PURPOSE Sets the button's label. Ml
syntax c void setLabel(String label)
parameters label D The non-nul 1 string specifying the button peer's new label. E
SEiE ALSO java.awt.Button.setLabel(). b
G
H
1
J
К
L
M
N
О
P
Q
R
S
7'
i:
v
v
>
java.awt
Canvas
j Syntax
public class Canvas extends Component
M
n Description
O A canvas component is a primitive component meant to he either subclassed into custom com-
ponents or used for painting graphics. A canvas has no border or other bars.
q Canvases and Lightweight Components
With the introduction of lightweight components (see Component), there is really no need for
the canvas component. In fact, since a canvas has a native peer and a light weight component
s does not. it is much more efficient to use a lightweight component. If you are presently using a
T canvas, you should consider changing it to a lightweight component.
In theory, changing your class from a canvas to a lightweight component simply involves
L changing the extends from Canvas to Component. However, there are a few problems with
V Java LI.2 that forces you to make a few more modifications before your class will work
exactly the same. See the Component class description on lightweights for details.
X Events
Y A canvas tires all of the events fired by the Component class. See the Component class for
details. See the AWTEvent class for general information on events and how to filter or handle
7 them.
202
MEMBER SUMMARY
Peer .Method
addNotifyO Creates this ean\as\ peer.
Paint Override
paintO Paints this canvas.
Example
This example demonstrates how to build a custom button.
The button displays a blinking colored circle rather than a
text string. A thread is created to blink the button. The
custom button also overrides the enabled and disabled
methods in order to paint different images depending on
the state of this property. The custom button also fires an
action event when clicked.
Thi s example creates three colored buttons to control
the color of the main canvas. See Figure 45. After a color
is chosen, the corresponding button becomes disabled.
Canvas Example №IE3
ЕИЛ RE 45: Custom Button I sin$>
Canvas.
import java.awt.'';
import java. awt. event . ;
class Main extends Frame implements ActionListener {
Stringf] colorNames = {“red”, “green”, “blue”};
Color[] colorValues = {Color.red. Color.green, Color.blue};
MainButton[] buttons = new MainButton[colorNames.1ength];
Canvas cv = new CanvasO;
Main() {
super(“Canvas Example”);
Panel p = new Panelfnew CridLayout(1, 0));
for (int i=0: i<colorNames.1ength; i-+) {
p.add(buttons[i] = new MainButton(colorNames[i]. colorValues[i])):
buttons[i j.addActi onLi stener(thi sj;
}
add(p, BorderLayout.SOUTH);
cv.setSize(150, 150);
add(cv. BorderLayout.CENTER);
pack(j;
showf) ;
}
/7 when a MainButton is clicked, update color of main canvas
public void actionPerformed(ActionEvent evt; {
for (int i-0 ; i<colorNames.1ength; nj {
if (colorNames[ij.equals(evt.getActionCommandf;;; {
bu t tons [i ] .setEnaoled(false j;
cv.setBackground(colorValues[i]j;
Canvas
java.awt
cv.repaint();
} else {
buttons[i].setEnabled(true);
}
}
}
static public void main(String[] args) {
new MainQ;
}
}
class MainButton extends Canvas implements Runnable {
boolean on;
boolean engaged;
String label;
Thread timerThread;
ActionListener actionListener;
MainButton(String label, Color color) {
thi s.label = label;
(timerThread new Thread(thi s)) . startO ;
setSize(40T 40);
setForeground(color);
setBackground(Color.gray);
addMouseLi stener(new MouseListener());
}
public void setEnabled(boolean on) {
super.setEnabled(on);
if (on) {
if (timerThread -= null) {
(timerThread = new Thread(this)).startO ;
}
} else {
timerThread = null;
}
repaintO;
}
public void addActionListener(ActionListener 1) {
actionListener - AWTEventMulticaster.add(actionl isi
}
public void paint(Graphics g) {
update(g);
public void update(Graphics g) {
FontMetrics fm g.getFontMetrics();
int w « getSize().width;
int h = getSize().height;
int oval Size = Math.min(w/3, h/3);
g.clearRect(0, 0, w, h);
if (isEnabledO) {
if (engaged j| on) {
g.fillOval((w-ovalSize)/2, (h-ovalSize)/2,
oval Size, oval Size);
204
} else {
g.drawOval((w-ovalSize)/2, (h-ovalSize)/2,
ovalSize, ovalSize);
}
} else {
g.setColor(Color,white):
g.drawOval((w-oval Size)/2 , (h-ovalSize)/2, ovalSize, ovalSize); /
}
g.setColor(getBackground()); I
g.draw3DRect(0, 0, w-1, h-1, ’engaged); м
g.draw3DRect(l, 1, w-2, h-2, ’engaged); И
} ™
I
// Mouse event listener }
class MouseListener extends MouseAdapter {
public void mousePressed(MouseEvent evt) { I
engaged = true;
repai ntO; (
}
1
public void mouseReleased(MouseEvent evt) {
engaged = false;
repai nt();
if (actionlistener != null) {
// Create action event for listener to process 1
ActionEvent action
new ActionFvent(this, ActionEvent.ACTION_PERFORMED, label);
actionListener.actionPerformed(action);
} ?
}
1
public void run() { i
while (timerThread == Thread.currentThreadO) {
on = ’on;
repaint();
try { Thread.sleep(1000); } catch (Exception e) {}; '
}
}
}
addNotify()
PURPOSE Creates this canvas’s peer.
SYNTAX public void addNotify()
description This method creates the peer if it does not yet exist. TTie peer is created by call- ing the Tool ki t .createCanvas О method. This method should never be called directly. It is normally called by the parent.
OVERRIDES Component.addNotifу().
SEE ALSO Component, Toolkit.
Canvas
java.au I
paintl)
paintf)
Pl RE’OSF Paints lhe canvas.
SYNTAX public void paint(Graphics graphics)
DbSCRIHION This method is called when part of the canvas that was previously occluded by some other window is now exposed. You can determine the bounds of the exposed area by using the getClipBoundsO method on the graphics context. This method, by default, simply clears the exposed area with the canvas’s background color. Override this method to implement your drawing routines. Note that the system does not automatically clear the exposed area. Note: Canvases have been replaced by lightweight components. See the class description for details.
PARAMEIERS
graphi cs The non-nul1 graphics context used to paint on the component.
ove rrides Component. pal nt О.
example This is the simplest example of a program that
uses a canvas to draw a graphic. Л subclass of
canvas is defined and its pai nt О method over-
ridden. The pai nt О method simply draws an
oval. See Figure 46.
FIGURE 46: Painting on a
Canvas.
import java.awt.*;
class Main {
static public void mainfString[] args) {
Frame f - new Frame(“paint Example”);
f.add(new Mai nCanvasQ , BorderLayout .CENTER) ;
f.setSize(200, 100);
f. showO ;
}
}
MainCanvas extends Canvas {
class
public void paint(Graphics g) {
g.drawOval(0, 0, getSize(),width-1,
getSizeQ .height -1);
}
206
CanvasPeer
Syntax
public interface CanvasPeer extends Componentpeer
Description
The canvas component (see the Canvas class) in the AWT uses the platform's native imple-
mentation of a canvas. So that the AWT canvas component behaves the same on all platforms,
the canvas is assigned a peer, whose task is to translate the behavior of the platform's native
canvas to the behavior of the AWT canvas.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java. awt counterparts.
See Component and Tool kit for additional information about component peers.
See Also
java.awt.Canvas, java.awt.Component, java.awt.Toolkit.
java.awt
CardLayout
Syntax
public class CardLayout implements LayoutManager2, Serializable
i Description
G The card layout manager shows only one component in the container at a time: all other com-
ponents in the container are hidden. The visible component, called the current component. is
H resized to take up the entire visible area of the container (that is, the container’s bounds less the
I space taken up by the container insets and card layout manager gaps).
Several methods allow you to change the current component. One of them is the show О
method, which allows you to make any component current via its name. Unless you need to
К use the show() method, it is not necessary to name the components.
। The card layout manager uses the visibility state of the components to keep track of the
current component, so you should not directly change the visibility state of the components
M while they are under the control of a card layout manager.
N
<) Gaps
I he card layout s gaps are really insets. The vertical gap specifies the space between the top
P and bottom edges of the container and the current component. The horizontal gap specifies the
space between the left and right edges of the container and the current component.
R
T
u MEMBER SUMMARY
V Constructor
w ) | Cardl ayoutO Constructs a new CardLayout instance. '
x | Show Methods
firstO Makes the contai ner *s first component current.
Y 1 last() Makes the container’s last component current. j
z next() Makes the next component current.
1 previous О Makes the pre\ ions component current. I
show() Makes a named component current.
I______________________________
208
MEMBER SUMMARY
— "
Layout Manager Methods addLayoutComponent() get Layout Al i gnmentXO get Layout Al ighmentYQ invalidateLayoutO layoutContainerO Associates a name w i th a component. 1 Retricxes this layout manager’s .\-alignment. Retrieves this layout manager's \-alignment Invalidates this lay out manager’s state. Lays out the container’s components based on the sellings of this lay out manager.
maximumLayoutSi ze() Calculates the maximum dimensions for lay ing out the compo- nents.
mi nimumLayoutSi ze() Calculates the minimum dimensions needed to lay out the com- ponents. ।
preferredLayoutSi ze() Calculates the preferred dimensions needed to lay out the com- ponents.
removeLayoutComponent О Removes a component from this layout manager.
Gap Methods getHgapO getVgapO setHgapO setVgapO Retrieves this layout manager’s horizontal gap. Retrieves this layout manager’s vertical gap. Sets this layout manager’s horizontal gap. Sets this layout manager’s vertical gap.
Debugging Method toStri ng() Generates the string representation of this lay out manager’s state.
See Also
java.i о.Seri ali zable, LayoutManager,
Example
This example creates a panel with a card lay-
out manager (sec Figure 47). A number of
labels are added to the panel, each labeled
with its position in the container. A row of
buttons at the bottom controls the current
component in the card lax out.
LayoutManager2.
I KU Rk 47: Button-controlled CardLayout.
CardLayout
ja\ a.awi
import java.awt.*;
import java.awt.event.ActionL istener;
import java.awt.event.ActionEvent;
class Main extends Frame implements ActionListener {
CardLayout cardLayout = new CardLayout();
Panel cardCont - new Panel(cardLayout);
Main() {
super(‘‘Cardl ayout Example”);
cardCont.add(new Label("First". Label .CEM FR), “First");
cardCont.add(new Label("Second”. Label.CENTER), "Second")
cardCont.add(new Label("Third", Label.CENTER), "Third");
cardCont.add(new Iabel(“Show”, Label.CENTER), "Show”);
cardCont.add(new Label("1ast", Label.CLKTFR), "Last");
add(cardCont, BorderLayout.CENTE R);
// Create control buttons
Panel p - new Panel(new GridLayout(1, 0)):
Button button;
p.add(button - new Button(“First”));
button.addActi onli stener(thi s);
p.add(button -- new Button("Next”));
button.addAct ionLi stenerfthi s);
p.add(button - new Button("Prev”));
button.addActionlistener(this);
p.add(button - new Button("Last"));
button,addActionLi stener(thi s);
p.add(button - new Button("Show”));
button,addAct i onLi stener(thi s);
// Add row of buttons to bottom
add(p, BorderLayout.SOUTH);
pack();
show();
}
public void actionPerformed(ActionLvent evt) {
String cmd =- evt .getActionCommandO ;
if ("First”.equals(cmd)) {
cardLayout.fi rst(cardCont);
} else if ("Prev”.equals(cmd)) {
cardLayout.previous(cardCont) ;
} else if ("Next".equals(cmd)) {
cardLayout.next(cardCont);
} else if ("Last’’.equals(cmd)) {
cardLayout.1ast(cardCont);
} else if ("Show”.equals(cmd)) {
cardLayout.show(cardCont, cmd);
}
}
public static void main(String arqs[j) {
new Mai n();
}
}
210
addLayoutComponent!)
purpose Associates a name with a component.
syntax public void addLayoutComponent(Component comp, Object compname)
nAw-ctrjjj public void addlayoutComponent(String compname, Component comp)
description This method associates the name compname with the component comp. If
another component in the same layout already has the same name, compname
becomes associated with comp and the old association is lost. The component
that was previously associated with comp name can no longer be addressed by a
name, but it can still be displayed using the firstf), last(). next(). and
previous О methods.
PARAMETERS
comp The non-nul 1 named component that has just been added to the container.
compname The non-nul 1 string name of the component to be added.
EXCEPTIONS
Illegal ArgumentException
If compname is not an instance of String.
deprecation addl ayoutComponent () now has a more generic form that can accept an
arbitrary Object as a location instead of a String. Replace the usage of the
deprecated form
addLayoutComponent("top”, component);
with
addlayoutComponent(component, “top”);
example See LayoutManager.
CardLayout()
purpose: Constructs a new CardLayout instance.
syntax public Cardlayout()
public Card!ayout(int hgap, int vgap)
desc ript ion This constructor creates a new card layout manager instance with the gaps
hgap and vgap. If the gaps are not specified, they both default to 0.
The first component added to the container becomes the default current com-
ponent. The component names are maintained in the card layout manager, so
each container requires its own CardLayout instance. A container can he set
to use a card layout only when the container has no components.
parameters
hgap A non-negative integer specifying the horizontal gap in pixels.
CardLayout
first()
java.awt
vgap /X non-negative integer specifying the vertical gap in pixels.
1 XAMPI L See the class example.
first() . _
PURPOSE Makes the container's first component current.
SXX’TaX public void first(Container cont)
DESCRIPTION The current component in the container cont is hidden and cont's first com- ponent is made current. The component need not haxe a name.
PARAMETERS cont The non-nul 1 container using this layout instance.
SEE .ALSO lastO. nextO- previousO. showO.
EXAMPLE See the class example.
getLayoutAlignmentXf)
Pl RPOSF. Retrieves this layout manager's \-alignment.
S\M XX public float getLayoutAlignmentX(Container cont)
DFSCRIPTIOX This method returns Component .CENTER-ALIGNMENT. See LayoutManager2 for more information about alignments.
PAR AMI П RS cont the non-nul 1 container using this layout manager instance.
RETURNS This layout manager's л-alignment. which must be in the range 0.0f to 1.Of.
SEI- Al SO Component.getAl i gnmentXO , Contai ner. getAl i gnmentXO » getLayoutAlignmentYO, 1 ayoutManager?.
EXAMPLE See the LayoutManager2 class example.
getLayout Alignment Y()
PURPOSE Retrieves this layout manager's v-alignment.
SYNTAX public float getLayoutAlignmentY(Container cont)
DESCRIPTION This method returns Component .CENTER-ALIGNMENT. Sec LayoutManager2 for more information about alignments.
212
parameters
cont The non-nul 1 container using this layout manager instance.
returns This layout manager’s v-ahgnment, which must be in lhe range 0.0f to 1.0f.
see also Component.getAlignmentYO , Container. getAl i gnmentYQ ,
getLayoutAlignmentXQ, LayoutManager?.
example See the LayoutManager? class example.
getHgap()
PURPOSE
Retrieves this layout manager's horizontal gap.
SYNTAX
public int getHgapO
description The horizontal gap specifies the space between the left and right edges of the
container and the current component. The horizontal gap is initialized by the
CardLayout constructor and updated using setHgapO.
returns A non-negative integer specifying the horizontal gap in pixels.
see also getVgapO, setHgapO.
example:
B0B
' CardLayout Gaps Example
This example
is a variation
on the class
example. Four
buttons label-
ed V+, V-. H+.
and H- control
the vertical
and horizontal
gaps of the First | Next | Prev [ Last | Show j
card layout. A ---------------------------------------------------------------
status button FIGURE 48: CardLayout‘s Horizontal and Vertical Gaps,
in the center is
used to display the current vertical and horizontal gaps in effect. The compo-
nent inside the panel has a blue background, while the panel itself has a red
background. See Figure 48.
import java.awt.-';
import java.awt.event.ActionLi stener;
i mport java.awt.event.Acti onEvent;
class Main extends Frame implements ActionListener {
CardLayout cardLayout - new CardLayout();
Panel cardCont = new Panel(cardLayout);
Button status;
java.awt
A
В
D
i:
F
G
H
I
J
К
1.
M
N
О
P
Q
R
S
T
u
V
w
X
Y
Z
CardLayout
getHgapf)
Main О {
super(“Cardl ayout Gaps Example'*);
cardCont.add(makeComponent(“Fi rst”), “First”);
cardCont.add(makeComponent(‘'Second”), “Second*');
cardCont. add(makeComponent(“Thi rd'’), “Thi rd”) ;
cardCont. add(makeComponent (“Show”) , “Show”);
cardCont.add(makeComponent(“Last”), “Last”);
add(cardCont, Borderlayout.CENTER);
cardCont.setBackground(Color.red);
// Create card layout control buttons
Panel p -= new Panel(new Grid!ayout(1, 0));
Button button;
p.add(button = new Button(‘Tirst"));
but ton.addActionLi stener(this);
p.add(button = new Button(“Next”));
button.addActionLi stener(thi s);
p.add(button = new Button(“Prev”));
button.addActionLi stener(thi s);
p.add(button = new Button(“Last”));
button.addActionListener(thi s);
p.add(button = new Button(“Show”));
button.addActionListener(this);
// Add row of buttons to bottom
add(p, BorderLayout.SOUTH);
// Create card layout control buttons
p = new Panel(new GridLayout(1, 0));
ActionListener gapHandler = new GapActionHandler();
p.add(button = new Button(“V+”));
button.addActionListener(gapHandler);
p.add(button = new Button(“V-”));
button.addActionLi stener(gapHandler);
p.add(button = new Button(“H+”));
button.addActionLi stener(gapHandler);
p.add(button = new Button(“H-”));
button.addActionLi stener(gapHandler);
status = new Button(“Vgap^”+cardLayout.getVgapQ +
“ , Hgap=”+cardLayout. getHgapQ)
p.add(status);
// Add gap control buttons to top
add(p, BorderLayout.NORTH);
packQ ;
show();
}
public Component makeComponent(String label) {
Label 1 = new Label(label, Label.CENTER);
1.setBackground(Col or.blue);
1.setForeground(Color.white);
return 1;
}
public void actionPerformed(Actiontvent evt) {
String cmd ~ evt .getActionCommandO;
if (“First”.equals(cmd)) {
214
cardLayout.first(cardCont);
} else if ("Prev”.equals(cmd)) {
cardLayout.previ ous(c ardCont);
} else if ("Next”.equals(cmd)) {
cardLayout.next(cardCont);
} else if ("Last”.equals(cmd)) {
cardLayout.last(cardCont);
} else if ("Show”.equals(cmd)) {
cardLayout.show(cardCont, cmd);
}
}
class GapActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String what = evt.getActionCommand();
if (“H+”.equals(what)) {
cardLayout.setHgap(cardLayout.getHgap()+5);
} else if ("H-”-equals(what)) {
cardLayout.setHgap(Math.max(0, cardl ayout .getHgapO -5));
} else if ("V+”.equals(what)) {
cardLayout.setVgap(cardlayout.getVgap()+5);
} else if ("V-”.equals(what)) {
cardLayout.setVgap(Math.max(0, cardLayout.getVgapO-5));
}
// Update status button
status.setLabel(uVgap="+cardLayout.getVgapO +
” , Hgap-”+cardi ayout. getHgapO) ;
cardCont.inval idateO ;
cardCont.val idateO ;
}
public static void main(String args[]) {
new Mai n();
}
}
getVgapt)___________
purpose Retrieves this layout manager's vertical gap.
syntax public int getVgapO
description The vertical gap specifies the space between the top and bottom edges of the
container and lhe current component. The vertical gap is initialized by the
CardLayout constructor and updated using setVgapO.
Returns A non-negative integer specifying the vertical gap in pixels.
see also getHgapO, setVgapO.
example See getHgapO.
CardLayout
invalidateLayout()
java.awt
invalidateLayout()
plrpose Invalidates this layout manager’s state.
symax public void invalidateLayout(Container cont)
Л description This method is called by the layout manager’s container to discard any cached
В information associated with this layout for the container cont. For CardLay-
M out, this method by default does not do anything.
D PARAMEI ERS
cont The non-nul 1 container using this layout instance.
E Slip ALSO LayoutManager2.
F EX AMPl I- See the LayoutManager2 class example.
G
H 1 last()
J Pl RPOSE Makes the container’s last component current.
К SYNTAX public void last(Container cont)
L DESCRIPTION The current component in the container cont is hidden and cont's last compo-
M nent is made current. The component need not have a name.
К PARAMETERS
cont Fhe non-nul 1 container using this layout instance.
0 SFF Al SO first(), next(), previous(). show().
p EXAMPLE See the class example.
Q
R s layoutContainer()
T PI’ RPOSE Lays out the container's components based on the settings of this layout man-
и ager.
v SYN'I AX public void layoutContainer(Container cont)
DESCRIPTION This method is called by the container when the layout is invalidated and needs
W to be redone. The current component in the container cont is resized to cont’s
X current dimensions, less the space used by the gaps and the container's insets.
Y PARAMETERS
7, cont The non null container using this layout instance.
EXAMPLE See LayoutManager.
216
maximumLayoutSize()
PURPOSE Calculates the maximum dimensions for laying out the components.
SYNTAX public Dimension maximumLayoutSize(Container cont)
description For a card layout, the maximum layout is by default the largest dimension available (Integer.MAX^VALUE by Integer. MAX-VALUE).
PARAMETERS cont The non-nul 1 container using this layout instance.
RETURNS Л new non-nul 1 Dimension instance containing the maximum size of the card layout.
SEE ALSO Component.getMaximumSizeО. Container, mi nimumLayoutSi zeQ. LayoutManager2, preferredLayoutSizeO.
EXAMPLE See the LayoutManager2 class example.
minimumLayoutSize()
PURPOSE Calculates the minimum dimensions needed to lay out the components.
SYNTAX public Dimension minimumLayoutSize(Container cont)
DESCRIPTION The minimum dimension is calculated by determining the minimum size of each component in the container cont. The minimum dimension of the layout is the maximum of these minimum dimensions plus the added space for the gaps and cont’s insets.
PARAMETERS cont The non-nul 1 container using this layout instance.
Returns A non-nul 1 Dimension object containing the minimum size of the card lay- out.
SEE ALSO Component.getMinimumSizeO, maximumLayoutSize(), preferredLayoutSizeO.
EXAMPLE See LayoutManager.
next()
purpose Makes the next component current.
syntax public void nextfContainer cont)
java.awt
CardLayout
preferred Layout Size()
description The current component in (he container cont is hidden, and the component
after the current component is made current. If the current component is
already lhe last component, the method call is ignored. The component need
not have a name.
A
В
PAR AM [ IT RS
cont
SEE ALSO
EXAMPLE
Г)
E
F
G
Ft
I
J
К
L
M
N
О
P
Q
R
S
T
u
V
The non-nul 1 container using this layout instance,
firstf). last(). previous(). show().
See (he class example.
preferredLayoutSize()
perpose Calculates the preferred dimensions needed to lay out the components.
syntax public Dimension preferredlayoutSize(Container cont)
description The preferred dimension is calculated by determining the preferred si/e of
each component in the container cont. l he preferred dimension of the layout
is the maximum of these preferred dimensions plus the added space for the
gaps and cont‘s insets.
PARAMETERS
cont The non-null container using this layout instance.
Ri’/rt rns A non-nul 1 Di men si on object containing the preferred si/e of the card layout.
see also Component.getPreferredSize()- maximumLayoutSize(),
mi nimumLayoutSizef).
exampi i See LayoutManager.
previous()
pi rposi Makes the previous component current.
syntax public void previous(Container cont)
descripiion l he current component in the container cont is hidden, and the component
before lhe current component is made current. If the current component is
already the first component, the method call is ignored. The component need
not ha\e a name.
PARAMETERS
cont The non-null container using this layout instance.
sei-Al so firstO. last(). nextC)- show().
exampi i- See the class example.
218
reinoveLayoutComponentt)
PURPOSE Removes a component from this layout manager
SYNTAX public void removeLayoutComponent(Component comp)
description This method removes the component comp from the layout.
PARAMETERS comp The non null component about to he removed from the container.
example See LayoutManager.
setHgapO — — —
purpose: Sets this layout manager's horizontal gap.
SYNTAX public void setHgap(int hgap)
DESCRIPTION See the class description for a discussion of a card layout manager’s gaps. This method sets the horizontal gap of this layout to be hgap.
PARAMETERS hgap A nun-negative integer specifying the horizontal gap in pixels.
SEE ALSO getHgapO , setVgapO.
EXAMPE.E See getHgapO.
setVgapt)
purpose: Sets this layout manager’s vertical gap.
syntax public void setVgap(int vgap)
DESCRIPTION See the class description for discussion of a card layout manager's gaps. This method sets the vertical gap of this layout to be vgap.
PARAMETERS vgap A non-negative integer specifying the vertical gap in pixels.
SEEAE.SO getVgapO. setHgapO.
example: See getHgapO.
java.awt
Card Layout
show()
show()
— —
purpose Makes a named component current.
SYNTAX public void show(Container cont, String name)
DESCRIPTION Phis method makes the component named by name the current component in the container cont. name is the component’s name as declared via the addLayoutComponentO method call. This call is ignored if name does not name a component in cont.
PARAMETERS cont name The non-nul 1 container containing the component. The non-nul 1 string specifying the component’s name.
EXAMPLE See the class example.
toString()
Pl ’RPOSE Generates a string representation of this layout manager’s state.
SYNTAX public String toStringO
DESCRIPTION The string representation contains the layout manager’s class name and the size of the two gaps. This method returns this string representation. This method is typically used for debugging.
RETURNS A non-nul 1 string representing the layout manager's state.
OVERRIDES j ava.1ang.Obj ect.toSt r i ng().
EXAMPLE See java.1ang.Object.toSt ri ng ().
220
Checkbox
Syntax
public class Checkbox extends Component implements ItemSelectable
Description
The checkbox is a component that maintains and displays a
check state that can be either on or off. The check state can
be changed by either the user or the program. A checkbox is
typically used to indicate a two-value choice in an applica-
tion. For example, in a mail application you may or may not
want an audible signal of new- mail. A checkbox with the
label "Play sound for new mail" would be a typical way to
display the current preference and to allow' the user to
change it.
Figure 49 shows a checkbox component with the label
“Checkbox"; the checkbox is set to on.
Checkbox Groups
Two or more checkboxes can be grouped together so that at
most one of the checkboxes in the group is set to on. That
checkbox is the current checkbox. Figure 50 shows a check-
box group containing four checkboxes. See the Checkbox-
Group class for more information about checkbox groups.
^Checkbox Ex... ИЕЕЗ
P Checkbox
FIGURE 49: Simple Checkbox.
^Checkbox Ex RRTD
C Send now
Send later’
C Dontsend
C Send at
FIGURE 50: CheckboxGroup.
Checkbox
java.awt
Events
A checkbox fires an item event whenever it is clicked. See ItemEvent for details about item.
The item of the item event is the label of the checkbox.
\ grouped checkbox fires an item event whenever it is clicked. The event is fired only by
A the new current checkbox, with lhe item of the event being the label of the new current check-
box. The previous current checkbox does not fire an event indicating that it has been turned
к off. If the current checkbox is clicked, an event is fired because the modifiers may have
(
9 In addition to item events, a checkbox fires all the events fired by the Component class.
See the Component class for details. See the AWTEvent class for details on how to Tiller or han-
die events.
h
G MEMBER SUMMARY
H Constructor
1 CheckboxO Constructs a new Checkbox instance.
J Checkbox Group Methods
К getCheckboxG roupO Retrieves the checkbox's checkbox group.
setCheckboxGroupO Sets the checkbox's checkbox group to the specified group.
L M Property Methods getLabelО Retrieves the checkbox's label.
N getStateQ Retrieves the check state of the checkbox.
setLabelО Sets the checkbox's label.
О setStateO Sets the checkbox's check state.
P Selection Method
Q . getSelectedObjectsO Retrieves the checkbox label if this checkbox is selected.
R Event Methods
S addltemLi stener() Adds a listener to receive item events fired by this checkbox.
processEventО Processes an event enabled for this checkbox.
J4 | processItemFvent() Processes an item event enabled lor this checkbox.
и removeltemLi stenerO Removes a listener from receiving item events fired by this check-
V box.
w Peer Method
x addNoti fyC) Creates the checkbox's peer.
Y Debugging Method
Z paramString() Generates a string representation of the checkbox's stale.
222
Example
For a simple example using a checkbox. see the Check-
box () constructor. The example given here is more elabo-
rate and features a program that display a set of options
that can be applied to the purchase of a car. As more options
are enabled, the price of the car increases. See Figure 51.
import java.awt.'';
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
Checkbox Ex... RWE
П Air Conditioning
P Sun Roof
П Steering Wheel
П Tires
Total Sticker Price: $27222
class Main extends Frame implements ItemListener HGlREsl: I sc of Checkbox for
{ Multiple Options.
Checkbox cbAC =
new Checkbox(“Air Conditioning”);
Checkbox cbSR = new Checkbox(“Sun Roof”):
Checkbox cbSW = new Checkbox(”Steering Wheel”);
Checkbox cbTR = new Checkbox(“Tires”);
Label status = new Label();
Main() {
super(“Checkbox Example”);
Panel gridPanel = new Panel(new GridLayout(0, 1));
gridPanel.add(cbAC);
gri dPanel.add(cbSR);
gri dPanel . add(cbSW') ;
gri dPanel.add(cbTR);
add(gridPanel, BorderLayout.CENTER);
// Set listener for each checkbox
cbAC.addltemLi stener(this);
cbSR.addltemLi stener(this);
cbSW.addltemLi stener(thi s) ;
cbTR.addltemLi stener(thi s);
computeTotal();
add(status, BorderLayout.SOUTH);
packQ ;
show();
}
public void i temStateChangeddtemEvent evt) {
computeTotal() ;
}
void computeTotal () {
int total = 25000;
if (cbAC.getStateO) total += 510;
if (cbSR. getStateO) total *= 2222;
if (cbSW.getStateO) total *= 150;
if (cbTR. getStateO) total *= 320;
status.setText(“Total Sticker Price: $” + total;;
static public void main(String[J args; {
new via i n ( ) ;
java.awt
Checkbox
addlteniListenerO
addltemListenerO
pcrposf Adds a listener to receive item events fired by this checkbox.
SYNTAX
DESCRIPTION
PARAMETERS
listener
SEE ALSO
EXAMPLE
public synchronized void addltemLi stenerdtemLi stener listener)
An item event is fired when this checkbox is checked. See ItemEvent and the
class description for more details. After this method is called, the item listener
listener will receive item events fired by this checkbox. If listener is
nul 1, this method does nothing.
The possibly null item listener to add.
ItemSelectable, java.awt.event.ItemEvent,
java.awt.event.Item!istener, removeltemListenerf).
See the class example.
j addNotifyC)
К Pl RPOSE Creates the checkbox's peer.
1. SYNTAX public void addNotifyO
M DESCRIPTION This method creates the peer if it does not exist. The peer is created by calling
N the Toolkit.createCheckbox() method.
() This method should never be called directly. It is normally called by the parent.
P OVERRIDES Component.addNoti fy().
Q SEE ALSO Component. Toolkit.
R EXAMPLE See Component.setVisi ble().
T Checkboxf)
I purpose: Constructs a new Checkbox instance.
V SYNTAX public CheckboxO
W public Checkbox(String label) public Checkbox(String label, boolean state)
X public Checkbox(String label, boolean state, CheckboxCroup group)
Y public Checkbox(String label, CheckboxGroup group, boolean state)
7 DESCRIPTION This constructor creates a new visible checkbox component with the label label, checkbox group group, and initial check state state. A null label is the same as If the label is not specified, it defaults to null. If state is not
224
gCIS ilCCKDOXkjrOlipt
specified, it defaults to false. If group is null, the checkbox will not be
included in any checkbox group. If group is not specitled, it defaults to nul 1.
PARAMETERS
group The checkbox group in which to include the new checkbox. May be null,
label A string specifying the label on the checkbox. Ma\ be null.
state A bool ean specifying the checkbox's initial check state.
example This simple example creates a checkbox | t with the label “Checkbox" and prints the 1^19№ЩШ|1|КИмЬыа1ж1 current state of the checkbox each time it is СЬесИзох clicked. See Figure 52. FIGURE52: Simple Checkbox.
import java.awt.*;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
class Main extends Frame implements ItemListener {
Checkbox cb - new Checkbox(“Checkbox");
MainQ {
supe[-(“Checkbox Example”);
addfcb, BorderLayout.NORTH);
cb.addltemlistener(thi s);
pack();
showO;
)
public void itemStateChanged(ItemEvent evt) {
Object obj = evt.getSource();
if (obj instanceof Checkbox) {
System.out.println("checkbox: “ + ((Checkbox)obj) .getStateO) ;
}
}
static public void main(Stringfl args) {
new Mai n();
}
}
getCheckboxGroupf)
purpose Retrieves the checkbox's checkbox group.
syntax public CheckboxCroup getCheckboxCroupO
descript ion If the return value is null, the checkbox is not a group checkbox.
Returns The checkbox’s checkbox group. The return value may be null. This means
the checkbox is not in a checkbox group.
java.au t
Checkbox
get Label ()
see also setCheckboxGroupO •
example Sec setCheckboxGroupO.
A get Label()
в ” “ — '
pt‘rpose Retrieves the checkbox's label.
symax public String getlabelf)
I)
ri ri rns Л string containing the checkbox^ label. The result value tnav be null
E
si t also setlabel () .
1 I’Xampi f See set Label O.
G
н
j getSelectedObjects()
J Pt’RPOSL Retrieves the checkbox's label it this checkbox is selected.
к SYNTAX public Object[] getSelectedObjectsO
1. M N RFTl’RNS An array with one item containing the checkbox’s label if the checkbox is selected: null olherwise.
SEL Al SO getLabelO. ItemSelectable.
() EXAMPLE See the class example of ItemSelectable.
p
Q
R
S
T
и
V
w
X
Y
7
getState()
piRposE Retrieves the check state of the
checkbox.
syntax public boolean getStateO
rf.tlrns true if the check state is set to on:
fal se otherwise.
si-l also setStateQ.
l-XAMPi f This example creates a checkbox and
a text area. If the checkbox is set to
off. the text area behaves normally. If
the checkbox is set to on. all charac-
ters typed in the text area are con-
verted to uppercase. See Figure 53.
getState Example |H|iJ S3
Here are some lowercase
characters NOW FOR
SOME UPPERCASE
CHARACTERS
«I_______ ______I
FIGI RE 53: Using Checkbox to Control
a TextArea.
226
puidlliou iEJ£U }
import java.awt. ;
import java.awt.event. ;
class Main extends Frame {
Checkbox cb - new Checkbox(k,upper Case1’);
TextArea ta = new TextArea(10, 40);
Main О {
super(“getState Example’1);
add(cb, BorderLayout.NORTH);
add(ta, BorderLayout.CFNTFR);
ta.addKeylistener(new Keyli stener());
packQ;
showO;
}
// Define listener to deal with upper case mode
class KeyListener extends KeyAdapter {
public void keyPressedfKeyEvent evt) {
char ch - evt.getKeyChar();
if (cb.getState() && Character.isLowerCase(ch)) {
evt.setKeyChar(Character.toUpperCase(ch));
}
}
}
static public void main(String^] args) {
new Main();
}
}
paramStringf)
PURPOSE Generates a string representation of the checkbox’s state.
SYNTAX protected String paramString()
DESCRfH ION The returned string includes the checkbox's label and check state. /\ subclass of this class should override this method and return a concatenation of its state with the results of super.paramStringQ. This method is called by (he toStringO method and is typically used for debugging.
RETURNS A non-nul1 string representing the checkbox's state.
OVERRIDES Component.paramString().
SEE ALSO toStri ng().
example See Component.paramStri ng().
java.aw i
Checkbox
processEvent()
processEventO
pi rposf. Processes an event enabled for this checkbox.
D
E
F
G
H
1
J
К
L
M
N
о
p
Q
R
S
T
i:
syntax protected void processEvent(AWlEvent evt)
description This method extends Component.processEventO b\ adding support for
ItemFvent.
When a subclass overrides processEventO. it should call super. process-
EventO to perform the processing intended by its base class (such as dis-
patching the listeners).
PARAMETERS
evt The event to be processed.
overrides Component. processEventO .
see also AWTEvent, processItemEventQ ,
example See ItemSel ectabl e's class example.
processItemEventO
purpose Processes an item event on this checkbox.
v
w
X
Y
7.
syniax protected void processItemEvent(ItemEvent evt)
description An item event is fired when this checkbox is clicked. See ItemEvent and the
class description for more details. This method processes item events for this
checkbox by calling any registered ItemLi stener. This method is invoked
only if item events have been enabled for this checkbox. This can happen
either when an item listener is added to this component or if item events are
enabled explicitly via Component .enableEventsO.
Typically, a program controls how item events for a checkbox are processed. It
does this by adding or removing item listeners. It overrides processItem-
EventO only if it needs to do processing in addition to that performed b\ the
registered listeners.
When a subclass does override processItemEventO. it should cull
super. processItemEventO to perform lhe processing intended by its base
class (such as dispatching the listeners).
PAR A METERS
evt The event to be processed.
SEE At .so java.awt.event,IremEvent, ItemSelectable,
java.awt.event.ItemListener, processEventO.
ex ample See ItemSe 1 ectabl e's class example.
228
renioveltemListenerf)
PLRPOSl Removes a listener from recciv mg item events from thi^ checkbox.
SYNTAX public synchronized void removeltemListener(ItemListener 1i stener)
description An item event is fired when this checkbox is clicked. See ItemEvent in the class description for more details. After this method is called, the item listener listener will no longer receive item events from this checkbox. If listener is null, this method does nothing.
PARAMETERS li stener The possibly null item listener to remove.
SEE ALSO addltemListener(), ItemSelectable, java.awt.event.ItemEvent, java.awt.event.ItemLi stener.
EXAMPLE. See the usage of removeActionListener() in Menuitem.dispatch- EventsQ.
setCheckboxGroupl)
purpose Seis the checkbox’s checkbox group.
syntax public void setCheckboxGroupfCheckboxGroup group)
description This method is used to change a checkbox’s checkbox group. It is not used
very often, as checkboxes do not typically change groups after they are cre-
ated. The checkbox group of a checkbox is typically known at the lime the
checkbox is created, so it is supplied to the checkbox constructor method.
PARAMETERS
group The checkbox’s new checkbox group. A value of null removes the checkbox
from its current group.
seealso getCheckboxGroupO .
example This example creates two check-
box groups called “Left” and
“Right.” Bv using the choice
component at the bottom, the
user can make the checkbox at
the top part be of either group or
of nogroup. See Figure 54.
import java.awt.’';
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent:
lESsetCheckboxGroup Ex . ЯЕВ1
s
C Left <* Right
C Left Г Right
juft 21
I КЛ RE 54: Dynamically Modifying
CheckboxGroup Membership.
Checkbox
java.awt
seiLabeK)
В
I)
E
F
G
H
1
J
К
I.
M
N
()
P
Q
R
S
T
I
V
class Main extends Frame implements ItemListener {
CheckboxGroup cgLeft = new CheckboxGroupQ;
CheckboxGroup cgRight new CheckboxGroup() ;
Choice choice = new ChoiceO;
Checkbox cb = new Checkbox('T eft", cgLeft, true);
Main О {
super("setCheckboxGroup Example");
Panel p new Panel(new GridLayout(0, 1));
add(cb, BorderLayout.NORTH);
p.add(new Checkbox(‘‘Left”, cgLeft, false));
p,add(new Checkbox(“Left”, cgLeft, false));
add(p, Border!ayout.WEST);
p = new Panel(new GridLayout(0, 1));
p,add(new Checkbox( “Right", cgRight, false));
p.add(new Checkbox(“Right", cgRight, false));
add(p, BorderLayout.LAST);
choice.addltem("None”);
choice.addItem("Left");
choice.addItem(“Right");
choi ce.select("Left");
choice.addltemLi stener(this) ;
add(choice, BorderLayout.SOUTH);
packO;
show();
}
public void itemStateChanged(ItemEvent evt) {
String what = (Stri ng) (evt .getltemO) ;
cb.setLabel((String)what);
if ("None".equals(what)) {
cb.setCheckboxGroup(null);
} else if (“Left".equals(what)) {
cb.setCheckboxGroup(cgLeft);
} else if ("Right".equals(what)) {
cb.setCheckboxGroup(cgRight);
}
}
static public void mainfStringC] args) {
new Mai n();
}
}
x setLabel()
Y
pi rposl Sets the checkbox's label.
Z
syntax public synchronized void setLabel(String label)
230
setLabcK
DESCRIPTION Note that the minimum and preferred sizes of the checkbox may change, so i may be necessary to resize the checkbox. The example shows how ю cause tht checkbox's parent to resize the checkbox.
PARAMETERS label The non-null string specifying the checkbox's new label.
SEE ALSO getLabel().
EXAMPLE This example creates a checkbox and a text field. Pressing Return in the text field causes the checkbox label to be Checkbox set to the contents of the text field. | Checkbox When the label changes, so does its — minimum size. This example also HGIRE55: Changing Checkbox’s shows how to cause the checkbox’s Label, parent to properly resize the checkbox. The canvas to the right of the checkbox is there to force the checkbox to be a* narrow' as possible. See Figure 55.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class Main extends Frame implements Actionlistener {
Checkbox cb = new Checkbox("Checkbox”);
TextField tf new TextEield(40);
Main» {
superC'setLabel Example”);
add(new CanvasO, BorderLayout.CENTER);
add(cb, BorderLayout.WEST);
add(tf, BorderLayout.SOUTH);
tf.setText(cb.getLabeI()); // Initialize with current label
tf.addActionl istener(this); // Set listener for updating label
pack();
show() ;
}
public void actionPerformed(ActionEvent evt) {
cb.setLabel(tf.getText());
// Invalidate this checkbox because of size change
cb. inval idateO ;
// Validate parent to resize checkbox
cb. get Parent О . val idateO ;
J
static public void main(Strinqn args) {
new MainO ;
1
}
java.awt
Checkbox
setStatcf)
setState() pt rpom-: Sets the checkbox's check slate. sysfax public void setState(boolean state)
A dkscripiios The method call is ignored when this is both a group checkbox and the curreni
В checkbox. PARA METERS
D F. F state If true, the checkbox's check state is set to оя: otherwise, it is set to off see also getStateO. ex ample This example creates a checkbox and a checkbox menu item and synchronizes i \
G their check states. If the checkbox is set *soun^^CTn^w mai/ |
H I to oik so is the checkbox menu item. See Figure 56. _ import java.awt.7';
J import java, awt. event. Iteir.L i stener; „ . _ .. ♦ import java.awt.event.ItemEvent; MGIRE56: < hanging Checkbox s
К class Main extends Frame Mate, implements ItemListener {
I. CheckboxMenuItem mi = new CheckboxMenuItem(”Play sound for new mail”); Checkbox cb = new Checkbox(“Pl ay sound for new mail”);
M Main() {
N super(“setState Example”); MenuBar mb - new MenuBarO;
О Menu m = new Menu(“Options”);
P m.add(mi); mb.add(m);
Q setMenuBar(mb); add(cbT BorderLayout.SOU1H);
R S T I // Set listeners for checkbox and checkbox menu item cb.addltemti stener(thi s); mi.addltemLi stenerfthi s); pack(); show(); } public void itemStateChanged(ItemEvent evt) {
V if (evt.getSourceO == mi) { cb.setSt ate(mi.get State());
W } else { mi ,setState(cb.getStateO);
X j // playSoundforNewMai1(); i
Y Z J static public void main(String[] args) { new Mai n(); } }
232
CheckboxGroup
Syntax
public class CheckboxGroup -implements Serializable
Description
The checkbox group is used to group checkbox components: it
is not an AWT component. In a checkbox group, at most one
checkbox is in the on state. This checkbox is the currently
selected checkbox. Selecting any of the other checkboxes in the
group causes that checkbox to become the currently selected
checkbox and all other checkboxes in the group to be automati-
cally set to off. Figure 57 shows a checkbox group that contains
four checkboxes: the ‘’Send later' checkbox is set to on. See the
> Checkbox... [WIREI
C Send now
<• Send later
C Doni send
C Send at |7:10pm|
FIGURE 57: CheckboxGroup.
Checkbox class for more information about checkboxes.
It is possible that none of the checkboxes in the group are set to on. This can happen in one
of two ways:
1. If none of the checkboxes that are added to the group are set to on.
2. If the current checkbox in the group is removed from the group.
Checkbox Group versus Choice Component
The choice component is similar to the checkbox group in that it lets the user choose from a
fixed set of items (see the Choice class). Following are two design guidelines to consider
when deciding between the checkbox group and the choice component. As with all user inter-
face “principles,” these guidelines are intended to summarize the issues and not mandate your
design.
1. The larger the number of items, the more appropriate the choice component becomes.
You should probably use a choice component if you have five or more items.
2. If a group of one or more components is related to one particular item and is therefore
enabled only if that item is selected, a checkbox group might be appropriate.
CheckboxGroup
ja\ a. aw l
A MEMBER SUMMARY ! Constructor CheckboxGroupO Constructs a new CheckboxGroup instance. Selected Checkbox Methods
getSe1ectedCheckbox() Retrieves the currcntlv selected checkbox. setSelectedCheckbox() Sets the currcntlx selected checkbox.
D E Debugging Method toStringO Gcnciales a string representation ol the checkbox group’s state. Deprecated Methods
1 (i qetCurrentO Replaced bv getSelectedCheckbox(). setCurrentO Replaced bv setSe 1 ectedCheckbox0
H
1
। See Also
Checkbox, Choice, java.iо.Seri alizable.
К
1 Example
M lliis example creates a checkbox group and a col-
lection of colored canvases. Clicking a checkbox
N
causes its associated color canvas to be selected.
() Also, clicking a colored canvas causes its associ
l> aled checkbox to be current. Sec Figure 5S.
CheckboxGroup Example BBE
Rjed
Green
Г Blue
Q ГКД Rl 5S: Fse of CheckboxGroup for
К Exclusive Options,
import java.awt.’-';
S import java.awt.event;
1 class Main extends Frame implements Itemlistener {
ColorLJ cbColor = {Color.red, Color.green, Color.blue};
I' Stringf] cbName = {"Red”, "Green”, "Blue”}:
MainCanvas[] cbCanvas = new MainCanvas{3 J;
V CheckboxGroup egroup = new CheckboxGroupO:
W Main О {
super("CheckboxGroup Example”);
X Panel p = new Panel(new GridLayout(0, 11),
colorpanel new Panelfnew GridLayout(1. 0));
Y
for (int i=0; i <cbCol or. 1 engt h ; in) {
/ Checkbox cb = new Checkbox(cbName[i ]. egroup, i - 0);
p.add(cb) ;
cb.addltemListener(thi s) ;
colorPanel.add(cbCanvas[i] = new MainCanvas(cbColor{iJ, cbl);
234
cbCanvas[iJ•setSize(70, 70);
}
add(pr BorderLayout.hFSl);
addfcolorPanel, Borderlayout.CENTER);
pack();
showO;
}
public void itemStateChanged(ItemEvent evt) {
// Update canvases when checkbox pressed
for (int i-0; i<cbCanvas.length; i++) {
cbCanvas[i].repaint();
}
static public void main(String[] arqs) {
new Main() ;
}
}
class MainCanvas extends Canvas {
Checkbox cb;
MainCanvas(Color color, Checkbox cb) {
setBackground(color);
this.cb = cb;
addMouseListener(new Mousel istenerC));
}
public void paint(Graphics g) {
if (cb.getCheckboxGroupO.getSelectedCheckboxO == cb) {
Dimension d = getSizeO;
g.setColor(Color.black);
g.fi1lOval(d.width/3, d.height/3, d.width/3, d.height/3);
}
class MouseListener extends MouseAdapter {
public void mousePressed(MouseFvent evt) {
// Update checkbox group
cb.getCheckboxGroupO.setSe1ectedCheckbox(cb);
// Update all sibling canvases.
for (int i-0; i<getParent() .getComponentCountO ; i+*) {
getParent().qetComponent(i).repaint();
}
}
}
}
CheckboxGroup
CheckboxGroup()
java.awl
CheckboxGroupf)
purpose Constructs a new CheckboxGroup instance.
syntax public CheckboxGroupO
example This example creates a checkbox
group that has three buttons. When a
checkbox is clicked» it prints out the
new state of the checkbox. See Figure
59.
import java.awt.*;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
FIGURE 59: CheckboxGroupO.
class Main extends Frame implements ItemListener {
CheckboxGroup eg = new CheckboxGroupO;
Main О {
super(”CheckboxGroup Example”);
Panel p = new Panel(new GridLayout(0, 1));
Checkbox cb;
p.add(cb = new Checkbox(‘‘Send now”, eg, true));
cb.addltemLi stenerCthi s);
p.add(cb = new Checkbox(“Send later", eg, false));
cb.addltemLi stenerCthis);
p.addCcb = new CheckboxC'Dont send”, eg, false));
cb.addltemlistenerCthis);
add(pT BorderLayout.CENTER);
pack();
show();
}
public void itemStateChanged(ItemEvent evt) {
String what = CString)(evt.getltemSelectableC)•
getSelectedObjectsC)[0]);
System,out.println(what);
}
static public void main(String[] args) {
new Mai n();
}
1
getCurrent()
l)EPKE( ATEI)
purpose Replaced by getSelectedCheckboxO.
syntax public Checkbox getCurrentO
deprecation Replace the usage of the deprecated method
236
Checkbox cb = cbgroup.getCurrentO;
with
Checkbox cb - cbqroup.getSelectedCheckboxO;
returns The currently selected checkbox in the group. The return value may be null.
getSelectedCheckbox()
PURPOSE Retrieves the currently selected checkbox.
SYNTAX public Checkbox getCurrentO
description This method retrieves lhe currently selected checkbox. The check state of the currently selected checkbox will always be set to on. If the return value is null, then either there are no checkboxes in the group or none of the check- boxes are set to on.
RETURNS The currently selected checkbox in the group. The return value may be null.
SEE ALSO setSelectedCheckboxО.
EXAMPLE Sec the class example.
setCurrentf)
DEPRECATED
PURPOSE Replaced by setSelectedCheckbox().
SYNTAX public synchronized void setCurrent(Checkbox checkbox)
PARAMETERS checkbox The checkbox to be selected. May be null.
DEPRECATION Replace the usage of the deprecated method cbgroup.setCurrent(checkbox); with cbgroup.setSelectedCheckbox(checkbox);
setSelectedCheckboxf)
PURPOSE Sets the selected checkbox.
SYNTAX public synchronized void setSelectedCheckbox(Checkbox checkbox)
DESCRIPTION This method sets checkbox to be the currently selected checkbox. If check- box is null, none of the checkboxes in the group will be made current. The method is ignored if checkbox belongs to a different group.
java.awt
CheckboxGroup
loString()
PARA ME I ERS
checkbox The checkbox to be selected. May be nul 1.
se.e also getSelectedCheckboxO-
example See the class example.
toString()
Pl RPOSE
SYNTAX
DESCRIHION
RE1 I RVS
OVERRIDES
Generates a string representation of the checkbox group's state.
public String toStringO
This method returns the string representation of this checkbox group'?
(the checkbox that is currently selected). It is typically used for debuggir
?\ non-nul 1 string representing the checkbox group's state.
java.lang.Object. toStringO .
j EXAMPLE
CheckboxGroup gb = new CheckboxGroupO;
К Checkbox cb new CheckboxCRead-only", gb, true);
System.out.println(qb) ;
I.
M
IN
()
P
Q
R
S
I
i:
v
w
x
A'
7
238
CheckboxMenuItem
Syntax
public class CheckboxMenuItem extends Menuitem implements ItemSelectable
Description
A checkbox menu item adds an additional property to a Menuitem object: the check slate. The
checkbox menu item's check state is always in one of two states: on or off. It can be changed al
any time by either the user or a program. A checkbox menu item is typically used to indicate a
two-value choice in an application. For example, in a mail application you may or may not
want an audible signal of new mail. A checkbox menu item with the label "Play sound for new
mail" would be a typical way to display the current preference and to allow the user to change
it.
Figure 60 shows a menu displaying two
checkbox menu items. The one labeled "Play
sound for new mail" is set to on. while the one
labeled "Pop dialog for new mail" is set to off.
Events
The checkbox menu item fires an action event just
like the menu item does (see Menuitem for
details).1 In addition, the checkbox menu item also
1^ CheckboxMenuItem Ex..
Pla^ sound for new mail Pop dialog for new mail
HGl ИЕ 60: CheckboxMenuItem.
fires an item event when the state of the checkbox changes, flic item of the item e\ent is the
label of the checkbox menu item.
The checked state of the checkbox menu item is automatical!} set before the action or item
event is fired. For example, if the checked state is current!} true and the user selects the
checkbox menu item, the checked state is set to fal se and then lhe event is fired.
1. In Java 1.1.2. a checkbox menu item does not lire action events even though it is a subclass o| Menultem.
This is a but?
Checkbox Men u Item
java.awt
See the Menuitem class for more details about the action event. See ItemEvent for more
details about item events. See the AWTEvent class for general information on events and how
to filter or handle them.
A
В
D
E
F
G
ft
I
J
К
L
M
N
О
P
Q
R
S
T
u
MEMBER SUMMARY 1 i
Constructor CheckboxMenuItemf) Constructs a new’ CheckboxMenuItem instance.
State Methods getStateO setStateO Retrieves the checked stale of the checkbox menu item. Sets the checkbox menu item's check state.
> Selection Method getSelectedObjects О Retrieves the checkbox menu item's label if this item is selected.
Event Methods addlteml i stenerO processItemEventO processFvent() removeTtemLi stenerO . Peer Method addNotifyO Adds a listener to receive item events fired b_v this checkbox menu item. Processes an item event enabled for this checkbox menu item. Processes an event enabled for this checkbox menu item. Removes a listener from receiving item events tired bv this checkbox menu item. Creates the checkbox menu item's peer.
Debugging Method paramStringQ Generates a string representation of the checkbox menu's state.
w
X
Y
Z
See Also
AWTEvent, Checkbox, java.awt.event.ActionEvent,
java.awt.event.ActionListener, java.awt.event.ItemEvent,
java.awt.event.ItemListener. Menuitem.
Example
This example creates a menu with two checkbox menu items. The one labeled “Play sound for
new mail" is enabled and the one labeled “Pop dialog for new mail" is disabled. See Figure 60
for a screen shot of the example. The menu is installed in a menu bar. which in turn is installed
in a frame. This example also shows you how to handle item events fired by a checkbox menu
item.
240
import java.awt.*;
import java.awt.event.ItemLi stener;
import java.awt.event.ItemEvent;
class Main extends Frame implements Itemlistener {
CheckboxMenuItem sound, popup;
Main О {
superC'CheckboxMenuItem Example”);
MenuBar mb - new MenuBar();
Menu m - new Menu(“Options");
m.add(sound - new CheckboxMenuItem(*'Play sound for new mail”));
sound.addltemlistener(this);
m.add(popup = new CheckboxMenuItemC'Pop dialog for new mail''));
popup.addltemListenerfthis);
mb.add(m);
// Set the menu bar on the frame.
setMenuBar(mb);
setSize(100, 50):
showQ;
}
public void itemStateChanged(TtemFvent evt) {
Object src = evt. getSourceQ ;
if (src == sound) {
// playSoundO;
System.out.printInC'Play sound”);
} else if (src — popup) {
// popDialogO;
System.out.printlnC'Pop dialog”) ;
}
}
static public void main(String[] args) {
new Mai n();
}
}
addltemListenerl)
PURPOSE Adds a listener to receive item events fired by this checkbox menu item.
SYNTAX public synchronized void addltemlistener(ItemListener listener)
description An item event is fired when this checkbox menu item is selected or deselected. See ItemEvent for more details. After this method is called, the item listener listener will receive item events fired by this checkbox menu item.
parameters listener The item listener to add.
SEE ALSO ItemSelectable, java.awt.event.ItemEvent, java.awt.event.Ttemlistener, removeltemListener().
ВХЛМР1 F: See the class example.
Check box Menuitem
add Noli fy( )
java.au l
В
D
E
Г
G
H
I
J
addNotify()
per pose (.’reales the checkbox menu item's peer.
symax public void addNotifyO
description This method creates the checkbox menu item's peer if it does not exist. The
peer is created by calling the Toolkit.createCheckboxMenuItemO
method.
This method should never be called di redly. It is normally called by the check
box menu item's parent.
o\ lrrjdi-s Menu Item. addNot i fy().
seealso Menuitem, Toolkit.
example See the similar usage of Component.addNoti fy() in Component. setvi si-
ble().
CheckboxMenuItem()
Pt rpose- Constructs a new CheekBoxMenultem instance.
syntax public CheckboxMenuItemO
public CheckboxMenuItemfString label)
public CheckboxMenuItem(String label, boolean state)
description This constructor creates a new CheckBoxMenuItem instance with the label
label and initial check state state. A null label is the same as ,,n. If the
label is not specified, it defaults to null. If state is not specified, it defaults
to false.
PARAMETERS
label The non-nul 1 string specifying the checkbox menu item's label.
state A boolean specifying the checkbox menu item's initial checked state.
see ai so Menu I ten.
ex am pi e Sec the class example.
getSelectedObjects()
у Pl’RPOSE. Retrieves the checkbox menu item's label if this item is selected.
/ SV M AX public Objectn getSelectedObjectsO
RE1TI RNS An array with one item containing the checkbox menu item's label if the item is selected: null otherwise.
242
SEE also ItemSelectable.
example See ItemSelectable\ class example.
getState() ___ _____ ____________________
purpose Retrieves the checked state of the checkbox menu item.
syntax public boolean getStateO
returns true if the checkbox menu item is checked; false otherwise.
example-: This method prints the checked state of all checkbox menu items in the menu
bar.
void printMenuLabels(MenuBar menubar) {
for (int i-0; i<menubar.getMenuCount(); i+*) {
Menu menu - menubar.getMenu(i);
for (int j=0; jcmenu.getltemCountO; j+*) {
if (menu.getlter(j) instanceof CheckboxMenuItem) {
CheckboxMenuItem mi - (Checkbox^enuTtem)rnenu.getltem(j);
System.out.print 1n(mi.getlabel() + "
+ mi .getStateO):
)
}
}
paramStringf)
purpose Generates a string representation of the checkbox menu item’s state.
syntax public String paramString()
description The string includes the label and the enabled and checked stales of the check-
box menu item component. This method is called by the toStringO method
and is typically used for debugging.
returns A non-nul 1 string representing the checkbox menu item's state.
overrides MenuTtem.paramStri ng().
see also MenuComponent.toStri ng О, java.lang.Object.toStri ng().
processEventO
purpose Processes an event enabled for this checkbox menu item.
syntax protected void process!"vent (AWTFvent evt)
java.awt
Checkbox Menultem
processhemEventt)
DESCRIPTION
PARA Mt IERS
evt
OVERRUN'S
SEE ALSO
EXAMPLE
This method extends Menuitem.processEventO by adding support for
ItemEvent.
When a subclass does override processEventO. it should call
super. processEventO to perform the processing intended by its base class
(such as dispatching the listeners).
The event to be processed.
MenuTtem.processEventО
AWTEvent, processltemEventО.
See Component's class example.
н processltemEvent()
pi rposf Processes an item event enabled for this checkbox menu item.
J SY VI AX
K DESCRIPTION
I.
M
N
()
P
Q
R
S
T
r PARAMETERS
V evt
w SEE ALSO
X
EXAM PI E
Y
protected void processItemEvent(ltemEvent evt)
An item event is fired when this checkbox menu item is selected or deselected.
See ItemEvent for more details. This method processes item events for this
checkbox menu item by calling any registered ItemLi stener. This method is
invoked only if item events have been enabled for this checkbox menu item.
This enabling happens automatically when an item listener is added to this
component.
Typically, a program controls how item events for a checkbox menu item are
processed by adding or removing item listeners. It overrides processitem
EventO only if it needs to do processing in addition to that performed by the
registered listeners.
When a subclass does override processItemFventO- it should call
super. processItemEventO to perform the processing intended by its base
class (such as dispatching the listeners).
The event to be processed.
java.awt.event.ItemEvent. ItemSelectable,
java.awt.event.ItemLi stener, processEvent().
See ItemSel ectable's class example.
244
removelteniListenerl)
pcrpo.se Removes a listener from receiving item events from this checkbox menu item.
SYNTAX public synchronized void removeltemListener(ItemListener 1i stener)
description An item event is fired when this checkbox menu item is selected or deselected. See ItemEvent for more details. After this method is called, the item listener li stener will no longer receive item events from this checkbox menu item.
parameters 1i stener The item listener to remove.
SEE ALSO addltemListenerO, ItemSelectable, java.awt.event.ItemEvent, java.awt.event.ItemLi stener.
EXAMPLE See removeActionListener() in Menuitem.disableEventsO.
setState()
Pt-KPOSE
Seis the checkbox menu item's check state.
syntax public synchronized void setStatefboolean state)
description The method call is ignored if the check
state docs not change.
PARAMETERS
state If true, the checkbox's check state is set
to on\ otherwise, it is set to off.
see also getStateO.
example This example creates a checkbox and a
checkbox menu item and synchronizes
their check states. If the checkbox is set
to on. so is the checkbox menu item. See
Figure 61.
set St ate Example
Exit
P Sere All Fifes On Ёхй|
FIGI RE 61: Synchronizing a
Checkbox with a CheckboxMenuItem.
import java.awt.--;
import java.awt.event.ItemLi stener;
import java.awt.event.ItemEvent;
class Main extends Frame implements ItemListener {
CheckboxMenuItem mi = new CheckboxMenuItemC“Save All Files On Exit");
Checkbox cb = new Checkbox(“Save All Files On Exit");
MainQ {
super(“setState Example");
MenuBar mb = new MenuBarC);
Menu m = new Menu("Fi1e");
Checkbox Menu I tem
java.awt
setStatef)
D
E
l-
G
II
I
J
К
I.
M
N
()
P
Q
R
S
m.add(mi);
m.add(“Exit");
mb.add Cm);
setMenuBar(mb);
// Add the checkbox
addCcb, Border!ayout.SOUTH):
// Set listeners for checkbox and checkbox
cb.addltemLi stener(thi s) ;
mi.addltemL i stener(t hi s);
packO;
show();
}
public void itemStateChanged(TtemEvent evt) {
if (evt.getSource() == mi) {
cb. setStatefmi .getStateO) ;
} else {
mi. setState(cb.getStateO) ;
}
// saveAl1Fi1es();
static public void main(String[] args) {
new Mai nO;
}
T
и
V
w
X
Y
z
246
Checkbox MenuItemPeer
Syntax
public interface CheckboxMenuItemPeer extends MenuItemPeer
Description
The checkbox menu item component (see CheckboxMenuItem class) in the AWT uses the
platform’s native implementation of a checkbox menu item. So that the AWT checkbox menu
item component behaves the same on all platforms, the checkbox menu item is assigned a peer.
whose task is to translate the behavior of the platform s native checkbox menu item to the
behavior of the AWT checkbox menu item.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
See Component and Toolkit for additional information about component peers.
SUMMARY
Peer Method
setStateО Sets the checkbox menu item’s check state.
See Also
java.awt.CheckboxMenuItem, java.awt.Component, java.awt.Toolkit.
Check box M enul temPce г
setSiate()
java.awt.peer
setState()
PCRPOSE Sets the checkbox menu item’s check state.
SV M AX void setStatefboolean state)
PARAMI’TKRS state If true, the checkbox’s check state is set to on; otherwise it is set to off.
SLL ALSO java.awt.CheckboxMenuItem.setStateQ.
248
CheckboxPeer
Syntax
public interface CheckboxPeer extends ComponentPeer
Description
The checkbox component (see the Checkbox class) in the AWT uses the platform's native
implementation of a checkbox. So that the AWT checkbox component behaves the same on all
platforms, the checkbox is assigned a peer, whose task is to translate the behavior of the plat-
form's native checkbox to the behavior of the AWT checkbox.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt. These in turn automatically manage their peers.
Only someone who is porting the AWT to another platform should be concerned with the peer
classes and interfaces. Consequently, most peer documentation refers to java.awt counter-
parts.
See Component and Tool ki t for additional information about component peers.
Peer Methods
setCheckboxGroupO
setLabelО
setStateO
Sets the checkbox peer’s checkbox group.
Sets the checkbox peer’s label.
Sets the checkbox peer’s check state.
CheckboxPeer java.awt.peer
setCheckboxGroup()
See Also
java.awt.Checkbox, java.awt.Component, java.awt.Toolkit.
setCheckboxGroup()
pt rpose Sets the checkbox peer's checkbox group.
syntax void setCheckboxGroup(CheckboxGroup g)
PARA Mt I LRS
g The checkbox peer's new checkbox group. A value of null removes lhe
checkbox peer from its current group.
see also java.awt.Checkbox.setCheckboxGroupO.
setLabel()
per pose Seis the checkbox peer's label.
s\niax void setLabel(String label)
PARAMEIERS
label The non-null string specifying the checkbox peer s new label.
see also java. awt.Checkbox . setLabel ().
setState()
pl rpose Sets the checkbox peer's check state.
syntax void setState(boolean state)
PARAML I LRS
state If true, the checkbox peer's check state is set to on: otherwise it is set to off.
see also java.awt.Checkbox.setState О
250
гтттгггт
Choice
Syntax
public class Choice extends Component implements ItemSelectable
Description
A choice is a component that lets the user choose from a fixed set of string items. It is similar (
to a list, except that it occupies much less screen space in its normal state. In its normal state,
the choice component displays the currently selected item. In its activated state, it displays the
entire list of choices. Once a selection has been made, the choice component shrinks to a single ।
line and displays the newly selected item.
The checkbox group is a component that resembles a choice component in that it lets the
user choose from a fixed set of items (see the Checkbox class). Following are two design
guidelines to consider when deciding between the choice component and the checkbox group.
As with all user interlace “principles/* these guidelines are intended to summarize the issues,
not to mandate your design.
1. The larger the number of items, the more appropriate the choice component becomes.
You should probably use a choice component if you have five or more items. \
2. It a group of one or more components is related to one particular item and is therefore
enabled only if that item is selected, a checkbox group might be more appropriate.
The Selected Item
If there arc any items in the choice, one is always selected. This is called the selected item. The
selected item can be changed by either the program or the user.
Choice
java.awt
Events
A choice fires an item event whenever the user selects an item. See ItemEvent for more
details. The item of the item event is the label of choice’s newly selected item. Even if the
selected item is reselected, an item event is fired, since the modifier keys may have changed.
In addition to generating item events, a choice also fires all the events fired the Compo-
nent class. See the Component class for details. See the AWTEvent class for details on how to
filter or handle events.
MEMBER SUMMARY .5^.. _ . £
Constructor ChoiceO Constructs a new Choice instance.
Item Methods addO addltemO getltemO getltemCountO insertO remove О ' removeAllO Adds an item to this choice. Adds an item to this choice. Retrieves an item from this choice. Retrieves the number of items in this choice. Inserts an item into this choice. Removes an item from this choice. | Removes all items from this choice.
Selection Methods getSelectedlndex() getSel ectedltemQ getSelectedObj ects О selectO Retrieves the index of this choice's currently selected item. Retrieves this choice's currently selected item. Retrieves this choice’s currently selected item. Selects an item in this choice.
Event Methods addltemLi stenerO processEventO processItemEventO removeltemLi stenerO Peer Method addNoti fy() Adds a listener to receive item events fired by this choice. Processes an event enabled for this choice. Processes an item event enabled for this choice. Removes a listener from receiving item events fired hv this choice. Creates the choice’s peer.
Debugging Method paramStri ngO Generates a string representing the choice's state.
Deprecated Method countitems О i । Replaced by getItemCount (). j
252
See Also
java.awt.event.ItemEvent, java.awt.event.ItemLi stener.
Example
For a simple example using the choice compo-
nent, see the example for the ChoiceO construc-
tor. This more elaborate example creates two
choice components for controlling the appearance
of a message that is displayed in the center (see
Figure 62). One choice controls the font name,
and the other controls the font style. You can use
the text field at the bottom to change the text of
the message. The message is painted in the mid-
dle of the frame container. Since frame containers
have insets, the paintO method needs to sub-
net RE 62: Using Choice to Control a
Component.
tract the insets from the frame’s bounds. For containers without insets (such as Panel), this
calculation is not necessary.
import java.awt.-;
import java.awt.event.*;
class Main extends Frame implements ItemListener, ActionListener {
String[] styleNames = {“plain”, “italic”, “bold”, “bold-italic”};
int[] styleValues = {Font.PLAIN, Font.ITALIC, Font.BOLD,
Font.ITALIC|Font.BOLD};
Choice chFont = new ChoiceO;
Choice chStyle = new ChoiceO;
TextField tf = new TextField(“Hello”);
Main() {
super(“Choice Example”);
Panel p = new Panel О;
// Retrieve all the font names.
for (int i=0; i<getToolkit().getFontList().1ength; i++) {
chFont.additem(getToolki t() .getFontLi st()[i]);
}
// Initialize the font style choice.
for (int i=0; i<styleNames.length; i++) {
chStyle.additem(styleNames[i]);
}
p.setLayout(new GridLayout(l, 0));
p.add(chFont);
p.add(chStyle);
// Listen for events on choices
chFont.addltemLi stener(thi s);
chStyle.addltemLi stener(thi s);
// Listen for events on text field
tf.addActi onLi stener(thi s);
Choice
java.awt
add()
add(p, BorderLayout.NORTH);
add(tf, BorderLayout.SOUTH);
setSize(300, 150);
setVi sible(true);
}
public void paint(Graphics g) {
Insets insets = getlnsetsO;
int w = getSize().width-insets.left-insets.right-2;
int h = getSizeQ .height-insets.top-insets.bottom-2;
Font f = new Font(chFont.getSelectedltemC),
stylevalues [chStyl e. getSelectedlndexQ] , 24);
FontMetrics fm = g.getFontMetrics(f);
String str = tf.getTextQ;
g.clearRect(0, 0, w, h);
g.setTont(f);
g.drawString(str, (w-fm.stringWidth(str))/2,
(h-fm.getHeight())/2чfm.getAscent());
}
// Update action for choice components
public void itemStateChanged(ItemEvent e) {
repaint();
}
// Update action for text field
public void actionPerformedCActionEvent e) {
repai nt();
}
static public void main(String[] args) {
new Mai n();
}
add()
purpose Adds an item to this choice.
SYNTAX public synchronized void add(String item)
DESCRIPTION This method adds the item i tern to the end of this choice. If the item is the first one in the list, then the item is selected; otherwise, rhe selected item does not change. This method is the same as additemО.
PAR/XMETERS
i tem The non-nul 1 item.
SLL ALSO addltemO, insertO, removeO, removeAllQ-
EXAMPLE See Choi ce().
254
addltemf
addltemf) _______________
PURPOSE Adds an item to this choice.
SYNTAX public synchronized void addltemfString item)
DESCRIPTION This method adds the item i tem to the end of this choice. If the item is the first one in the list, then the item is selected: otherwise, the selected item does not change. TTiis method is the same as add().
PARAMETERS item The non-nul 1 item.
SEE ALSO addO, insertO, removeQ, removeAllQ-
EXAMPLE See the class example.
addItemListener()
PURPOSE Adds a listener to receive item events fired by this choice.
SYNTAX public synchronized void addTtemListener(ItemListener listener)
DESCRIPTION An item event is fired when an item in this choice is selected. See ItemEvent and the class description for more details. After this method is called, the item listener listener will receive item events fired by this choice. If listener is null, this method does not do anything.
PARAMETERS listener The possibly null item listener to add.
SEE ALSO ItemSelectable, java.awt.event.ItemEvent, java.awt .event. ItemLi stener, removeItemLi stenerO.
example: See the class example. Choicef), and select().
addNotifyf)
PURPOSE Creates the choice's peer.
syntax public void addNotifyO
DESCRIPTION This method creates the peer if it does not yet exist. The peer is created by call ing the Toolkit. createChoiceO method. This method should never be called directly. It is normally called by the parent.
OVERRIDES Component.addNot i f у ().
SEE ALSO Component, Toolkit.
example See Component.setVi si ble().
Choice
Choicet)
java.awt
Choice()
pl rposf Constructs a new Choi ce instance.
syntax public ChoiceO
description This constructor constructs a new visible choice component.
example This example creates a choice component with
two items. The program simply prints out the
current item whenever the current item in the
choice changes. See Figure 63.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ItemListener {
Main() {
super(‘‘Choice Example1');
Choice choice *= new ChoiceO;
choice.add(“Item 1”);
choice.add(“Item 2”);
add(choice, Bordert ayout.CENTER);
// Add listener for choice
choi ce.addltemLi stener(thi s);
set$ize(150, 75);
setVi si ble(true);
}
FIGURE 63: Simple Choice.
public void itemStateChanged(ItemEvent evt) {
// get choice’s selection and display to stdout
ItemSelectable s = evt.getltemSelectableQ;
Object[] selected » s.getSelectedObjectsO;
if (selected null)
System.out.pri ntln(selected[0]);
}
static public void main(String[] args) {
new Main();
}
}
countltems()
purpose Replaced by getItemCount().
syntax public int countltemsQ
returns The number of items in this choice.
DEPRECATED
256
gUUlCHH
DEPRECATION Replace usage of the deprecated method int count - choi се. c ountltemsQ ; with int count - choice .getltemCountO ;
getltemQ
PURPOSE Retrieves an item from this choice.
SYNTAX public String getTtem(int index)
DESCRIPT ION This method retrieves the item at the index index from this choice.
PARAMETERS i ndex The non-negative zero-based index of the item.
RETURNS A non-nul 1 string containing the item s name.
SEE ALSO getltemCountO, getSel ectedltemQ.
EXAMPLE See selectO.
getItemCount()
PURPOSE Retrieves the number of items in this choice.
SYNTAX public int getltemCountO
RETURNS The number of items in this choice.
SEE ALSO getltemQ.
EXAMPLE See selectO.
getSelectedIndex()
PURPOSE Retrieves the index of this choice's selected item.
SYNTAX public int getSelectedlndexO
RETURNS The zero-based index of the selected item; -1 if this choice has no items.
SEE Al.SO getSelectedltemQ.
EXAMPLE See the class example.
Choice
geiSelectedltenit)
java.awt
getSelectedltemC)
PERPOSE Retrieves this choice's currently selected item.
SYNTAX public synchronized String getSelectedltemQ
REIl’RNS The selected item: null if this choice has no items.
SEE ALSO getSelectedlndexQ .
EXAMPLE. See the class example.
getSelectedObjects()
purpose Retrieves this choice's current!} selected item.
syntax public synchronized Objectf] getSelectedObjects()
returns An array with one item containing this choice's currently selected item; null
if this choice has no items.
see м so getSelectedlndexQ , getSe 1 ectedltemQ , TtemSelectable.
ex ample See Choice О.
insert()
perpose Inserts an item into this choice.
syntax public synchronized void insertfString item, int index)
descri Ftion This method inserts the item item at the index index of this choice. Existing
items at an index greater than or equal to index are shifted up by one to
accommodate the new item. If i ndex is greater than or equal to the number of
items in this choice, i tem is added to the end of this choice.
If the item is the first one being added to the choice, then the item becomes
selected. Otherw ise, if the selected item was one of the items shifted, the first
item in lhe choice becomes the selected item. If the selected item was not
among those shifted, it remains the selected item.
PARAMETERS
i ndex The position at which to insert lhe new item.
item The non-null item.
exceptions
Il legalArgumentException
If index is negative.
258
SEEALSO add()t addltem(), getTtemCount(), remove() , removeAl1().
example See remove О.
paramString()
PURPOSE Generates a string representing the choice's state.
SYNTAX protected String paramString()
DESCRIPTION This method returns the string representation of this choice’s state; the returned string includes the selected item. A subclass of this class should override this method and return a concatenation of its state with the results of super.paramString(). This method is called by the toStringO method and is typically used for debugging.
RETURNS A non-nul 1 string representing the choice's state.
OVERRIDE'S Component.paramStri ng().
SEE ALSO Component.toStri ng О, java.1ang.Object.toString().
EXAMPLE See Component.paramString().
processEventO
purpose: Processes an event enabled for this choice.
SYNTAX protected void processEvent(AWTEvent evt)
DESCRIPTION This method extends Component. processEvent() by adding support for ItemEvent. When a subclass does override processEventO. it should call super .processventO to perform the processing intended by its base class (such as dispatching the listeners).
parameters evt The event to be processed.
OVERRIDES Component.processEvent 0
SEE A I.SO AWTEvent, processItemEvent().
example: See Component's class example.
Choice java.awt
processItemEvenK)
processItemEvent()
PURPOSE Processes an item event enabled for this choice.
SV VI AX protected void processItemEventfltemEvent evt)
DESCRIPTION An item event is fired when an item in this choice is selected. See ItemEvent and class description for more details. This method processes item events for this choice by calling any registered ItemListener. This method is invoked only if item events have been enabled for this choice. This can happen cither when an item listener is added to this choice or if item events are enabled explicitly via Component.enableEvents(). Typically, a program controls how item events for a choice are processed. This is done by adding or removing item listeners. It overrides processitem EventO only if it needs to do processing in addition to that performed by the registered listeners. When a subclass does override processItemEventQ. it should call super .processItemEventO to perform the processing intended by its base class (such as dispatching the listeners).
PARAMl-.TI-RS
evt The event to be processed.
SEE ALSO java.awt.event.ItemEvent, ItemSelectable, java.awt.event.ItemListener, processEventO.
LX AMPLE. See ItemSel ectable's class example.
removc()
PURPOSE Removes an item from this choice.
SYNTAX public synchronized void remove(String item) public synchronized void remove(int index)
DESCRIPTION This method removes an item from this choice. The item can be identified either by its index i ndex in the choice or by its name i tem. If several matches exist for item, the item with the smallest index is removed. If the item being removed is the currently selected item, then the first item in the choice becomes the selected item. Otherwise, the currently selected item remains selected (and the selected index is updated accordingly).
PARAMETERS i ndex item The position from which to remove the item. I’he non-nul1 item to remove.
260
EXCEPTION >
Il legalArgumentException
If i ndex is negatixe or il i tern is not in this choice.
SEE ALSO
example
add(), addltemO, getltemCountO, insert(), removeAl1().
This example creates
a choice and a row of
buttons that controls
lhe insertion and
removal of items
from the choice. See
Figure 64.
import java.awt. , HGIRE64: Inserting and Removing Items from a
import java, awt. event . ;
Choice.
class Main extends Frame
implements ActionListener {
Choice choice = new ChoiceO;
Button removeBtn = new Button (“Remove”);
Button removeAUBtn = new Button(“RemoveAll ”) ;
Button addBtn = new Button(“Insert”);
int 1astltemCount = 0;
Main() {
super(“remove Example”);
// Initialize the choice with 10 items.
for (int i=0; i<10; i++) {
choi ce . addltemC'i tern “+C1 astItemCount++));
}
// Listen for events.
removeBtn.addActionLi stener(thi s);
addBtn.addActi onListener(this);
removeAl1Btn.addActi onListener(this);
Panel p = new Panelfnew GridLayout (T, 0));
p.add(removeBtn);
p.add(removeAl1Btn):
p.add(addBtn);
add(choice, BorderLayout.CENTER);
add(p, BorderLayout.NORTH);
setSi zef300, 150j;
show О ;
}
public void act i onPerf ornied (Ac t i onEveri l e; {
String cmd = e.getActionCommand(j ;
if Гcmd.equaIs(“RemoveAl1”)) {
choi ce.removeAlIf);
Choice
reinoveAIlt )
java.awt
} else {
int target - choice.getSelectedlndex();
if (end.equals(“Remove")) {
if (target >= 0) {
choi ce.remove(target);
}
// else add
} else {
if (target >= 0) {
choice.insert(“item “♦(1astltemCount++), target);
choi ce.seiect(target);
} else {
choice.add(“item “+(lastItemCount++));
}
}
}
removeBtn.setEnabled(choice.getltemCount() > 0);
removeAlIBtn.setEnabled(choice.getltemCountO > 0);
1
static public void main(String[J args) {
new Main();
)
}
removeAlK)
perpose Removes all items from this choice.
svniax public synchronized void removeAll()
see .also add(), addltem(), getltemCountO, InsertO, removeC).
fxample: See remove().
removeItemListener()
PE RPC )SF Removes an item listener from receiving item events from this choice.
S^ VI AX public synchronized void removeltemListener(ItemListener listener)
DESCRIP IK>\ An item event is tired when an item in this choice is selected. Sec Itemtvent and the class description for more details. After this method is called, the item listener listener will no longer receive item events from this choice. If lis- tener is null, this method does nothing.
PARAMETERS 1i stener The possibly null item listener to remove.
SEE ALSO addltemListener(), ItemSelectable, java.awt.event.ItemEvent, java.awt.event.Itemt i stener.
EX А МНЕ See removeActionLi stener() in MenuItem.disableEventsO.
262
selecK i
select()
purpose Selects an item in this choice.
SYNTAX
public synchronized void selectfint index)
public synchronized void select(String string)
DESCRIPTION
This method selects an item either by its
name or by its index. If i ndex is specified,
the item al index index is selected. If
string is specified, the item's name is
string. If several matches exist, the item
with the smallest index is selected. If
string does not match any item(s). then
the method call is ignored.
p| select Example BEE3
FIGI RE 65: Toggle to Choice.
PARAMETERS.
i ndex
stri ng
SEE AESO
EXAMPLE
The non-negative /его-based index of the
item.
The non-nul 1 item to select.
getSelectedlndexO ,
getSelectedltemQ .
This example creates a frame with a but-
ton and initially with a choice component
(see Figure 65). Clicking the button
causes the choice component to be
replaced by a list component (see Figure
66). Clicking the button again causes
the list to revert to a choice component
(see Figure 65). The program uses
selectO to maintain the selected item
betw ееn tran sformat i оn s.
select Example ЯВЕ
Toggle
itemO
item 1
item 2
item3
item 4
item 5
item 6
item?
item 8
item 9
FIGURE 66: Toggle to List.
import java.awt.'";
import java. awt. event . ;
class Main extends Frame implements ActionListener, ItemListener {
List list;
Choice choice = new ChoiceO;
Button toggle = new Button(“Toggle”);
Main О {
super(“seiect Example”;;
for fint i=0; i<10; i--j <
choi ce . addItemC i tern “ + i) ;
Choice
select! )
java.awt
// Set 1isteners
choice.addItem! istener(this) :
toggle.addAct ionListener(this);
add(choice, BorderLayout.SOUTH);
add(toggle, Borderl ayout.NORTH);
packQ;
show(true);
1
// When button is pushed
public void actionPerformed(ActionEvent evt) {
if (choice 1- null) {
// Create a list and transfer items to the list,
list = new Li st(choi ce. getltemCountO , false);
for (int i-0; i<choice.getItemCountО; i <--) {
list.addItern(choi ce.get Item(i));
if (i -- choice.getSelectedlndexQ) {
1ist . select(i);
}
}
// Add list
list.add ItemListener(this);
add(list, BorderLayout.CENTfR);
// Remove choice
remove(choi ce);
choice = nul1:
} else {
// Create a choice and transfer items to the 1isi
choice = new ChoiceO;
for (int 1=0; i< 1 i st.getltemCountO ; i+ + ) {
choice.additem(1i st.getltem(i));
if (i — 1ist.getSelectedlndex()) {
choi ce.seiect( i);
}
}
// Add choice
choice.addltemL istener(this);
add(choice, BorderLayout.SOUTH);
// Remove list
remove(1i st);
list = nul1;
}
pack();
}
// When list or choice is updated
public void itemStateChanged(ItemEvent evt) {
repaintQ ;
}
static public void main(String[] args) {
new Mai n();
J
}
264
ChoicePeer
Syntax
public interface ChoicePeer extends Componentpeer
Description
The choice component (see the Choice class) in the AWT uses the platform \s native imple-
mentation of a choice component. So that the AWT choice component behaves the same on all
platforms, the choice component is assigned a peer, whose task is to translate the behavior of
the platform’s native choice component to the behavior of the AWT choice component.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to its
java.awt counterparts.
See Component and Tool kit for additional information about component peers.
Choice Peer
java.awt. peer
add()
MEMBER SUMMARY !
Peer Methods add() Adds an item to the choice.
A removeO Removes an item from the choice.
Г» select() Select5 an item in the choice. ।
В D I Deprecated Method I addltemO Replaced by add О •
See Also
java.awt.Choi ce, java.awt.Component , java.awt.Toolki t.
add()
J К PIRPC >SF. Adds an item to the choice.
L SY\ 1 AX void add(String item, int index)
M DI.SCRIPTION This method adds the item item to the choice list al index.
N PARAMlTl.RS
О i ndex The position in the choice list at which to place item.
P i tem The non-nul 1 item to be added.
Q SIT ALSO java.awt .Choice. addQ
R
S addltemO
T Pl RPOSL Replaced b> add().
u SYNTAX void addItem(String item, int index)
V PAR AMI 'll RS
w v i ndex The position in the choice list at which to place item.
item I he non-nul 1 item to be added.
Л DEPRECATION Replace usage of this deprecated method, as in
Y peer.addltem(item, index);
Z with
peer.add(item, index);
the index specified b\
DEPRECATED
266
removc() — —
PURPOSE Removes an item from the choice.
SYNTAX void removefint index)
DESCRIPTION This method removes the item al the index specified b\ index from the choice.
PARAMETERS index The item s position in the choice.
SEE ALSO java. awt. Choice. removeO.
selectO
PURPOSE Selects an item in the choice.
SYNTAX void select(int index)
DESCRIPTION This method selects the item at lhe index indicated by index.
PARAMETERS index The non-negative zero-based index of the item.
SEE ALSO java.awt .Choice, se lectQ.
j a v a. a w t. d atat ran s t'e r
Clipboard
Syntax
public class Clipboard
E
Description
A clipboard is an object that temporarily holds data as it is being transferred between or within
G an application. It is typically used in cut/copy/paste operations. An application can create as
H many clipboard objects as it wants, but these clipboard objects can be used only within that
one application. That is, the clipboard cannot be shared between different applications. How-
1 ever, there is one special clipboard that is created and maintained by the AWT system that can
J be shared between applications. In fact, the system clipboard is shared by all applications run-
K ning on the system, Java or otherwise. This clipboard is called the system clipboard. Most
applications typically use the system clipboard rather than create and manage their own.
I Note: In Java 1.1.2, the system clipboard can hold only string selections (see StringSe-
M lection)
A clipboard does not hold data directly. Instead, the data must be encapsulated in a trans-
ferable object before it can be placed on the clipboard. See the Transferable interface for
<) more details.
p At present, there is no facility for registering a clipboard so that other objects can use it.
The creator of a clipboard must supply a reference to the clipboard to all objects wishing to
Q exchange data via that clipboard. You can retrieve a handle to the system clipboard by calling
r Toolki t.getSystemCli pboard().
The Clipboard Name
T The clipboard name is an arbitrary string associated with the clipboard object at the time the
clipboard object is created. The name cannot be changed. At present, the name is not signifi-
cant other than for debugging purposes.
V
w The Clipboard Owner
A clipboard can have an owner. The owner is the last object to place contents on the clipboard,
x The owner of the clipboard is notified when some other object places contents on the clip-
Y board.
An object need nor take ownership of the clipboard when placing contents on the clip-
board.
268
[BER SUMMARY
Constructor ClipboardO Constructs a Cl i pboard instance.
Content Methods getContentsO Retrieves lhe contents of this clipboard.
setContentsO Places a transferable object in this clipboard.
Name Method getNameO Retrieves the clipboard name of this clipboard
Fields contents Contains the contents of this clipboard.
owner Contains the current clipboard owner.
See Also
Transferable.
Example
This example is a program that can be used to
view the contents of the system clipboard in a
text area. The example can view only strings
objects. If the clipboard is empty or contains
something other than a string, the text area
becomes red and displays an error message. See
Figure 67.
Clipboard Example
This is some veiv Iona messaa Л
on the clipboard Clip this |
import java.awt.*;
import java.io.*:
import java.awt .datat ransfer_ ;
import java.awt.event;
ГИД RE Ъ7: Viewing Clipboard
Contents.
class Main extends Frame implements
ActionListener, ClipboardOwner {
TextArea textArea = new fextAreaO;
Main О {
super("Clipboard example");
MenuBar mb = new MenuBarQ:
Menu m = new venu(”Fdit”);
// Add text area.
setLayout(new BorderLayoutO);
addC'Center", textArea);
// Prepare menu and menubar.
Clipboard
jav a.awi.datatransler
m.addC'Cut");
m.addC'Copy") ;
m.add("Paste") ;
mb.add(m);
setMenuBar(mb) ;
// Listen to events from the menu items.
for (int i=0; i<m.getltemCountQ ; i+*) {
m.getltemfi).addActionl istener(this);
}
setSize(300, 3003;
showQ ;
}
public void actionPerformed(ActionEvent evt) {
if ("Paste".equals(evt.getActionCommandQ)) {
boolean error = true;
Transferable t
get Tool ki t () .getSystemCl i pboardQ • getContents(thi s);
try {
if (t ; = null
&& t.i sDatarlavorSupported(DataFlavor. stringFlavor))
textArea.setBackground(Col or.white);
textArea.setForeground(Col or.black);
textArea.replaceRange(
(String)t.get!ransferData(DataFlavor.stringflavor),
textArea.getSelectionStartO,
textArea.getSelectionEnd());
error = false;
}
} catch (UnsupportedFlavorException e) {
} catch (lOException e) {
}
// Display an error message.
if (error) {
textArea.setBackground(Col or.red);
textArea,setForeground(Color.white);
textArea.repai nt();
textArea.setText("ERROR: \nEither the clipboard"
+ 11 is empty or the contents is not a string.");
}
} else if ("Copy" .equals(evt.getActionCommandQ)) {
setContentsQ;
} else if ("Cut" .equals(evt.getActionCommandQ)) {
setContentsQ ;
textArea.replaceRangeC’", textArea.getSelectionStart(),
textArea.getSelectionEndQ) ;
}
}
void setContentsQ {
String s = textArea.getSelectedTextQ;
Stringselection contents = new StringSelection(s);
qetTool ki t() .getSystemCl i pboardQ .setContents(contents, this);
}
public void lostOwnership(Clipboard clipboard, Transferable contents) {
270
C hphoardt)
System.out.priniln("lost ownership") ;
}
public static void main(String argsfl) {
new MainO:
1
}
ClipboardO
PURPOSE Constructs a Cl i pboard instance.
SYNTAX public Clipboard(String name)
DESCRIPTION This constructor creates a new clipboard object with the name name. The name is an arbitrary string associated with the clipboard object and cannot be changed. At present, the name is not significant other than for debugging pur poses.
PARAMEIERS name /X possibly null string.
example: See the Transferable class example.
contents
PURPOSE Field containing the current clipboard contents.
SYNTAX protected Transferable contents
DESCRIPTION This field may be null; this means the clipboard is empty. Note that it is pos- sible for the clipboard to be empty and owned.
getContentsQ
purpose: Retrieves the contents of this clipboard.
syntax public synchronized Transferable getContents(Object requester)
description This method does not return the actual data on the clipboard. Rather it returns a Transferable object, which can then be used to retrieve the actual data. See Transferable for details. If the clipboard is empty, null is returned. Note: In Java 1.1.2, this method returns null if the clipboard is holding an object that is not a string selection (see StringSelection). This may evenlu-
Clipboard
gctContents(}
ja\a.aw’t.datatranster
ally change to return a non-null transferable object that returns a zero-length
array when getTransferDataFl avorsQ is called on it.
parameters
requester This parameter is currently ignored.
reti res A possibly null Transferable object.
see ai so Transferab1e.getTransferDataFlavors О.
example-.
1 пгййшт oo ]
OKSh English Chinese Dictionary
English: tdCTI jHaRY
Size: r t2^ Л I Uah » I
, getContents|| Ex ВИяТВ
\u5b57\u5178
Copy
Paste
FIGI RE 68; Big5 to Unicode (’on vert er.
This example converts Big5-encoded characters to Unicode. The program
reads the contents of the system clipboard and converts it into a Java siring of
Unicode characters that are suitable for inserting into a resource bundle (see
java.util.ResourceBundle)or a Java program.
Figure 68 shows a browser displaying an on-line Fnglish-to-Chinesc dictio-
nary. The dictionary generates Big5-encoded characters, and the browser is set
to display Big5 encoded characters. In the figure, two Chinese characters have
been selected. When these characters are copied into the system clipboard,
they can be pasted into lhe example program by clicking in the area above the
text field. When this is done, the text field shows the Java Unicode string of the
two Big5-encoded characters.
When Big5-encoded characters are copied from the system clipboard, they are
retrieved as a string of bytes. In other words, each character in the resulting
siring is actually a byte value. These byte values are copied into a byte array
and passed to a sun.io.ByteToCharConverter object for conversion.
Although the sun.io.ByteToCharConverter class is not yet part of lhe core
set of classes, it is part of the runtime and available for use. Just be aware that
272
this class may be moved io another package at some point. See the Internation-
al izution Specification document at the java.sun.com Web site for informa-
tion on supported converter classes. This document also describes how to
install Big5 fonts on your system.
import java.awt."';
import java.io.*;
import java.awt.datatransfer.*;
import java. awt. event. ;
class Main extends Frame {
TextField textField - new TextFieldO;
TextDisplay textDisplay - new TextDisplay(textField);
MainO {
super(“getContentsО Example”);
// Layout component.
add(textDisplay, BorderLayout.CENTER);
add(textField, BorderLayout.SOUTH);
setSize(300, 100);
show();
1
public static void main(String arqs[^) {
new Mai n();
}
}
class TextDisplay extends Canvas {
String text = ;
TextField textField;
Font f = new Font(“Monospaced”, Font.BOLD, 24);
TextDisplay(TextField textField) {
this.textField = textField;
setFont(new Font(“Monospaced”, Font.BOLD, 24));
// Listen for events.
addMouseListener(new MouseEventHandler());
}
public void paint(Graphics g) {
FontMetrics fm = getFontMetrics(f);
// Draw the character centered in the canvas area.
g.setFont(f);
g.drawString(text, (getSize() .width-frr. stringWidth(text))/2 ,
(getSi ze(). hei ght-fm.getHei ght ())/?4fm. getAscentO);
class MouseEventHandler extends MouseAdapter {
public void mousePressed(vouseEvent evt) {
Transferable t =
get Foolki t().getSystemCli pboard().get€ontents(thi s);
try {
Clipboard
getName()
ja\ a.au t.dalalransfer
if (t != null
&& t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
text -
(St ring)t .getTransferData(DataFlavor. stringFlavor! ;
// Generate the unicode string for ‘text’.
String result -
byte big5[] - new byte[ text. 1 engthO 1;
char unicodel"; - new char [text. length()/2J;
for (int i--0; i<text.lengthQ ; i*-O {
bigS[iJ = (byte)text.charAt(i):
}
// Create the converter object.
sun.io.ByteToCharConverter toUnicodeConv
- sun.io.ByteToCharConverter.getConverter(“Bi gS”);
// Convert the big5 array to unicode.
int len - toUnicodeConv.convert(big5, 0, big5.length,
unicode, 0, uni code.length);
// Display the lava unicode characters
// field in the text,
for (int i-0; iclen; i+-<-) {
String s;
result *- “\\u";
s = “0000” * Integer.toHexString(unicode[i]);
result ♦- s. substri ng(s. 1 engthO-4) ;
}
text = new String(unicode):
// Set it in the text field,
textГ i eld,setText(result);
repai nt();
}
} catch (UnsupportedFlavorException e) {
e.pri ntStack!race();
} catch (lOException e) {
e.pri ntStackT race();
}
}
}
V
w
getNameO
pirposf Retrieves the clipboard name of this clipboard.
public String getNameO
description The name is an arbitrary string associated with the clipboard object. Al
present, the name has no significance other than for debugging purposes.
rfttrns A possibl} nul 1 string containing the clipboard's name.
274
О1
owner____________
PURPOSE Field containing the current clipboard owner.
SYNTAX protected Clipboardowner owner
description This field may be null. This means the clipboard does not have an owner. In this case, the clipboard may still have contents.
setContentsO
PURPOSE Places a transferable object in this clipboard.
SYNTAX public synchronized void setContents(Transferable contents, Clipboardowner owner)
DESCRIPTION This method sets contents to be the new contents of the clipboard and regis- ters owner as the new clipboard owner. If contents is null, the clipboard is cleared of all contents. The owner parameter may be nul 1. This indicates that the object placing con- tents on the clipboard does not want to be notified when the content changes. If owner differs from the previous clipboard owner, the previous clipboard owner is notified that it has lost ownership of the clipboard (see Clipboard- Owner. lostOwnershipO). Note: In Java 1.1.2, the system clipboard can hold only string selections (see Stringselection). All other transferable objects are ignored.
PARAMEI ERS contents owner A possibly null transferable object to place on the clipboard. The possibly null owner of contents.
SEE ALSO Stri ngSelecti on.
example See the class example.
java.awt.datatransfer
ClipboardOwner
(^ClipboardOwner ' 1 '*’ **' * ‘ 'I
A
Syntax
public interface ClipboardOwner
D
Description
When an object seis some data in the clipboard, the object can be notified when the data is no
b longer in the clipboard. Such an object must implement the ClipboardOwner interface and
G then supply a reference to itself when calling Clipboard. setContentsQ. After doing so.
the object becomes the owner of the clipboard. When the object loses ownership of the clip-
H board, its lostOwnership() method is called.
I One use for this capability is to allow an object to dispose of resources used by the clip
j board contents, since it is no longer being used.
К.......................................................................................
( MEMBER SUMMARY
M Lost Ownership Callback Method
1 ostOwnershi pO Called when an object loses ou nership of the clipboard.
N ___ __________________________________________________________________ — ---
()
See Also
Cl i pboard. setContentsQ.
R
s Example
T This example sets a string selection in the system clipboard and makes itself the clipboard
owner. When the string selection is replaced by some other application, the program prints a
1 message and terminates.
V
import java.awt.-;
W import java. awt. datatransfer ;
X class Main implements ClipboardOwner {
//ClipboardOwner Example
Y Main О {
// Retrieve handle to clipboard and contents
Z Clipboard clipboard -
Toolkit.getDefaultToolkitO.getSystemClipboardО;
clipboard.setContents(new Stri ngSelect i onQHel lo”), this);
276
lUMWWncrsnipU
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out. printing’lost ownership”) ;
System.exit(0);
}
public static void main(String[] args) {
new Main();
lostOwnershipO
PURPOSE Called when an object loses ownership of the clipboard.
SYNTAX public void lostOwnership(Clipboard clipboard, Transferable contents)
DESCRIPTION The contents parameter should he equal to (the same reference as) the trans- ferable that this object placed on the clipboard using Cl ipboard.set- Contentsf). This method is not called if the current owner of the clipboard changes the clipboard contents.
PARAMETERS cli pboard contents The non-nul 1 handle to a clipboard. The non-null old contents of the clipboard.
EXAMPLE See the class example.
java.awt
Color
A
В
D
i:
F
G
El
I
J
К
L
M
N
О
P
Q
R
S
T
t;
v
w
X
Y
Z
Syntax
public class Color implements java.io.Serializable
Description
A Color instance specifies a color that is used in graphics operations. Colors are also used
when setting the background and foreground colors of components. The actual color displayed
by the system may not exactly match the desired color because of limitations in the rendering
device. In this case, the closest matching color is used.
A color can he specified using either the RGB {red, green, blue) or HSB (hue, saturation,
brightness} color coding system. In the ROB system, the three color components are x allies in
the range 0-255; the higher the value, the brighter the component. An RGB value of (0. 0, 0) is
black and an RGB value of (255, 2 55. 255) is white. In the USB system, the three color com-
ponents are values between 0.0 and 1,0. An HSB value of (0.0. 0.0. 0.0) is black and an
HSB value of (0.0, 0.0. 1.0) is white.
MEMBER SUMMARY
Constructor
ColorO Constructs a new' Color instance.
Predefined Color Constants
bl ack The color black (0. 0. 0).
blue The color blue (0, 0, 255).
cyan The color cyan (0, 255. 2 55).
darkGray The color dark gray (64, 64. 64).
gray The color gray (128.128.128).
green The color green (0. 255. 0).
lightGray The color light gray (192. 192. 192).
magenta The color magenta (255. 0. 2 55).
orange The color orange (255. 200. 0).
pink The color pink (255. 175, 175).
red The color red (255, 0, 0).
white The color white (255, 255. 255).
yellow The color yellow (25 5. 255, 0).
278
MEMBER SUMMARY
Color Converters
brighterf) Calculates a brighter version of the color.
darkerO Calculates a darker version of lhe color.
Color Component Methods
getBlue() Retrieves the blue component of the color.
getGreenO Retrieves the green component of (he color.
getRedO Retrieves the red component of the color.
getRGBO Retrieves the 24-bit RGB representation of the color.
HSB Methods getHSBColorO Creates a new Color instance from an HSB specification.
HSBtoRGBQ Converts an HSB color specification to a 24-bit RGB color
specification.
RGBtoHSBO Converts an RGB color specification to an HSB color specification.
Other Color Creation Methods
decodeO (’reales a color using a numeric siring that represent ils RGB value.
getColorO Creates a color whose RGB value is specified in a svsiem propertv.
Debugging Method toStri ng() Generates a siring representation of the color.
General Methods equals() Determines if an object is equal to lhe color.
hashCodeO Calculates lhe hash code for the color.
See Also
SystemCol or.
Example
This example creates two sets of scrollbars that
are used to pick a color (see Figure 69). One set is
based on RGB values and lhe other on HSB val-
ues. Changing a scrollbar in one set modifies the
scrollbars in the other. An uneditable text field is
located at the bottom of the frame and shows the
current color in both the RGB and HSB color cod-
ing systems.
j RGB(183,0,183 I #b?00b7) HSB(0.33-£
IK.I Rl. 69: Pick a Color.
.1
Color
java,awt
Since the HSB values are in the range 0.0 1.0 and scrollbars handle only integer values,
you must multiply the HSB values by 1,000 to get an integer value, Hence, a scrollbar repre-
senting an HSB component uses the range 0-1000.
The scrollbar sets the value 0 at the top of the scrollbar. However, since it is more intuitive
to have the value 0 appear at the bottom of the scrollbar, the direction of the scrollbar is
“reversed." Reversing the direction of the scrollbar involves subtracting the value of the scroll-
bar from the maximum value. The sizes of the scrollbars are larger than the range of the RGB
and HSB values in order to account for the scrollbars’ “visible size” (see Scroll bar).
A gridbag layout (see GridBagLayout) is used to lay out a set of scrollbars. The first row
is a row of labels and the second a row of scrollbars. The weight is given to the second row so
that if the window is enlarged, then the scrollbars, rather than the labels, stretch.
import java.awt.*;
import java.awt.event;
class Main extends Frame implements Adjustment!-! stener {
int r = 255;
int g = 255;
int b - 255;
Scrollbar sbRed = new Scrollbar(Scrol1 bar.VERTICAL, 0, 1, 1, 257);
Scrollbar sbGreen = new Scrol1bar(Scrol1 bar.VERTICAL, 0, 1, 1» 257);
Scrollbar sbBlue - new Scrol1 bar(Scrol1 bar.VERTICAL. 0, 1, 1, 257);
Scrollbar sbH = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1. 1002);
Scrollbar sbS = new Scrol1 bar(Scrol1 bar.VERTICAL, 0, 1, 1, 1002);
Scrollbar sbB = new Scrollbar(ScrolIbar.VERTICAL, 0, 1, 1, 1002);
TextField status - new TextFieldO;
floatr] hsb;
Main() {
super(“Color Example’);
sbRed.addAdjustmentLi stener(thi s);
sbGreen.addAdjustmentListener(thi s);
sbBlue.addAdjustmentListener(this);
sbH.addAdjustmentLi stener(this);
sbS.addAdjustmentLi stener(thi s);
sbB.addAdjustmentLi stener(thi s);
add(makeScrol1bars(“R". sbRed, V, sbGreen, '‘B", sbBlue),
BorderLayout.WEST);
add(makeScrollbars("H”, sbH, “S", sbS, "B”, sbB), BorderLayout.EAST);
status.setEdi table(false);
add(status, BorderLayout.SOUTH);
setSize(300, 300);
showO;
setBackground(adjustHSBScrollbarsO);
adjustRGBScrollbarsO;
}
Panel makeScrol1bars(String 11, Scrollbar sbl,
String 12, Scrollbar sb2, String 13, Scrollbar sb3) {
double[] rowWeights - {0.0, 1.0};
GridBagLayout gbl - new GridBagLayout();
Panel p - new Panel(gbl);
gbl.rowWeights - rowWeights;
280
p.setLayout(gbl);
add(p. gbl, new Label(11, Label.CENTER),
0, 0, GridBagConstraints.NONE);
add(p, gbl, sbl, 0, 1, GridBagConstraints.VERTICAL);
add(p, gbl, new label(12, Label.CENTER),
1, 0, GridBagConstraints.NONE);
add(p, gbl, sb2, 1, 1, GridBagConstraints.VERTICAL);
add(p, gbl, new Label(13, Label.CENTER),
2, 0, GridBagConstraints.NONE);
add(p, gbl, sb3, 2, 1, GridBagConstraints.VERTICAL);
return p;
void add(Pane) p, GridBagLayout gbl, Component comp, int x, int y, int fill)
GridBagConstraints gbc = new GridBagConstraintsO;
gbc.gridx = x;
gbc.gridy = y;
gbc .fill fill;
gbl.setConstraints(comp, gbc);
p.add(comp);
public void adjustmentValueChanged(AdjustmentEvent evt) {
Color c - getBackgroundQ ;
Object src = evt .getSourceQ;
// Value from scroll bar is one greater than actual RGB or HSB value
if (src -= sbRed) {
r = 255-(sbRed.getValue()-I);
c = adjustHSBScrol IbarsQ ;
} else if (src =- sbGreen) {
g = 255-(sbGreen.getValueQ-1);
c = adjustHSBScrollbarsQ;
} else if (src -= sbBlue) {
b = 255-(sbBlue.getValueQ 1);
c = adjustHSBScrollbarsQ ;
} else if (src === sbH) {
hsb[0] = (1000 (sbH.getValueQ-1)) / 1000.0f;
c - adjustRGBScrollbarsQ;
} else if (src sbS) {
hsb[lj = (1000-(sbS.getValueQ-1)) / 1000.0f;
c = adjustRGBScrollbarsQ;
} else if (src == sbB) {
hsb[2] = (1000-(sbB.getValueQ-1)) / 1000.Of;
c = adjustRGBScrollbarsQ;
}
setBackground(c);
repaint();
status.setTextQ'RGBC' *-r+" , "^g+’Y^bf’1 / 11 ♦
“^'-►Integer. toString(c .getRGBQ&Oxffffff, 16)+”)”+
“ HSB(“*hsb[01 ,’'+hsbri] *”,'’+hsb[2Q")”);
Color adjustHSBScrolIbarsO {
hsb = Color.RGBtoHSB(r, g, b, null):
// need to offset values by 1 to account for ‘visible’ part
// of sc roll bar
sbH.setValue(1001-(int)(hsb[0] * 1000));
Color
black
ja\ a.aw t
A
В
Г)
F
F
G
II
I
.1
К
L
M
N
()
P
Q
R
s
T
г
V'
sbS.setValue(1001-(int)(hsb[l] 1000));
sbB.setValue(1001-(int)(hsb[21 " 1000));
return new Color(r, g, b);
}
Color adjustRGBScrol1 bars() {
Color c - Col or.getHSBColor(hsb[0], hsb[l], hsb{2]);
// An alternate way of converting the HSB values to RGB:
// Color c = new Col or (Color. HSBtoRGB(hsbfO]. hsbfl] . hsb[2_])) :
// need to offset values by 1 to account for ‘visible’ part
// of scroll bar
sbRed.setValue(256-(r = c.getRed()));
sbGreen.setValue(256-(g - c.getGreenO));
sbBlue.setValue(256-(b = c.getBlue()));
return c;
}
public static void main(String И args) {
new MainO;
}
}
black
Pl RI4ISI
'This constant field holds the color black
(0. 0. 0).
s>\i\\ public final static Color black
I \ win I
This example paints dots at random posi-
tions on the screen using random colors
taken from lhe predefined palette of col-
ors. It also demonstrates the use of a
thread to continually paint a dot even 16
ms. See Figure 70.
FIGI Rl 70: Predefined Colors.
import java.awt.-’;
class Main extends Frame implements Runnable {
Color[] colors - {Col or.bl ack, Color.blue. Color.cyan,
Col or.darkGray, Color.gray, Color.green, Co 1 or.1ightGray,
Col or.magenta, Col or.orange, Color.pink. Color.red,
Color.white, Co 1 or.yel1ow};
Main() {
super(“Color Example’’);
setSi ze(200, 200);
show О ;
(new Thread(this)).start();
}
282
DIUC
int random(int r) {
return (int)vath.floorf^ath.random() v r);
}
public void update(Graphics g) {
g.setColor(colors Г random(colors.length)');
g.fillOval (random(getSize() .width), randorr(getSize() .height) , 10, 10);
}
public void run() {
while (true) {
repaintO ;
try {
Thread.sleep(16);
} catch (Exception e) {
}
}
public static void main(String[J args) {
new Main();
}
}
blue
PURPOSE This constant field holds the color blue (0, 0. 255).
SYNTAX public final static Color blue
example See black.
brighterf)
PURPOSE Calculates a brighter version of the color.
SYNTAX public Color brighterO
RETURNS A new non-nul 1 color instance containing a brighter version of the color.
example See getColorQ.
Color()
PURPOSE Constructs a new Color instance.
syntax public Color(int red, int green, int blue) public Color(float redf-, float greenF, float blueF) public Color(int rgb)
Color
Colon )
java.aw I
description This constructor creates a new Color with the specified RGB valuer The
RGB values can be specified in three ways. The first is with three integers in
the range 0 2 55. If an integer is larger than 25 5. only the lower S bits are used.
The second way is with three floats in the range 0.0-1.0. These floating
point numbers are converted into integers in the range 0-2 5 5.
The third way is with a 24-bit integer. See getRGBQ for information about
how the values are encoded. If the integer is larger than 24 bits. onlv the lower
24 bits are used.
PARAMETERS
blue The blue component of the color. 'Phis value must be in the range 0 2 55.
blueF The blue component of the color. This value must be in the range 0.0-1.0.
green The green component of the color. 'This value must be in the range 0 255
greenF The green component of the color. This value must be in the range 0.0-1.0.
red The red component of the color. This value must be in the range 0 255.
redF The red component of the color. This value must be in the range 0.0 1.0.
rgb The RGB value encoded as 24 bits. See getRGBQ for details about the encod-
ing.
EXCEPTIONS
Il legal ArgumentExcept!on
If any of the values supplied to the constructor is invalid.
EXAMPLE
This simple example creates a frame and draw s
a yellow oval in the middle of the frame. See
Figure 71.
Color Ex... HO"!E3
import java.awt.’';
class Main extends Frame {
Main() {
super("Cclor Example”);
setSize(100, 100);
show();
FIGI RE 71: A simple use of
Col or.
public void paint(Graphics g) {
Insets insets = getlnsetsO;
int x = insets.left, у = insets.top;
int w = getSize().width - insets.left -
int h = getSize().height - insets.top -
insets.right;
insets.hot tom;
g.setColorfnew Color(255, 255, 0));
g.fi1lOval(x+w/4, y+h/4, w/2, h/2);
public static void mai n(St ri ng[] args) {
new Mai n();
}
284
uvan
cyan_________________________________________ ___ _ ______ _ _______ ___
PURPOSE This constant field holds the color cyan (0, 255. 255).
SYNTAX public final static Color cyan
example See black.
I
darkerQ ___ ____ _____ _
purpose Calculates a darker version of the color.
syntax public Color darkerO
returns A new non-nul 1 Col or instance containing a darker version of the color.
example See get Color().
darkGray
PURPOSE This constant field holds the color dark gray (64, 64, 64).
syntax public final static Color darkGray
example See bl ack.
decodeO
purpose Creates a color using a numeric string representing its RGB value.
syntax public static Color decode(String numstr) Number! ormatException
description This method creates a new instance of Color represented by the 24-bit RGB
value decoded from the string numstr. numstr is first decoded into an integer,
whose value is then treated as a 24-bit RGB value.
parameters
numstr A string containing the numeric 24-bit RGB value of the color. It can be a dec-
imal, hexadecimal, or octal number. See Integer.decodeO for acceptable
formats.
Returns A new instance of Color represented by the RGB value specified by numstr.
exceptions
NumberFormatException
If numstr cannot be parsed into a valid integer
ja\ a.awt
Color
dccodet)
si.i. \i.so getColor(), Integer.decode ().
C
i\ \mpi.i. 'This example reads in a list of hexa-
decimal numbers from a file and uses
decode О to turn them into RGB val-
ues. The input file that produced lhe
results in l igure 72 is shown after lhe
code.
ГИЛ К К 72: Decoding an RGB String.
import java.awt.':
import java, io.'-;
import java.uti1.Vector;
class Main extends Frame implements Runnable
int dotSize = 30;
Vector vec = new VectorO;
Main(String filename) {
super (“decode Example’’);
try {
Buffe^edReader in =
new BufferedReader(new InputStreamReader(
new Fi1 eInputSt ream(fi1 ename)));
String str;
while ((str = in.readLine()1 !- null) {
vec.addElement(str);
}
} catch (lOException e) {
setSize(200, 200);
show();
(new Thread(this)).start();
}
public void update(Graphics g) {
Insets insets = this.getlnsets() ;
int x = 0, у = 0, rowCount = 0;
for (int i - 0; i<vec.size(); i++) {
g.setColor(Col or.decode((Stri ng)vec.elementAt(i)));
q. f i I lOval (insets. 1 ef t + x-x%dotSi ze , insets, topi y-y%dot Si ze ,
dotSize, dotSize);
x += dotSize;
if (rowCount == 5) {
у += dotSize;
x — 0;
rowCount - 0;
r else {
a+rowCount;
public void run() {
while (true) {
try {Thread.sieep(100);} catch (Exception e) {}
286
repaint();
public static void main(String[] args) {
if (args.length != 1) {
System.err.printlnC'java Main <input_file>");
System.exi t(-l);
}
new Main(args[0]);
input
#e286ff
#ff90ff
#73909a
#732c9a
#lf2c51
#c56c20
#ab31df
#b3021f
#23f39d
#123c90
equalsO
purpose Determines if an object is equal to the color.
Syntax public boolean equals(Object obj)
description An object obj is equal to this color if obj is a Color instance and its red,
green, and blue component values are identical to those of this color.
PARAMETERS
obj The object with which to compare, obj may be null.
Returns true if object is equal to this color; fal se otherwise.
overrides java.1ang.Obj ect.equals().
example See getColorQ-
getBlue()
purpose Retrieves the blue component of the color.
syntax public int getBlueO
Returns The blue component of the color that is a value in the range 0 255.
SEE ALSO Color().
example See the class example.
java.awt
Color
getColor()
Л
В
D
E
F
G
H
I
J
К
L
M
N
О
p
Q
R
s
и
V
w
X
Y
getColorf)
purpose Creates a color whose RGB value is specified in a system property.
syntax public static Color getColor(String propertyName)
public static Color getColor(String propertyName, int defaultlnt)
public static Color getColor(String propertyName, Color
defaultcolor)
description These methods create a new instance of Color whose 24-bit RGB value is
specified by the system property propertyName. If propertyName is not
defined or the value is not an integer, then one of three things can be returned.
First, if defaultlnt is defined, then a new Color instance containing the 24
bit RGB defaultlnt value is returned. Second, if defaultcolor is speci-
fied, then it is returned. Third, if neither defaultlnt nor defaultcolor are
specified, then nul 1 is returned.
PARAMETERS
defaulted orThe Color instance to use if the system property is not defined or the value is
malformed.
defaultlnt The 24-bit color value to use if the system property is not defined or the value
is malformed.
propertyNameThe non-nul 1 name of the system property.
returns A new non-nul 1 Color instance containing the color as specified by the value
of the system property propertyName.
see also decodeO , getRGBQ * java. lang. System. getProperty О .
example This example reads in some properties from a file that defines some text, the
color of the text, and its background color. Figure 73(a) shows the contents of
the properties file. Figure 73(b) shows the frame that displays the text. To see
how the two methods brighter О and darker () work, click the window: the
text brightens and the background color darkens.
। -------------------------------]
I # text
text.value=)ava
# blue text
text.fg=#O0O088
# yellow background
text.bg=#eeee00
(a)
(b)
FIGURE 75: Using Foreground and Background Colors.
288
getc oior(
import java.awt.-;
import java.awt.event.*;
import java.io.*;
import java.util.';
class Main extends Frame {
Color fg, originalFg;
Color bg, originalBg;
String str;
MainO {
super(“getColor Exarple”);
try {
System.getProperti esO • load(
new FileInputStream(“properties.txt”));
System.getProperties().1ist(Syster.out);
fg = originalFg = Color.getColor(“text.fg”, 0x000000);
bg = originalBg - Color.getColor(“text.bg”, Color.white);
str = System.getPropertiesO.getProperty(“text.va1ue”);
} catch (Exception e) {
e. pri ntStackTraceO ;
}
addMouseListener(new MouseLi stener());
setSize(200, 100);
show();
}
public void paint(Graphics g) {
Insets insets = getlnsetsO;
int w - getSize().width-insets.left-insets.right;
int h = getSize().height-insets.top-insets.bottom;
Font f - new Font(“Helvetica”, Font.BOID, 40);
FontMetrics fm = g,getFontMetrics(f);
g.setFont(f);
g.setColor(bg);
g.fi1lRect(insets.left, insets.top, w, h);
g.setColor(fg);
g.drawStri ng(str, insets.left +• (w-fm. stringWidth(str))/2 ,
insets.top * (h-fm.getHeight())/2+fm.getAscent());
// Mouse event listener
class MouseListener extends MouseAdapter {
public void mousePressed(Mousetvent evt) {
// If darkening or brightening either color has no
// effect, simply swap the colors.
if (originalFg.brighter().equals(originalFg)
II originalBg.brighterO .equals(originalBg)) {
fg * originalBg;
bg =r originalFg;
} else {
fg originalFg.brighter();
bg - originalBg.darkerO ;
}
repai nt ();
}
Color
java.aw i
getGreenC)
D
E
E
Ci
H
I
J
к
L
M
N
()
P
Q
R
S
T
u
V
w
X
Y
Z
public void mouseReleased(MouseEvent evt) {
// Restore original colors
fg originalFg;
bg = original Bg;
repaint();
}
}
public static void mai n(St r i ng[J args) {
new Main();
1
getGreenO
Pt’RPOSt- Retrieves the green component of the color.
S'! \TAX public int getGreenO
RI H R VS Fhe green component of the color. It is a \alue in the range 0-255
SEE M SO ColorO .
EXAMPI k See the class example.
getHSBColorf)
Pt’RPOSl- Creates a new Color instance from an HSB specification.
SY VI AX public static Color getHSBColor(float hue, float saturation, float brightness)
DESCRIPTION PARAMEI ERS This method is equivalent to new Color(HSBtoRGB(hue, saturation, brightness));
brightness Fhe brightness component of the color. This value must be in the range 1.0.
hue The hue component of the color. This value must he in the range 0.0 1.
saturation The saturation component of the color. This value must be in the range 1.0.
REIl RXS A new non-nul 1 Color instance based on the specified HSB values.
EXAMPLE See the class example.
290
getRed()___________________ __________________________
purpose. Retrieves the red component of the color.
syntax public int getRedO
returns The red component of the color, h is a value in the range 0-2 55.
SEE ALSO Col or о . *
example Sec the class example. И
I
getRGBQ____________________________________________ _ ____ _______ _________ *
purpose Retrieves the 24-bit RGB representation of the color. (
syntax public int getRGBQ }
description This method returns the RGB representation of the color. It always has the fol-
lowing formal. Bits 24-31 always have the value 0xff. Bits 16-23 contain the
value of the red component. Bits 8 15 contain the \alue of the green compo-
nent. Bits 0-7 contain the value of the blue component. I
returns The 24-bit RGB representation of the color.
SEE ALSO Co I or О. *
example See the class example.
gray ________________ ______________________
purpose This constant field holds the color gray (128, 128.128).
syntax public final static Color gray
example See black.
green
purpose This constant field holds the color green (0. 255, 0).
Syntax public final static Color green
example Sec black.
Color
hashCodef)
ja\ a.awt
hashCodef)
PURPOSE Calculates the hash code for the color.
SYNTAX public int hashCodeQ
DESCRIPTION This method calculates this color’s hash code from its RGB value. If equals(cl, c2) is true, then cl and c2 will have the same hash codes: oth- erwise. cl and c2 will likely have different hash codes.
RI 1 I RNS The color's hash code.
OVERRIDES Object. hashCodeQ.
SEE At.SO equalsQ.
LXAMPl E Sec Object.hashCodeQ.
HSBtoRGBO
Pl’RPC ISE Converts an HSB color specification to a 24-bit RGB color specification.
SYNTAX public static int HSBtoRGB(float hue, float saturation, float bri ghtness)
DESCRIPTION The RGB color as a 24-bit integer. See getRGBQ for details about the encod- ing.
PARA MET f RS brightness I hc brightness component of the color. This value must be in the range 0.0 1,0.
hue saturation I he hue component of the color. This value must be in the range 0.0 1.0. The saturation component of the color. This value must be in the range 0.0 1,0.
SEE ALSO ColorModel .getRGBdefaultQ , getRGBQ .
EXAMPLE. See the class example.
lightGray
purpose This constant field holds the color light gray (192. 192.192).
syniax public final static Color lightGray
example See black.
292
magenta
magenta
-— — - — —
PURPOSE This constant field holds the color magenta (255. 0. 255).
SYNTAX public final static Color magenta
EXAMPI-E See black.
orange _
PURPOSE- This constant field holds the color orange (2 55. 200. 0).
SYNTAX public final static Color orange
EXAMPLE: See black.
pink
PURPOSE: This constant field holds the color pink (255, 175, 175).
SYNTAX public final static Color pink
EXAMPLE Sec black.
red
PURPOSE This constant field holds the color red (255, 0. 0).
SYNTAX public final static Color red
EXAMPLE. See bl ack.
RGBtoHSBO
PURPOSE Converts an RGB color specification to an HSB color specification.
SYNTAX public static float[J RGBtoHSB(int red, int green, int blue, float[] hsbReturnValues)
DESCRIPTION If' hsbReturnValues is not null, the HSB values are placed in the hsbRe- turnValues and hsbReturnValues itself is returned. If hsbReturnValues is nul 1, a new array containing the HSB values is returned.
PARAMETERS blue The blue component of the color. T his value must be in the range 0-255.
Color
java.awt
toString()
green The green component of the color This value must be in the range 0 255.
hsbRet urnVal ues
The array to be used to return the three HSB values—hue. saturation, and
brightness -or null. If non-nul 1, the array must hax e length of at least 3.
red The red component of the color. This value must he in the range 0 255.
rfti’rns A non-nul 1 array containing three values in the range 0.0-1.0. The first ele-
ment contains the hue: the second, saturation; and the third, brightness.
shh also ColorModel .getRGBdefau 110 , getRGBQ . Image.
e xample: See the class example.
F G toString()
H PCRPOSF Generates a string representation of the color.
1 SYNTAX public String toStringQ
J DESCRIPTION This method returns the string representation of this color. It consists of its
К RGB values.
L This method is typically used for debugging.
M Rl-П RNS A non-nul 1 string representing the color.
N OVERRIDES java. 1 ang.Object. toStri ngO-
() EXAMPLE Sec java.1ang.Object.toString().
P
Q white
R plrpose. This constant field holds the color white (255,255. 255).
s syntax public final static Color white
1 example See black.
v
w yellow
% pi rpose This constant field holds the color yellow (255. 2 55. 0).
Y syniax public final static Color yellow
/ exxmpie- See black.
294
I Cl V Cl. c I VV L . 1 1 I
ColorModel
Syntax
public abstract class ColorModel
Description
An image is a collection of pixels. Each pixel has a location in the image and a value. The pur-
pose of the ColorModel class is to convert these pixel values into colors. There are many ways
to encode a color as a pixel value; the two main ones are described in the following sections.
However, the important fact to remember is that a set of pixel values is meaningless unless it is
associated with an instance of ColorModel to interpret the values.
The index Color Model
Image
s
>1 2
Color Table
Pixel
Value
ARGB
ARGB
ARGB
Pixel
Value
»| ARGB 1
(a) Index Color Model
(bl Direct Color Model
FIGURE 74: The Two Types of Color Models.
In the index color model, pixel values do not themselves contain any information from which
you could extract a color. Rather, pixel values are used to index into a color table (see Figure
74a). The actual set of colors in the table are encapsulated in a ColorModel instance and can
vary from instance to instance.
You can tell if a color model instance is using the index color model by determining if it is
an instance of IndexColorModel. Using the IndexColorModel class, you can create an
instance with your own set of colors. See the IndexColorModel class for additional methods.
ColorModei
java.awt. image
The Direct Color Model
In the direct color model, the pixel values actually contain the color information. In this case,
the color mode is to extract the color information from the pixel value (see Figure 74bк The
typical encoding used in a direct color model is to div ide the bits in a pixel value among the
components of a color. For example, in one encoding you could allow 2 bits for red and green.
10 hits for blue, and 4 bits for alpha.
You can tell if a color model instance is using the direct color model by determining if it is
an instance of Di rectColorModel. The DirectColorMode1 class allows you to specify an
encoding that divides the bits of a pixel value among the four color components. See the
Di rectColorModel class for additional methods.
The main advantage of the index color model over the direct color model is that an image
using an index color model can be represented in much less space (three to four times smaller),
rhe disadvantage is that (he available colors that the image can use are limited to the ones in
the color table.
lhe Default Color Model
The ?\WT package specifies what is called the
default color model, which is used as a ‘’standard"
when converting between different color models.
If a method is described to return pixel values in
rhe default color model, it doesn't need to return
an instance of any other color model. To interpret
such pixels, you need only to retrieve the default
color model using the get RGB-def aul tO
method in this class.
3* 2^ 23 16 15 8 7 0
alpha red green blue
FIGI RE 75: Pixel Value Format for the
Default C olor Model.
The format for pixel values in the default color model is an integer with 8 bits each of
alpha, red, green, and blue color components ordered correspondingly from the most signifi-
cant byte to the least significant byte. This is shown in Figure 75.
MEMBER SUMMARY
Constructor Method
ColorModei() Constructs a new ColorModei instance.
Color Component Methods
getAlpha() getBlueO getGreen() getRedO getRGBQ Retrieves the alpha component of a pixel value. Retrieves the blue component of a pixel value. Retrieves the green component of a pixel value. Retrieves the red component of a pixel value. Converts a pixel value to a pixel value in the default color model.
296
MEMBER SUMMARY
Pixel Size Members
getPixelSizeO
pi xel_bi ts
Retrieves the bii size of pixel valuer in the color model.
Holds the bit si/e of pixel valuer using this color model.
Default Color Model Method
Retrieves the default color mode
getRGBdefault()
Example
This example retrieves the color
model used by an AWT component
(which is platform-dependent). If an
index color model is used, all the col-
ors in the color model's color table
are displayed in a grid (sec Figure
76). If a direct color model is used.
256 random colors are generated and
displayed.
When the cursor is moved over a
displayed color, the program displays
the color components of lhe color in a
label located al the lop of lhe win-
dow.
import java
import java
import java
import java
HGl RE 76: ColorModel .
алt. •';
awt.image. •’
awt.event. "
uti1.Random
class Main extends Frame {
ColorGrid egrid;
Label label = new Label();
MainQ {
superC’ColorModel Example”);
ColorModel colorVodel = Tool ki t. getDefau'1 t^ool ki ). getCol orN'odel (j ;
int bitsize = coloc^odel . getPi xel Si zeO ;
if (ColorModel instanceof IndexColorModel; r
// index color model
egrid = new ColorGridfl bitsizej;
for Lint i=0; i<l<<bitsize; i+-j {
egri d . setColо г Г i. col orModel.net RGB Ci) j;
}
} else {
direct color model
ColorModel
java.inn. image
A
Random r - new RandomO;
cgrid - new ColorGrid(256);
for (int i-0; i<256; i*+) {
cgrid.setColor(i, г. nextlntO) ;
}
}
add(<grid, BorderLayout.CENTLR);
add(1abel, BorderLayout.NORTH);
// Add mouse motion listener for color grid
cgrid.addMouseMoti onListener(new MouseMotionEventHandler О);
setSize(300, 300);
show();
I-' class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
(1 ColorModel cm = ColorModel.getRGBdefau1t();
int x = evt.getXQ, у = evt.getYO;
H int rgb т cgrid.getRGB(x, y) ;
] 1abel.setText(cm.getRed(rgb) * “ “ * cm.getGreen(rgb)
+ “ “ + cm.getBlue(rgb) + “ a:” + cm.getAlph
J }
}
К
public static void main(String[] args) {
L new Mai n();
}
M }
N // This class displays a grid that is used for displaying colors,
class ColorGrid extends Component {
() int rows, cols;
int colorsLJ;
P ColorGrid(int numColors) {
colors = new int[numColors];
Q cols - Math.min(16, numColors);
rows = (numColors - 1) / cols + 1;
R }
S // Sets the color at the cell located at position ‘i‘.
// ‘rgb’ is a color in the default RGB color model.
T void setColor(int i, int rgb) {
colorsf i] = rgb;
U }
V // Returns the pixel value at (x, y). The pixel value is encoded
// using the default color model.
W int getRGB(int x, int y) {
int cellw = getSize().width / cols;
X int cellH - getSize().height / rows;
Y x /- cellW;
у /- cellH;
Z
// Return the last color if out of bounds,
return colors[Math.min(colors.1ength-1, у •• cols * x)J;
}
298
public void paint(Graphics g) {
int cellW = getSizeO.width / cols;
int cellH = getSize().height / rows;
for (int i-0; i<colors.length; i++) {
int r -= i / cols;
int c = i % cols;
g.setColor(new Color(colors И 1));
g.fillRect(c " cellW, r * cellH, cellW, cellH);
}
}
}
ColorModeK)
PURPOSE Constructs a new ColorModei instance.
SYNTAX public ColorModei(int b)
DESCRIPTION This constructor is used by subclasses of this class to specify that the bit size of pixel values of this color model instance is b bits wide. This class cannot be directly instantiated.
PARAMETERS b A non-negative number specifying the bit size of pixel values using this color model.
example This class cannot be directly instantiated. See the ColorModei subclasses IndexColorModel and Di rectColorModel for examples for constructing ColorModei instances.
getAlpha()
PURPOSE Retrieves the alpha component of a pixel value.
syntax public abstract int getAlpha(int pixelvalue)
DESCRIPTION Subclasses must implement this method to return the alpha component of a color specified by the pixel value pixel Value. The return value must be in the range 0-255. where the value 0 means completely transparent and 255 means completely opaque.
PARAMEIERS pixelVaiue I he pixel value specifying a color in the color model.
RETURNS The alpha transparency component in the range 0 255.
example. See the class example.
java.awi.image
ColorModel
getBlue()
getBlucf)
PI RPOSI svnt ax DE SC RIP 1 ION Retrieves lhe blue component of a pixel value. public abstract int getBlue(int pixelValue) Subclasses must implement this method to return the blue component of lhe
в color specified bv the pixel value pixelValue. The return value must be in (he
range 0 255. where lhe value 0 means no blue and 2 55 means maximum blue.
I) PARAMETERS
П pi xelValue The pixel value specif}ing a color in the color model.
p RE/TCRNS The blue color component in the range 0-255.
Cl l.X \MPI 1 See the class example.
H J getGreen()
J PCRPOSi: Retrieves the green component of a pixel value.
к SYNTAX public abstract int getGreen(int pixelValue)
L M N DESCRIPTION Subclasses must implement this method io return the green component of the color specified by the pixel value pi xel Vai ue. The return value must be in (he range 0-2 55. where the value 0 means no green and 255 means maximum green.
0 PARAMETERS
P pi xelVaiue The pixel value specifying a color in the color model.
Q Rl TCRNS The green color component in the range 0-25 5.
R exampe.e: See the class example.
s
getHixelSize()
i: V PCRPOSI- Retrieves the bit size of pixel values in the color model.
w SV NTAX public int getPixelSize()
X DESCRIPTION 'rhe returned value is the same as the one supplied to the constructor.
Y Kbit RNS The bit si/e of pixel values in the color model.
Z EXAMPLE See the class example.
300
getRedf) _ _ _
PURPOSE Retrieves the red component of a pixel value.
SYNTAX public abstract int getRedfint pixelValue)
DESCRIPTION Subclasses must implement this method to return the red component of the color specified by the pixel value pi xelValue. The return value must be in the range 0-255. where the value 0 means no red and 255 means maximum red.
PARAMETERS pi xel Value The pixel value specifying a color in the color model.
returns The red color component in the range 0-255.
EXAMPLE See the class example.
getRGBQ
PURPOSE. Converts a pixel value to a pixel value in the default color model.
SYNTAX public int getRGB(int pixelValue)
DESCRIPTION The pixel value pixelValue is converted to an equivalent pixel value that must be interpreted using the default color model. The color of the new pixel value may not necessarily be identical to the color of pi xel Vai ue. There may be some loss of color information.
PARAMETERS pixelValue The pixel value specifying a color in the color model.
RETURNS A pixel value that specifies a color in the default color model.
SEE ALSO getRCBdefault().
EXAMPLE See the class example.
getRGBdefault()
PURPOSE Retrieves the default color model.
SYNTAX public static ColorModel getRCBdefault()
DESCRIP'J ion The color model instance returned by (his method is used to translate pixel sal ues encoded with the default color model into colors.
RETURNS Л non-nu 11 instance of the default color model.
example. See the class example.
ja\a.awt.image
ColorModei
pixel bits
pixel bits
Pl RPOSL this field holds the hit size of pixel values using this color model.
SA XT AX protected int pixel_bits
DESCRIP 1ЮХ This holds the value that was specified by the ColorModei constructor.
SF.E A [.SO See ColorModei().
F
F
(j
H
I
J
К
L
M
N
()
P
Q
R
s
T
L
V
W
X
Y
Z
302
java.awi
Component
J
Syntax
public abstract class Component implements Imageobserver, MenuContainer,
Serializable
Description
A component is a user interface object that can be displayed on the screen and can interact with
the user. Such user interface objects include buttons, scrollbars, and (ext fields. The Compo-
nent class is the superclass of all nonmenu-related components (the MenuComponent class is
the superclass of all menu-related components).
The Component Hierarchy
Some components are containers that have all the
properties of a component, plus the ability to contain
other components (called children}. A user interface
is made of many components and containers. All
components (and containers) must exist inside
another container (called the parent)', only the top-
most container lacks a parent. This arrangement pro-
duces a hierarchy of components that affects how
components are laid out and how events travel from
one component to another. Figure 77 shows an exam-
TextArea
Frame
But ton
Panel
Button
FIGURE 77: Component Hierarchy.
Component
java.au t
pie of a component hierarchy More information about layout and e\enls are described in this
section.
The Bounds
д T he bounds of a component specify the absolute size of the component and its location within
its parent. The bounds includes any decorations or borders that the component may haxc. The
a- and у-coordinates of the hounds specify the coordinates of the component relathe to the
Щ bounds of its parent.
D All coordinates used by the classes in the AWT package, such as in mouse events or
graphics painting, are relathe to a component's bounds.
[.
p The Minimum, Maximum. and Preferred Sizes
livery component has a minimum, maximum, and preferred size. The minimum size and pre-
G furred si/e of a button, for example, is such that the button's label can be properly displayed in
H its current font. The maximum size of the button might be such that its width is ’Infinite" but
[ its height is exactly the font height. For noncontainer components like buttons and scrollbars,
the preferred and minimum sizes are usually the same and the maximum size is usually "infi-
1 nite" in both dimensions.
K The minimum, maximum, and preferred sizes of a component is strictly a hint to the lay-
out manager. The layout manager can ignore these hints and resize the component to whatexcr
L size it chooses. In other words, these sizes are not enforced in any way.
M h's important to note that the results of calling getMinimumSize(\ getMaximum-
N Size(). and getPreferredSize() differ depending on whether the component's peer
exists (see ‘Layout and the Valid State" later in this section). In general, the peers of the com-
° ponent hierarchy should be created before the calculation of the minimum, maximum, or pre-
P ferred size of the component hierarchy.
The Alignment Property
r rhe alignment property is a pair of floating-point values, one that specifies the v-alignment
and one that specifies the у-alignment. Together the a- and у alignment values specify an
alignment point on the component. 'This alignment point affects how some layout managers
1 place the components in a container. See the LayoutManager2 class description for more
U information about this property. More specifically, the alignment point on a component c is
V (x_alignment * c.width, y_alignment * c.height)
w Table 7 shows the alignment constants available in this class for the most common align-
X ment values.
Y
Z
304
Constant Name Numeric Value Alignment Meaning
LEFT_AL1GNMENT 0.0 t-alignment point is at the left edge of the component.
right_altgnveni 1.0 А-alignment point is at the right edge of the component.
CENTER_AL1GNMENT 0.5 л ofy-alignment point is at the center of the component.
TOP_ALTGNMENT 0.0 у-alignment point is at the top edge of the component.
B0TT0M_ALIGN'1EM 1.0 у alignment point is at the bottom edge of the component.
TABLE 7: Alignment Constants.
The Enabled Property
A component can be either enabled or disabled. When it is enabled, the user can interact with
the component to cause it to fire events. When it is disabled, the component will not respond to
user gestures and so will not fire events. Enabled and disabled components look different so
that they can be visually distinguished.
Disabled components are also transparent to mouse events. Therefore, if the user clicks a
disabled component, the mouse event will be dispatched to the first enabled component behind
the disabled component or to the container.
The Focus
When the user presses a key on the keyboard, a key event is created and dispatched to the com-
ponent with the focus. There can be only one component with the focus at any time, but any
component can acquire the focus at any time by calling requestFocusQ. A component will
fire the focus gained/focus lost event (see FocusEvent) whenever it gains or loses the focus.
Currently, there is no easy way for an object to determine which component in a hierarchy of
components has the focus (the only way is for the object to walk lhe component hierarchy and
register for focus events on each component.)
Л component should give some kind of visual indication that it has the focus so that the
user can easily identify lhe component that will be affected by keyboard activity.
Focus Traversal
The user can move the focus from one component to another by pressing the Tab or Shift-Tab
keys. This action is called focus traversal. See the Contai ner class for more information.
The Visible Property
A component can be made visible or invisible. Components are typically created visible by
default. Only top-level components like frames and windows are created invisible by default.
The Name
A component has a locale-independent name that is primarily used by a program to identify
the component. For example, when a program receives an event, it could retrieve the event’s
Component
java.aw't
source and use its name to determine which component fired the event. The name is. by
default, initialized to a unique identifier. For example, the Button class assigns a name of the
form ’'button" concatenated with the value of a counter that it increments for each new
instance of Button (e.g.. "buttonO"). The program can overwrite this default by using set-
A Name О to set it to another locale-independent string.
The Locale
A component can have a locale associated with it. If a component docs not have its locale set
P explicitly, it inherits the locale from its closest ancestor that does have a locale. If no locale is
found, the locale defaults to Locale.getDefault().
A component can use its locale setting to display localized resources (such as text, colors.
I- and images). This fine-grained locale association allows a component or a hierarchs of com-
ponents to maintain and manage their own locales. This enables a single applet or application
to have components using different locales. It also enables different applets running within a
H single applet context like a Web browser to have different locales from each other and from the
। applet context itself.
J Layout and the Valid Slate
К Layout normally applies to components that are containers. A container has associated with it
a layout manager that controls the placement of children within the container. See the Con-
l' tai ner class for more information about layout managers. However, all components maintain
M a valid state that is used by the layout manager. In particular, if a component is invalid, the
component's doLayoutO method will be called the next time the layout manager is invoked.
О Peers
p A component such as a button uses the platform’s native implementation of a button. For
example, on Solaris, the AWT button uses the Motif button widget, while on Windows 95. the
AWT button uses the button control. So that the AWT button component behaves the same on
R all platforms, the button is assigned a peer that takes care of translating the behavior of the
platform's native button to the behavior of the AWT button.
When a user interface with components and containers is constructed, the component hier-
T archy is created without any peers. Even without the peers, it is possible to initialize all the
U properties on the components. When the user interface is ready to be displayed on the screen,
the peers for each component are finally created and properly initialized with the current state
V of the component. Once the peer exists, any modifications to the component's properties are
W forwarded directly to the peer. (With the peers in existence, the component may or may not
x maintain the state changes. However, when the peer is destroyed, any state that the peer main-
tained for the component must be transferred back to the component.)
The peers of a component hierarchy are created by calling the addNotifyO method of
/ the top level container. Although all components have an addNotifyO method, the method
cannot be called directly. Only the addNotifyO method of a subclass of Window can be
called. When this happens, it sets off a chain reaction that results in a call to the addNoti fy О
306
method of every component in the hierarchy. The opposite sequence occurs when the
removeNotifyO method is called on the top-level container.
Figure 78 shows a component hierarchy and its corresponding peer hierarchy.
FIGURE 78: Л Component Hierarchy and Its Corresponding Peer Class Hierarchy;
Events
Components interact with a program that uses them through the use of events. For example,
clicking a component with the mouse fires a mouse-clicked event. For a complete discussion
on available events, event handlers, and event flow through a component hierarchy, see the
AWTEvent class.
Л component fires the following types of events: KeyEvent. MouseEvent. FocusEvent,
and ComponentEvent. A KeyEvent is fired when a key is pressed or released inside the com-
ponent. A basic MouseEvent is fired when the mouse enters or exits the component and when
a mouse button is pressed or released while the mouse is inside the component. A mouse-
motion MouseEvent is fired when the mouse is moved or dragged inside the component. A
FocusEvent is fired when the component gains or loses keyboard focus. Finally, a Compo-
nentEvent is fired whenever the component is moved, resized, hidden, or made visible. See
the class descriptions of these events for details.
Popup Menus
A component can have one or more popup menus associated with it. These popup menus con-
tain menu items that are specific to the component tor its component hierarchy) and are typi-
cally displayed in response to a special mousing gesture. The particular mousing gesture is
platform-specific. For example, on Windows 95, clicking the right mouse button causes a
popup menu to appear. When the user makes the special popup mousing gesture, the generated
mouse event is flagged. The application can then decided whether to display a popup.
The Tree Lock
The tree lock is a lock that protects the AWT hierarchies. It is a global lock and is shared by all
live components running in the system (or more precisely, from one class loader). It must be
held whenever it is necessary to walk or modify the hierarchy. For example, the tree lock
Component
java.awt
should be held while climbing the ancestor chain looking for a frame or while a container is
laying out its children.
The tree lock is intended to prevent inconsistent states if two or more threads are simulta-
neously using the hierarchy. For example, suppose you retrieve a container's component count
just before another thread removes the last child. As you walk the list of children, you will get
unexpected results as you try to retrieve the last child. To prevent this, you need to acquire the
tree lock before retrieving the component count and release it only after you have finished
walking the list of children.
Painting
When a component wants to do some painting, such as display an image or draw a circle, it
must override its paint() method and paint with the supplied graphics context. The paintQ
method is called by the AWT whenever it discovers that some part of the component has been
damaged and needs repainting.
When a component wishes to change some part of the drawing for example, if the com-
ponent is a button and the user has just clicked it the component should not create a graphics
context and make the change. Instead, the component should request the AWT system to
invoke its pai nt О method.
In the case of native components, calling repaintf) actually results in a call to updateO
rather than to pai nt О. The difference between paint() and update () is that when
paintf) is called, you can assume that the background has been cleared to the component's
background color. When updateO is called, you assume that the background has not been
damaged. The default implementation of updateO is to clear the background and call
paintO- If the component's painting is fairly simple, there is no need to override lhe
pai nt О method. However, if the painting involves an continuous animation, you may notice
an annoying effect called flickering, where the animation seems to flash the background on
and off. The flickering effect is caused by the background's continuously being cleared and
repainted. If this happens, you need to override the updateO and implement a technique
called double-buffering. See the createlmageO example for an example of how to imple-
ment double-buffering.
Native and Lightweight Components
There are two kinds of components: native and lightweight. A native component has a peer
that uses a user interface object provided by lhe platform. Button and List are examples of
native components. A lightweight component behaves like a native component, except that its
peer does not use any system resources. Its advantage is more-efficient use of the platform s
resources. You can freely mix lightweight and native components in a lightweight or native
container. However, a lightweight component requires the use of one native component in
order to function. In particular, one of its ancestors must be a native component. For example,
an application needs to have only a single Window component, which is a native component.
All the other components and containers in the window could be lightweights.
308
At present, the AWT does not supply any lightweight components; many will be available
in a future release. However, the lightweight support is fully implemented and you can (and
are encouraged to) create your own lightweight components. To create a lightweight compo-
nent, you must have your component extend from Component. To create a lightweight compo-
nent that is a container, see Contai ner for information about lightweight containers.
There are small differences between lightweight and native components. Here are some of
them:
1. When a container contains lightweight and native components, the lightweights will
always appear behind the native components, regardless of the /-ordering of (he compo-
nents. However, the relative z-ordering within each group (lightweight or native) is pre-
served. (See Contai ner for more details on /-ordering.) So if a lightweight LI is in front
of a lightweight L2 with many native components in between, Li will appear in front of
L2 even though both LI and L2 appear behind the native components. Mouse events are
delivered to the native components before they are offered to the lightweight components,
regardless of their z-orderings. When lightweight and native components are mixed in a
container, it is highly recommended that a nonoverlapping layout manager be used to
avoid confusion.
2. If you call repai nt О on a lightweight, the AWT responds by calling its paint О
method. In the case of a native component, the AWT will call its updateO method. This
means that the background for the lightweight is always cleared. Special steps must be
taken to avoid flickering. It is not enough for the lightweight to implement double-buffer-
ing. See the Container class for more information.
3. The default implementation of getPreferredSizeO for lightweight returns l-x-l. The
getPreferredSizeO method for a native component returns its current size. The result
of this difference is that when the components are laid out. they may not take on the sizes
you expect. To have the lightweight behave exactly like a native component, the light-
weight should override getPreferredSizeO and return its current size.
4. When a graphics context is created on a lightweight component, either by the AWT sys-
tem or by a call to getGraphi csQ, the graphics context is not initialized with values
from the component. Instead, its background color, foreground color, and font are initial-
ized with the values from its closest native container. What this means is that when the
paint О method is called on a lightweight, the colors and fonts must be properly initial-
ized.
ДЙМВЕК SUMMARY
Constructor Component О Constructs a new instance of Component. Cont in ue d
Component
java.awt
A
В
D
E
I
G
H
I
J
К
I,
M
N
О
P
У
R
S
T
u
V
w
X
Y
Z
MEMBER SUMMARY
Alignment Methods and Fields
BOTTOM-ALIGNMENT
CENTER-ALIGNMENT
1 getAl i gnmentXO
getAl ignmentYQ
LEFT-ALIGNMENT
RIGHT-ALIGNMENT
TOP ALIGNMENT
Color Methods
getBackgroundO
getColorModel()
getForegroundQ
setBackgroundO
sett oregroundQ
Cursor Methods
getCursorO
setCursorO
: Enable Methods
i sr nabledO
setEnabledO
Event Methods
: di spatchEventO
enableEventsO
di sabl eEventsO
processComponentEventO
processEvent О
processFocusEventО
processKeyEventO
processMouseEventO
processMouseMotionEvent()
Constant indicating alignment along a component's bot-
tom edge.
Constant indicating alignment along a component's cen-
ter.
Retrieves this component's preferred alignment along the
л-axis.
Retrieves this component's preferred alignment along the
v axis.
Constant indicating alignment along a component's left ;
edge. .
Constant indicating alignment along a component's right ,
edge. i
Constant indicating alignment along a component's top J
edge. j
Retrieves this component's background color.
Retrieves this component's color model.
Retrieves this component's foreground color.
Sets this component's background color.
Sets this component s foreground color.
Retrieves this component's cursor image. |
Sets this component's cursor image. <
Determines if this component is enabled.
Enables and disables this component.
Dispatches an event to this component.
Enables event types for this component.
Disables event types for this component.
Processes a component event enabled for this component.
Processes an event enabled for this component.
Processes a focus event enabled for this component.
Processes a key event enabled for this component.
Processes a mouse event enabled for this component.
Processes a mouse motion event enabled for this compo-
nent.
310
KtwY '
Event Listener Methods addComponentLi stenerО Adds a listener to receive this component's component events.
addFocusListenerO addKeyListenerО addMouseLi stenerО addMouseMoti onLi stener() Adds a listener to receive this component's focus events. . Adds a listener to receive this component’s key events. 1 Adds a listener to receive this component's mouse events. Adds a listener to receive this component's mouse motion events.
removecomponentListenerО Removes a listener from receiving this component's com i ponent events. ।
removeFocusLi stenerO Removes a listener from receiving this component’s focus events.
removeKeyListener() Removes a listener from receiving this component's key events.
removeMouseLi stener() Removes a listener from receiving this component's | mouse events.
removeMouseMotionListener() Removes a listener from receiving this component's mouse motion events.
Focus Methods i sFocusT rave rsable() requestFocusQ transferFocusf) Determines if this component is focus traversable. I Requests that the focus be given to this component. I Moves the focus to the next focus traversable component.
Font Methods getFont() getFontMet ri cs() setFontO Retrieves this component's font. Retrieves the font metrics for a font for this component. Sets this component's font. ।
Graphics and Painting Methods getGraphicsО paintO paintAll() repaint() updateО Creates a graphics context for this component. Called to repaint this component. Called to repaint this component and its descendants. Requests that this component be repainted. Called to repaint this component without the back- ground's having been cleared.
Image Methods checklmageC) createlmageO Retrieves the construction status of an image. Creates an off-screen image or an image from an image producer.
imageUpdateO Called to deliver status information about the loading oi an image.
preparelmageO Triggers the loading of image data for an image. Continued
Component
java.awt
MEMBER SUMMARY
Localization Methods getl ocaleO setl ocale() Retrieves this component s locale. Sets this component’s locale.
Layout Methods contai ns() dotayout() getBoundsO getComponentAt() getLocationQ getLocati onOnScreenO getMaximumSizeO getMinimumSizeO getPreferredSi ze() getSizeO i rival idate() isValidO setBoundsQ setLocationO setSizeQ validated) Determines if this component contains a specified point. Invokes the layout manager on this component. Retrieves this component's bounds. Retrieves the component containing a specified point. Retrieves this component's location relative to its parent. Retrieves this component's location on the screen. Calculates this component s maximum size dimensions. Calculates this component's minimum size dimensions. Calculates this component's preferred size dimensions. Retrieves this component's size. Invalidates this component. Retrieves this component s valid state. Moves and resizes this component. Moves this component. Sets this component's size. Validates this component.
Lock Method getlreeLock() Retrieves lhe lock object for the entire AWT component tree.
Name Methods . getName() setNameO Retrieves this component's name. Sets this component's name.
Parent Method getParentO Retrieves this component's parent.
Popup Menu Methods add() remove() Adds a popup menu to this component. Removes a popup menu from this component.
Print Methods printO printAl1 О i Prints this component on a graphics context. Prints this component and its descendants on a graphics context.
Visibility Methods i sShowingO Determines if this component is visible and is showing on the screen.
. isVisibleO setVisibleO Determines whether this component is visible. Makes this component visible or invisible.
312
Fhember summary
Peer Methods
addNotifyO ( reales this component's peer.
getToolkitf) Retrieves this component's toolkit.
removeNoti fyO Destroys this component's peer. ‘
Debugging Methods
listO Prints out information about this component and its descendants.
paramStringO Generates a string representation of this component ’s state.
toStri ngO Generates a string representation of this component’s state.
Deprecated Methods
actionO Use ActionListener interface instead.
boundsO Replaced by getBoundsO
del i verEveritO Replaced by di spatchEventO.
disableO Replaced by setEnabl edO.
enableO Replaced by setEnabledO
getPeerf) Should not manipulate peers directly.
gotFocusQ Use the FocusLi stener interface instead.
handleEvent() Replaced by processEventO.
hide() Replaced by setVisibleO-
insideO Replaced by contai ns О.
keyDownO Use the KeyLi stener interface instead.
keyUp() Use the KeyLi stener interface instead.
1ayout0 Replaced by doLayoutO.
locateQ Replaced by getComponentAtO.
locationO Replaced by getLocationO-
lostFocusO Use the FocusLi stener interface instead.
minimumSizeO Replaced by getMi ni mumSi ze 0
mouseDowriO Use the MouseListener interface instead.
mouseDragO Use the MouseMotionLi stener interface instead.
mouseEnterO Use the MouseLi stener interface instead.
mouseExitO Use the MouseLi stener interface instead.
mouseMove() Use the MouseMotionListener interface instead.
mouseUpO Use the MouseLi stener interface instead.
move() Replaced by setLocationO.
nextFocusO Replaced by transferFocusO-
postEventO Replaced by di spatchEvent().
preferredSizeO Replaced by getPreferredSize().
reshapeO Replaced by setBounds(). Continued t 1
Component
jax a.awi
MEMBER SUMMARY
Deprecated Methods (Continued) I
resizeQ Replaced b\ setSizeО.
д show() Replaced by setVisi ble().
I size() Replaced b\ getSizeO-
I---------------------------------------' — -------------- ---------------
D
See Also
E ComponentPeer, Container, java.awt.image.Imageobserver,
p java.io.Serializable, Menucontainer, Toolkit.
G L i
Example
H This example demonstrates most of the methods in this class by implementing a simple text
1 field component using a lightweight component (see f igure 79). When the text field has the
focus, a block cursor appears, indicating where the next character will go. If the text field is
not full, the block cursor blinks. When the cursor is in the text field, the cursor is changed to a
К Cursor. TEXT-CURSOR. Pressing Return in the text field causes it to fire an action event filled
L with the current contents of the text field. The action event is dispatched using the overridden
processEventO method, which has support for processing ActionEvent.
M The component's isFocusTraversableO method returns true, so it is a fouus-travers-
N able component.
()
’ Component Example H["IE3[
This is an example[]
FIGI RE 79: Simple Text Field Based on a Lightweight Component.
import java.awt.*;
import java. awt. event.;
class Main extends Frame implements Actiont istener {
RainQ {
superC'Component Example”);
SimplelextField canvas - new SimpleTextField(30, 5);
add(canvas, BorderLayout.CENTER):
canvas.addActionLi stener(thi s);
packO;
show();
}
public void actionPerformedfActionTvent evt) {
System.out.pri ntln(evt);
}
static public void main(String[] args) f
314
java.awt
new Main();
}
}
class SimpleTextField extends Component implements Runnable {
int border;
int length;
Font font;
FontMetrics fontM;
char[J buffer;
int bufferlx;
boolean hasfocus;
boolean cursorOn;
SimpleTextField(int len, int bor) {
superO;
border = bor;
length = len;
buffer - new char^len];
font - getTontO;
if (font == null) {
font = new Font("Di alog", Font.PLAIN, 20);
}
fontM = getFontMetrics(font);
// L isten for key and mouse events.
this.addMouseListener(new Mouse£ventHandler());
thi s.addFocusLi stener(new FocusEventHandler());
thi s . addKeyLi stener(new KeyEventHandlerO) ;
// Set text cursor,
setCursor(Cursor.qetPredefinedCursor(Cursor.fEXT_CURSOR));
// Start the thread that blinks the cursor.
(new Thread(this)) .startO ;
}
public Dimension getMinimumSizeO {
// The minimum height depends on the point size.
int w - fontM.charWidth(‘m’) * length;
return new Dimension^ + 2-border, fontv. getHeightO + 2-border);
}
public Dimension getPreferredSizeO {
return getMinimumSizeO;
}
public Dimension getMaximumSize() {
return new DimensionfShort .MAX_VALUE, getPreferredSizeO . height);
}
public boolean i sFocusI raversableO {
return true;
}
public void paintfGraphics g) {
int у (getsize() . height-fontv.getHeightO)/2;
// Clear the background using the text background color.
g.setColor(SystemColor.text);
g,fi 1 lRect(0, 0, getSizeO .width, getSizeO .height) ;
Component
java.awt
g.setFont(font);
g.setColor(SystemColor.textText);
g.drawChars(bufferT 0, bufferlx, border, у + fontM.getAscent());
// Draw blinking cursor.
int x = fontM.charsWidth(buffer, 0, bufferlx) + border;
int w - fontM.charWidth(1c’);
if (hasFocus) {
g. setColor(getForegroundO);
g.fillRect(x, y, wT fontM.getHeight());
if (cursorOn) {
if (bufferlx < buffer.1ength) {
g.setColor(SystemColor.text);
g.fi11Rect(x+2, y+2, w-4, fontM.getHeight() 4);
}
}
}
}
// Event handlers
class MouseFventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
requestFocusO;
}
}
class FocusEventHandler extends FocusAdapter {
public void focusGained(FocusEvent evt) {
hasFocus = true;
repaintO;
}
public void focusLost(FocusEvent evt) {
hasFocus ~ false;
repaintO;
}
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_DELETE:
case KeyEvent.VK_BACK_SPACE:
if (bufferlx > 0) {
bufferlx ;
repaintO ;
}
break;
case KeyEvent.VK.ENTER:
ActionEvent action =
new ActionEvent(SimpleTextField.this,
ActionEvent.ACTION-PERFORMED,
String.valueOf(buffer, 0. bufferlx));
// Send contents of buffer to listeners
processEvent(action);
break;
default:
repaintO;
}
}
public void keyTyped(KeyEvent evt) {
if (bufferlx < buffer.length
316
java.awt
Com ponen
actionf
&& !evt.isActionKeyO
M iCharacter.isTSOControl(evt.getKeyChar())) {
buffer [bufferlx-n-J = evt.getKeyChar();
}
}
}
// Support for Action Listener.
ActionListener actionListener;
public void addActionListener(ActionListener I) {
actionListener = AWTEventMulticaster,add(actionl istener, 1);
}
// Override processEventO to deal with ActionEvent.
protected void processEvent(AWTEvent evt) {
if (evt instanceof ActionEvent) {
processAc t i onEvent((Acti onEvent)evt);
} else {
super.processEvent(evt);
}
}
// Supply method to process Action event.
protected void processActionEvent(ActionEvent evt) {
if (actionLiStener b null) {
actionLi stener.acti onPerformed(evt);
}
}
public void runО {
while (true) {
try {
// If component has focus, blink the cursor every 1/2 second.
Thread.sleep(500);
cursorOn = icursorOn;
if (hasFocus) {
repaint();
}
} catch (Exception e) {
e.pri ntStackT race();
}
}
}
}
action()
DEPRECATED
purpose Use the ActionLi stener interface instead.
syntax public boolean action(Lvent evt, Object arg)
PARAMETERS arg evt An object whose contents depend on the component that fired the event. The non-nul 1 event.
Component
aclion()
java.awt
reti’rns fal se if the event should be passed up to the component’s parent; true other-
wise.
deprecation Formerly, the component would override acti on О to handle action events,
import java.awt.*;
class Old extends Frame {
Button b = new Button(“Button”);
OldO {
super(“Deprecated actionQ example”);
add(b, BorderLayout.CENTER);
show();
pack() ;
}
public boolean action(Event evt, Object what) {
if (evt.target == b) {
System.out.println(“Button pressed");
return true;
}
return false;
}
public static void main(String[1 args) {
new 01d();
}
}
Replace the usage of actionQ with the ActionListener interface. An
action listener is first defined to implement the actionPerformedQ method
and then added as a listener for the component.
import java.awt.*;
import java.awt.event;
class New extends Frame {
Button b = new Button(“Button”);
NewQ {
super(“New ActionEvent Example”);
add(b, BorderLayout.CENTER);
b.addActionLi stener(new ActionEventHandlerO);
packQ ;
show();
}
class ActionEventHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
System.out.pri nt In(“Button pressed”);
}
1
public static void main(String[J args) {
new New();
}
J
SEE also java.awt.event.ActionEvent.
318
java.awt
ширине! 11
addf)
add()
PURPOSE SYNTAX Adds a popup menu to this component. .
public synchronized void add(PopupMenu popup) I • add Ex . PIPTE3
p” [Popup^
DESCRIPTION PARAMETERS popup SEE ALSO A component can have a list of popup menus that can be dynamically displayed on the component. This method adds the popup menu popup to the end of the list of popup menus for this component. The non-nul 1 popup menu to add. PopupMenur remove(). itenrt iem2
EXAMPLE This example creates a frame with a checkbox and a canvas. The checkbox controls whether the canvas has a popup menu. The canvas overrides processMouseEventO to display the popup if the popup trigger. See Figure 80. FIGURE 81): Canvas with Popup Menu. mouse event indicates a
import java.awt.*;
import java.awt.event;
class CanvasWithPopup extends Canvas {
РорирМели popup;
CanvasWithPopup(РорирЧепи popup) {
enableEvents(AWTEvent.VOUSE_EVENT_MASK);
this.popup - popup;
}
void addPopupO {
add(popup);
}
void removePopupO {
remove(popup);
}
protected void processMouseEvent(MouseEvent evt) {
// Display popup only if it has not been removed
if (popup.getParent() != null && evt.isPopupTrigqer()) {
popup.show(evt.getComponent(), evt.getXO, evt.getYO);
1
super.processMouseEvent(evt);
}
}
public class 4ain extends Frame implements ItemListener, ActionL istener {
Checkbox cb - new CheckboxC'Popup”, false);
CanvasWithPopup canvas;
Component
addComponent Listened)
java.awt
Main() {
super(“add Example”);
add(cb, BorderLayout.NORIH);
cb.addlterrListenerfthi s);
PopupMenu popup = new PopupMenu("Button Control”);
popup.add(‘‘i teml”) ;
popup.add("i tem2”);
popup.addActionLi stener(thi s);
canvas - new CanvasWithPopup(popup);
add(canvasT BorderLayout.CENTER);
setSize(100, 200);
show();
}
// Handler for checkbox
public void itemStateChanged(ItemEvent evt) {
switch (evt.getStateChangeO) {
case ItemEvent.SELECTED:
canvas.addPopup();
break;
case ItemEvent.DESELECTED:
canvas. removePopupO ;
break;
}
}
// Handler for popup menu
public void actionPerformed(ActionEvent evt) {
System.out.println(evt.getActionCommandO) ;
}
static public void main(String[] args) {
new Main();
}
}
addComponentListenerf)
Pl'kPOSF Adds a listener for receiving this component’s component events.
SV ХТЛХ public synchronized void addComponentListener(ComponentListener listener)
DhSCRIPWX’ A component fires component events as it is resized, moved, or made visible or invisible. See ComponentEvent for more details. After this method is called, the component event listener listener will receive component events fired by this component. If listener is null, this method does nothing.
PAkAMl’TRRS 1i stener Lhe possibly null component listener to add.
320
java.awt ___ _______ vvinpviron
add Focus Listened
SHF. ALSO java . awt .event. ComponentAdapter, j’ava. awt.event.ComponentEvent, java.awt.event.Component Listener, removeComponentlistener().
EXAMPI.fl See the java.awt .event .ComponentEvent class example.
addFocusListener()
PURPOSE Adds a listener for receiving (his component s focus events.
SYNTAX public synchronized void addFocusListener(locusListener 1istener)
description A component fires focus events as it gains or loses keyboard focus. See FocusEvent for more details. After this method is called, the focus listener listener will receive focus events fired by this component. If listener is null, this method does nothing.
PARAMETERS listener The possibly nul 1 focus listener to add.
SEE ALSO java.awt.event.FocusAdapter, java.awt.event.FocusEvent, java.awt.event.FocusListener, removeFoeusListener().
EXAMPLE; See the class example.
addKeyListenerf)
PURPOSE Adds a listener for receiving this component's key events.
syntax public synchronized void addKeyListener(KeyListener listener)
DESCRIPTION Key events are fired when a key has been pressed, or released in a component. See KeyEvent for more details. After this method is called, the key listener listener will receive key events fired by this component. If listener is null, this method does nothing.
PARA ME: IERS 1i stener The possibly null key listener to add.
SEE ALSO java.awt.event.KeyAdapter, java.awt.event.KeyEvent, java.awt.event.KeyListener, removeKeyi istenerQ-
example See the class example.
addMoust*Listener()
PURPOSE. Adds a listener for receiving this component's mouse events.
Component
addMouseMotionl.istcncrt )
java.awt
SV NT XX public synchronized void addMouseListener(MouseListener 1i stener)
DESCRIPTION Mouse events are fired when the mouse enters, exits, or when a mouse button has been pressed, or released on a component. Sec MouseEvent for more details. After this method is called, the mouse listener listener will receive mouse events fired bv this component. If listener is nul 1, this method does nothing.
PARAMI-1 ERS 1i stener The possibly null mouse listener to add.
SEEALSO addMouseMot ionLi stenerf), java.awt.event.MouseAdapter, java.awt.event.MouseFvent, java.awt.event.MouseLi stener, removeMouseLi stener().
example: See the class example.
addMouseMotionListener()
PERPOSE Adds a listener for receiving this component's mouse motion events.
SYNI -XX public synchronized void addMouseMoti onli stener(MouseMoti onLi stener 1i stener)
DESCRIP 1 ION Mouse motion events are fired when the mouse is moved or dragged. Sec MouseEvent for more details. After this method is called, the mouse motion listener listener will receive mouse motion events fired bv this component. If 1 istener is null, this method does nothing.
PARAMETERS 1i stener The possibly null mouse motion listener to add.
St E ALSO addMouset istenerO, java.awt.event.MouseMotionAdaptert java.awt.event.MouseFvent, java.awt.event.MouseMotionListener, removeMouseMotionLi stenerO.
EX AM Pl I See the Container class example.
addNotify()
Pl'R POSE Creates this component's peer.
SYNTAX public void addNotifyO
DESCRIPTION This method notifies this component that this component has been added to a container and to create a peer for this component if necessary. By default, this method invalidates this component and invokes addNotifyO on any of its
322
BOTTOM ALIGXM[-:>
popup menus. This method must be overridden by a component subclass in order to actually create the peer. This method can be called directly only if this component is a top-lex el win dow. such as a frame or dialog (see Window.addNoti fyO).
SEE ALSO invalidateO t removeNotifyO.
EXAMPLE See setVisibleQ.
BOTTOM-ALIGNMENT
PLRPOSl: Constant indicating alignment along a component's bottom edge.
SYSIAX public static final float BOTTOM ALIGNMENT
DESCRIPTIOS This constant specifies that the у-coordinate of the component's alignment point be at the component's bottom edge. Its value is 1.0f.
SEE ALSO CENTER.ALIGNMENT, getAlignmentY(), TOP..ALIGNMENT.
EXAMPLE See the LayoutManager2 class example.
boundsO DEPRECATED
PURPOSE Replaced by getBoundsO,
SYNTAX public Rectangle bounds()
RETURNS A new non-nul 1 rectangle containing the bounds of this component.
DEPRECATION Replace the usage of the deprecated method Rectangle b = comp.boundsO ; with Rectangle b = comp.getBoundsO ;
CENTER-ALIGNMENT
PURPOSE Constant indicating alignment along a components center.
SYNTAX public static final float CENTER
DESCRIPTION This constant specifies that the y-coordinate of the component's alignment point be at the component's center. Its value is 0.5f.
SEE ALSO BOTTOM ALIGNMENT, CENTER_ALIGNMENT, getAlignmentXO. getAl ignmentYO, LEE-T_A1 TGNVENT, RICHI_ALIGNMENT, TOP-ALIGNMENT.
example See the LayoutManager2 class example.
it
Component
java.awt
A
к
F
G
H
I
J
К
L
M
IN
()
P
Q
R
S
T
u
V
w
X
Y
z
check Imaget)
checklmage()
PCRPOSi- Retrieves the construction status of an image.
syma\ public int checklmageflmage image, TmageObserver obs)
public int checklmage(lmage image, int width, int height,
ImageObserver obs)
description This method retrieves the status of an image that is being constructed. As far as
this method is concerned, an image that has been scaled is treated as a coni
pletely different image. Therefore, when checking the status of an image, sou
must also indicate which scaled version of the image to check. Do this b\ set-
ting the width and height parameters to the dimensions of the scaled image.
The image may not be in the process of being constructed: this method does
not start the process. To start the image construction process, use prepare-
ImageQ. If the image observer obs is not null, any status changes are deliv-
ered it.
PARAMI I FRS
height
image
obs
width
RETURNS
If >= 0, specifies the height of the
scaled version of the image to
check.
fhe non-nul 1 image to check.
If non-null. specifies the image
observer to be notified whenever
the status changes.
If >= 0. specifies the w idth of lhe
scaled version of the image to
check.
The combination of status bits as
defined by the TmageObserver
interface.
SU-aiso java.awt. image. ImageObserver, FIGURE 81: Checking the Status uf a
preparelmageO. Scaled Image,
example While an image is being loaded
and displayed, a background thread is created to create a scaled version of the
image. The thread uses the checklmageO to wait until the scaled image is
complete. When the scaled image is complete, it is displaced on (he screen.
See Figure 81 for a screen shot of this example.
import java.awt.-;
import java.awt.image.*;
class Main extends Frame {
324
checklrn
Main(String filename) {
super ('‘checkimage example");
add(new ImageCanvas(getTooIkit().getlmage(filename)),
BorderLayout .Ct-NTER);
setSi ze (300, 300);
show();
}
static public void main(String[] args) {
if (args.length 1) {
new Main(args[0J);
} else {
System.err.println(“usage: java Main <image file>”);
}
}
}
class ImageCanvas extends Component implements Runnable {
int newWidth = 200, newHeight - 200;
boolean drawScaled;
Image image;
ImageCanvas(Image image) [
this,image = image;
(new 7hread(thi s)) .startO;
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
if (drawScaled) {
g,clearRect(0, 0, getSize() .width, getSizeO . height);
g.drawlmage(image, 0, 0, newWidth, newHeight, this);
} else {
g,drawlmage(image, 0, 0, this);
}
}
public void run() {
preparelmage(image, newWidth, newHeight, null);
while (true) {
int status = checkimage(image, newWidth, newHeight, null);
if ((status&ImageObserver.ERROR) != 0) {
System.out.println("Error encountered while scaling image*’);
System.exit(l);
}
if ((status&ImageObserver.ALLBITS) 0) {
drawScaled = true;
repaint();
break;
}
try {
Thread.sieep(100);
1 catch (InterruptedException e) {
}
}
J
Component
ComponenK )
java.au t
Component!)
pi rposu Constructs a new instance of Component.
syntax protected Component()
description This constructor is used when implementing lightweight components. See the
class description for details on lightweight components.
EX/\MPLt Sue the class example's SimpleTextField. checklmageO's ImageCanvas.
and createlmageO's Mai nCanvas.
contains!)
perpose Determines if a point is inside this component.
syntax public boolean containsfint x, int y)
public boolean contains(Point pt)
description This method is used to determine whether the point pt is inside or outside of
this component. By default» this method returns true if pt is inside this com-
ponent's bounds. If a component is a lightweight component with a nonrectan-
gular shape, this component should override this method and return true only
if pt is inside the shape (heavy-weight components cannot have a nonrectan-
gular shape).
The AWT system calls this method to determine whether the cursor has moved
in or out of this component. It needs this information to determine when to fire
a mouse enter or exit event (sec MouseEvent).
PAR A MET LRS
Pt
X
У
RETl RNS
SEE Al SO
EXAMPI I
The point to check.
The л-uoordinate relative to this component.
The v-coordinate relative to this component.
true if the point is within this component’s bounds; false otherwise.
getComponentAt().
This example demonstrates
how to implement a nonrect
angular lightweight compo-
nent. The component is an
image button that fires action
events only when the user
clicks a nontransparent pixel.
To show which pixels are
EIGt'RE 82; Nonrectangular Lightweight
Component.
326
java.awi
contains
nontransparent, the image button displays a hand cursor when the cursor is
over a nontransparent pixel. See Figure 82.
The image button constructor takes an image and uses the pixel grabber class
to extract the color map and pixels from the image. The color map is used to
determine the transparent pixel value (if any).
The contains() method of the lightweight component uses the array of pix-
els and the transparent pixel value lo determine if the coordinate is on a non
transparent pixel.
The image button also implements all the methods necessary to support action
listeners.
import java.awt.*;
import java.awt.image.*;
import java.awt.event;
class Main extends Frame implements ActionListener {
Main(String filename) {
super ('‘Component. contai ns()”) ;
// Create image button and listen for events.
ImageComponent c - new ImageComponentCfilenare):
c.addActi onLi stenerCthi s);
// Layout and show components.
add(c, Border!ayout.CENTER);
pack();
show();
}
public void actionPerformed(ActionEvent evt) {
System.out.println(evt);
}
public static void mai n(Stri ng[] args) {
if (args.length != 1) {
System.err.println(“Usage: java Main <image-file>”);
System.exit(l);
}
new Main(args [0]);
}
}
class ImageComponent extends Component {
Dimension imageDim;
Image image;
int transparentPixel;
bytef] pixels;
ImageComponent(String filename) {
// Retrieve the image from a file.
image = getToolkit().getlmage(filename);
// Use -1 for the width and height to grab everything.
PixelGrabber pg = new PixelCrabber(image, 0, 0, -1, lt false);
Component
contai ns()
jusa.aut
A
В
D
Ji
F
G
H
1
J
К
L
M
N
()
P
Q
R
S
T
U
V
W
X
Y
Z
// Get the pixels.
pg.startGrabbing() I
try {
pg.grabPixelsO;
} catch (Exception e) {
e. pri ntStackl race() ;
}
imageDim - new Dinension(pg.getWidth() , pg.getHeight()) ;
// If the color map is an index color map, get the
// pixels and the transparent pixel.
if (pg.getColor^odelО instanceof IndexColorModel) {
pixels - (byteO)PQ-getPixels();
transparentPixel =
((IndexColor’Hodel)pg. get ColorModei ()) . get f ran spa rent Pi xel ();
}
// Enable mouse events.
add^ouseLi stener(now MouseEventHandl erО);
// Set the default cursor to be a hand cursor.
setCursor(Cursor.getPredefi nedCursor(Cursor.HAND-CURSOR));
}
public boolean contains(int x, int y) {
// Return true on if the cursor is over non-transparent pixels.
if (x >- 0 && x < imageDim.width
&& у >-- 0 && у < imageDim. height) {
return pixels ®=- nu 1 1 | I
pixelsLx+y-imageDim.width] !- transparentPixel;
}
return false;
1
public Dimension getPreferredSizeO {
return imageDim;
}
public void paint(Graphics g) {
g.setColor(Color.pink);
g.fi11Rect(0, 0, getSize() .width, getSizeO .height) ;
g.drawlmage(image, 0, 0, this);
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
if (actionLi stener null) {
acti onLi stener,actionPerformed(
new Act ionFvent(ImageComponent.thi s,
ActionEvent.AC1ION_PERFORMFD, null));
}
}
}
// Action listener support methods.
transient ActionListener actionListener;
public synchronized void addActionListener(ActionListener 1) {
actionListener - AWTEventMulticaster.add(actionListener. 1);
}
328
create I ma
public synchronized void removeActionListener(ActionListener 1 i {
acti onl i stener = A’^TEventvul ti caster. removefacti onLi stener , 1);
createlmage()
pirposf Creates an off-screen image or an image from an image producer.
syntax public Image createlmageQ’nt width, int height)
public Image createlmageflmageProducer prod)
description There are two forms of createlmageQ. The first form uses a width and
height to create an off-screen image on which you can paint. The off-screen
image is often used to achieve smooth animation. The image is first con-
structed in the off-screen image and then painted on the screen in its entirely.
This technique is called double-buffering. 'The following example demon-
strates the use of createlmageQ for double-buffering.
'I'hc second form of createlmageQ takes an image producer prod and cre-
ates an image based on the dala supplied by the image producer. See the
RGBImageFi 1 ter class for an example that uses this form of createlmageQ.
The height of the off-screen image in pixels.
'I'hc non-nul 1 image producer prod.
The width of the off-screen image in pixels.
par,\mf-:ters
height
prod
wi dth
returns I'hc image or nul 1.
exampit- This example imple-
ments a simple anima-
tion of the word “Java"
slowly rising in the cen-
ter of a “brown bubbling
liquid." as shown in Fig-
ure КЗ. To eliminate
flickering, the program
calls createlmageQ to
create an oft-screen
image and uses that
image to implement
I l(»l RE X3: Simple knimation I sinj» Double-buffering.
do u b I e - b u ffc ring. I: a c h
frame of the animation is first geneialed on the off-screen imaee and then
painted whole on the screen.
java.awt
Component
crcatelrnagei)
D
E
F
G
H
I
J
К
L
M
N
О
p
Q
R
S
T
u
V
w
X
Y
Z
import java.awt.";
class Main {
static public void mai n(Str i ng[] args) {
Frame f = new Frame("create Image Example");
f.add(new MainCanvas(), BorderLayout.CENTFR);
f.setSi?e(200, 100);
f.show();
}
}
class MainCanvas extends Component implements Runnable {
Image backBuffer;
Graphics backG;
String str - "Java";
int point Size = 15;
Point[] points new Point[10Z;
int[] pointRates = new int[points.length];
Point stringPt - new Point(0, 0);
MainCanvasQ {
for (int i-0; i<points.length; i* + ) {
pointsfi] = new Point(0, 0);
i ni tPoi nt(i);
}
(new Threadft hi s)) .start ();
}
void initPointfint i) {
pointsfi] .x = (int)(Math.floor(Math. random():;getSize() .wi dth));
points[iJ.у - getSize().height;
poi ntRates fi ] - (int)(Math. floor(Math. random ()'• 30)) f 5;
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
int w = getBounds().width;
int h = getBoundsQ .height;
if (backBuffer — null
|! backBuffer.getWidth(nul1) !~ w
I backBuffer.getHeight(nul1) != h) {
backBuffer = createlmage(wt h);
if (backBuffer Ь null) {
if (backG != null) {
backG.disposeO:
}
backG = backBuffer.getGraphicsO;
backG. setTont (new Font ("He I vetica1', Font.BOLD, 48));
FontMetrics fm =. backG.getFontMetricsO ;
stringPt.x - (w-fm.stringWidth(str))/?;
}
}
if (backBuffer !=- null) {
backG.setColor(new Color(130, 80» 80)); // brown
330
deliverEve
backG.fillRect(0, 0, h) ;
// Bubbles behind the string.
backG.setColor(Color.white);
for (int i-0; i<points.length/3; i++) {
backC.fillOval(points[iJ.x, points[i].y, pointSize, pointSize);
}
// Paint the string
backG.setColor(Color.black);
backG.drawString(str, stringPt.x, stringPt.у % h * h);
backG.drawStringfstr, stringPt.x, stringPt.у % h * ?vh);
// Bubbles in front of the string.
backG.setColor(Color.white);
for (int i=points.length/3; i<points.length; i++) {
backC.fillOval(points[i].x, points[ij.y, pointSize, pointSize);
}
g.draw!mage(backBuffer, 0, 0, null);
}
public void run() {
whi1e (true) {
for (int i=0: i<points.length; i++) {
points[i].y -- pointRatesИ';
if (points[ij.y -pointSize) {
ini tPoint(i);
}
}
stri ngPt. y--;
repaintO ;
try { Thread.sleep(80); } catch (Exception e) {};
}
}
deliverEventf)
DEPRECATED
purpose Replaced by di spatchEvent().
syntax public void deliverEvent(Event e)
PARAMETERS
e The non-nul 1 event,
deprecation Replace the usage of this deprecated method, as in
deli verEvent(e);
with
di spatchEvent(awtEvent);
SEE also AWTEvent.
Component
disable( )
java.awt
disable() DEPRECATED
Pl RP( )SE Replaced by setEnabledQ.
A SYNTAX public void disableO
В D DEPRECATION Replace the usage of this deprecated method, as in disable(); with setEnabled(false);
F
disableEvents()
G PURPOSE Disables event types for this component.
H SYNTAX protected final void di sab 1eFvents(long eventTypes)
1 J DESCRIPTION An event type is enabled when a listener for that type is added to this compo- nent or when enabl eEventsO is invoked explicitly on this component with the event type's mask. This method disables the event types specified by the
К mask eventTypes. It is used by subclasses of Component to undo the effects
L of enableEvents(). If a component has listeners corresponding to the event type, events will always be delivered to its processEventO method, inde-
M pendent of the effects of enabl eEvents 0 or di sabl eEvent sQ.
N PARAMETERS
0 eventlypes fhe event mask specifying the event types to disable. Event mask values are
P defined in AWTEvent.
o SEI. ALSO AWTEvent, dispatchEventO , enableEvents(), processEventO.
R EXAMPLE. Menuitem, di sabl eEvents О serves the same purpose as Component.dis- abl eEventsO. except that it is for Menuitem and its subclasses. See Menu-
S Item, di sabl eEvents О for an example.
dispatchEvent()
v ” ~
pcrposi Dispatches an event to this component.
syntax public final void dispatchEvent(AWTEvent evt)
X
description This method dispatches the event evt to this component or one of its ances-
tors. If evt is one of the event types that have been enabled for this compo-
Z nent. it is processed using processEventO. II the event is not consumed by
this component and it is a key event, it is passed on to this component’s parent
and up the ancestor component tree until it is consumed.
332
d i spatchi t
PAR Wit IFRS
evt l he non-nul 1 AWTEvent.
sel vlso AWTEvent. enableEventsO, disableEventsО, processEventO.
example This example creates a frame with two buttons. See Figure 84(ai. Clicking the
buttons changes the louts of all lhe components in the frame. In particular,
clicking lhe SmallFont button causes the components to assume a small font,
while clicking the LargeFont button causes all the components to assume a
large font. See Figure 84(b).
deli ver Event Example i®E
deli ver Event Example МрИ E3
i SmallFont
LargeFont
SmallFont
LargeFont
i a» < b)
FIGI RE 84: Component. dispatchEvent О: (a) Initial State and (b) after ('hanging Font Sizes.
Changing lhe si/c of the button label's font does not invalidate the button or its
container automatically. Updating the button's si/e requires the button itself
first to be invalidated (this automatical Iv invalidates all of its ancestors, includ-
ing its container). Cal ling doLayoutf) on the container then corrects the posi-
tion and si/e of the button. An alternative to calling doLayoutQ is calling
validateQ-
Changing the font of the container's components could have been achieved bv
simplv calling their setFontO methods. However, tor the purposes of this
example, the same effect is achieved bv delivering a special action event—
SetFontEvent—to the components using di spatchEvent ().
import java.awt.*;
import java. awt. event. ;
class Main extends Frame implements ActionListener {
Main Г) {
superCdi spatchEvent Exampi p” j :
setLayout<пел FlowLayout(jj;
Button b:
addfb = new vainButton(“Smal1 Font” ) ) :
b.addActionListenerfthisj ;
addfb = new MainButton("LargeFont")) :
Component
dispatchEvenU)
java.awt
b.addAct ionListener(thi s);
setSize(200, 200);
show() ;
}
public void actionPerformed(ActionEvent evt) {
String arg - evt.getActionCommand();
Font f = nul1;
if ("Smal1 Font”.equal s(arg)) {
f - new Font(“Serif”, Font.PLAIN, 12);
} else if (“1 argeFont".equals(arg)) {
f - new Font(“Serif”, Font.PI AIN, 30);
}
if (f null) {
SetFontEvent fevt - new SetFontEvent(thisf f);
for (int i=0; i<getComponentCount(); i++) {
Component c - getComponent(i);
c.dispatchEvent(fevt);
}
}
dot ayout();
}
public static void main(StringLJ args) {
new Main();
}
}
// Define new event for setting font of button
class SetFontFvent extends ActionEvent {
Font font;
public static final int SFT_FONT-EVENT - AWTEvent.RESERVED_ID_MAX > 1;
public SetFontEvent(Object source, Font f) {
super(sourcet SET_FONI EVFNT, null);
font = f;
}
public Font getFont() {
return font;
}
}
class MainButton extends Button {
MainButton(St ring label) {
super(label);
}
// Override to handle special new event (SetFontEvent)
protected void processActionFvent(ActionEvent evt) {
if (evt instanceof SetFontEvent) {
// Change font as requested
set Font(((SetFontEvent)evt) .getFontO) ;
invalidate(); // invalid button so it’ll get resized
} else {
// Handle normal ActionEvent as before
super.processActionEvent(evt);
}
}
}
334
J4I Vd.dWl
doLayoutt
doLayout()
PURPOSE Invokes the layout manager on this component.
SYNTAX public void dotayout()
description If this component is a container, the container's layout manager is invoked (see Contai ner. doLayoutQ for more details). Otherwise, by default this method does nothing.
SEE ALSO Contai ner .doLayoutQ.
EXAMPLE See di spatchEvent 0
enable()
DEPRECATED
PURPOSE Replaced by setFnabledQ.
SYNTAX public void enableQ public void enablefboolean cond)
PARAMETERS cond If true, this component is enabled: otherwise, this component is disabled.
DEPRECATK )N Replace the usage of these deprecated methods, as in enableQ ; enable(false); with setFnabled(true); settnabled(false);
enableEventsf)
PURPOSE Enables event types for this component.
SYNTAX protected final void enab 1eEventsflong eventTypes)
DESCRIP IION An event type is enabled when a listener for that type is added to this compo- nent. This method is used by subclasses of Component to always deliver events of the specified type to its processEventO method, regardless of whether it has any listeners. This method enables the event types specified by the mask eventTypes.
parameters eventTypes The event mask specifying the event types to enable. Event mask values are defined in AWTEvent.
SEE ALSO AWTFvent, disabletventsО , processEventO.
exampi e See add() and processEventO.
Component
getAlignmentX()
java.avU
getAlignmentX()
PURP( )SE Retrieves this component's preferred alignment along the .v-axis.
SYNTAX public float getAl ignmentXO
DESCRIPTION This method returns the component's л alignment value. This affects the way some layout managers place their components. See the class description for more information. The default implementation of this method returns CENTER-ALIGNMENT. For a different л-alignment value to be returned, this method must be overridden.
RETURNS This component's д- alignment in the range 0.0f to l,0f.
SEE ALSO CENTER. ALIGNMENT , getAl i gnmentYQ , LEFT-ALIGNMENT, RTGHT-ALIGNMENT.
1 X AMPLE See the LayoutManager2 class example.
get Alignment Y()
PURPOSE Retrieves this component's preferred alignment along the y-axis.
SYNTAX public float getAlignmentYQ
DESCRIPTION This method returns the component's у alignment value. This affects the \xay some layout managers place their components. See the class description for more information. The default implementation of this method returns CENTER..ALIGNMENT. For a different у-alignment value to be returned, this method must be overridden.
RETURNS This component's у-alignment in the range 0.0f to 1.0f.
SEI; ALSO BOTTOM-ALIGNMENT, CENTER-ALIGNMENT, getAl ignmentXO, TOP ..Al IGNMENT.
EXAMPLE See the LayoutManager2 class example.
getBackgroundf)
Pl RPOSE Retrieves this component's background color.
S'! NTAX public Color getBackgroundO
DESCRIPTION Some pan of a component’s visual appearance is painted using the background color. For example, a button is painted in the background color, while the label is painted in the foreground color.
336
get Bound s(
If this component does not have a background color set (for example, by call ing setBackgroundQ with a null color), it inherits its background color from the closest ancestor whose background color has been set. If no back- ground setting is found, null is returned.
returns The possibly null background color of this component.
SEE ALSO getForegroundQ, setBackground().
EXAMPLE See the class example.
getBoundsf)
PURPOSE Retrieves this component's bounds.
SYMAX public Rectangle getBoundsQ
DESCRIPTION The bounds of a component specify (he size of this component and its location within its parent. The width and height of the bounds specify lhe dimensions of this component without regard to any insets. The a- and y-coordinates of the bounds specify the location of this component relative to its parent.
RETURNS A new non-null rectangle containing the bounds of this component.
SEE ALSO getLocation(). setSizeQ.
EXAMPLE See createlmageO.
getColorModelf)
PURPOSE Retrieves this component's color model.
SYNTAX public ColorModel getColorModel()
DESCRIPTION If this component's peer exists, this method returns the peer's color model. Otherwise. it returns the default toolkit's color model (see Tool kit. getDe faultToolkitO).
returns A non-nul 1 color model instance.
SEE ALSO ColorModel. Toolkit.getDefaultToolkit().
EXAMPLE See the ColorModel class example.
getComponentAtf)
PURPOSE Retrieves the component containing a specified point.
Component
getCursort)
java.awt
SYMAX public Component getComponentAt(int x, int y) public Component getComponentAt(Point pt)
DESCRIP 1 ION This method is used to determine which. if any, component is al the pixel spec- ified by the point pt or the coordinate x, y. The coordinates must be relative to
A the component's bounds. If this component is not a container, then this method
в uses contains() to determine whether this component contains the point. If this component is a container, sec Container .getComponentAt() for details on the effects.
D PARAMETERS
E pt I he point to check.
r. X The л-coord inate relative to this component's bounds.
У The v-coordinate relative to this component's bounds.
G RETIRES The child component at the specified point. If no child component is at the
H point but the point is inside this component, returns this component itself.
1 Returns null if the point is not in this component.
J SEE XESO contai ns().
К t.X.AMI’l.f. See Contai ner.getComponentAt().
L M getCursor()
N PVRPOSE Retrieves this component's cursor image.
0 SYNTAX public Cursor getCursorf)
P DESCRIPTION This method retrieves the cursor image set for this component. If
Q setCursor() has never been called on this component, this method returns
R the default cursor image.
S RETVRNS The non-nul 1 cursor image for this component.
T SEE AESO Cursor, setCursor().
i; V ЕХЛМРЕЕ See the class example.
w getFontO
X Pl RPOSl Retrieves this component's font.
Y SYNTAX public Font getFontO
z DESCRIHION This method returns the font supplied in the most recent call to setFontO on this component. If setFontQ has never been called on this component, this method returns the font of this component's parent. If this font also has never
338
getFontMetrics(
been set. the search continues up the parent chain until an ancestor component whose font has been set is encountered. If the search yields no such compo- nent. null is returned.
returns This component's font or the font of the closest ancestor whose font has been set. nul 1 is returned if no ancestor has a font set.
SUE ALSO setfontO.
example See the class example.
getFontMetrics()
PURPOSE Retrieves the font metrics for a font for this component.
SYNTAX public FontMetrics getlontMetrics(Font fnt)
DESCRIPTION If this component's peer exists, this method asks the peer for the font metrics of the font fnt. Otherwise, this method returns the result of calling Toolkit.getFontMetrics(fnt). The results of either action are typically the same.
PARAMETERS fnt The non-nul 1 font.
RETURNS The non-nul 1 font metrics for fnt.
SEE ALSO get! ontQ.
EXAMPLE See the class example.
getForegroundf)
PURPOSE Retrieves this component's foreground color.
SYNTAX public Color get! oregroundQ
DESCRIPT ION Some part of a component's visual appearance is painted using the foreground color. For example, a button is painted in the background color, while the label is painted in the foreground color. If this component does not have a foreground color set (for example, by calling setForegroundO with a null color), this component inherits its foreground color from the closest ancestor whose foreground color has been set. If no foreground color has been set. nul 1 is returned.
returns I'he possibly null foreground color of this component.
SEE ALSO gerВасkground(), set Foreground ().
EXAMPLE See the class example.
Component
getGraphicsf)
java.awt
getGraphics()
PFRPOSE SYNTAX Creates a graphics context for this component, public Graphics qetGraphics()
A DESCRIPTION Thi\ method returns a graphics context that uses this component as a drawing
в surface. The result is null if this component's peer does not exist.
If this component is a native component, the background and foreground col-
n ors and the font of the returned graphics context are initialized using the values
in this component. Otherwise, the background color is white, the foreground
i: color is black, and the initial font is undetermined. The origin of the new
F graphics context is the northwest corner of this component's bounds.
G RF.TFRNS A possibly null graphics context on this component.
H SEE Al.SO Graphics. paint().
1 J getLocale()
К Pl RPOSE Retrieves this component's locale.
1, SYNTAX public Locale getLocaleQ
M DESCRIPTION If a locale has been set for this component, it is returned. Otherwise, the locale
N of the closest ancestor with a locale is returned. Applet and Wi ndow, which are
o subclasses of Component, return Locale. getDefaul t О if their locales have
not been explicitly set. See the class description for more details.
I5 RETl’RNS A non null locale.
Q
EXCEPTIONS
R Til eqalComponentStateExcepti on
S If this component does not have its own locale and it docs not have a parent.
Г SEE ALSO java.uti1.Locale, setLocale().
U example: See getNameO.
V
w getLocation()
X PLRPOSE Retrieves this component's location relative to its parent.
Y SYNTAX public Point getLocation()
z DESCRIPTION The location of this component is the top-left corner of this component's
bounds. The location of this component is relative to its parent.
340
getl лк alio nOnScret
RETURNS A new non-null point containing this component's location relative to its par- ent.
SEE ALSO setLocationf).
EXAMPIE Seethe Container class example.
getLocationOnScreen()___________________________________
purpose: Retrieves this component's location on the screen.
syntax public Point getLocationOnScreenO
description The location of this component on the screen is the top-left comer of this com-
ponent's bounds relative to the screen's coordinate space. This component
must be visible and showing on the screen in order for its location on the
screen to be determined.
returns A new non-null point containing this component's location relative to the
screen.
EXCEPTIONS
Il1 egalComponentStateExcepti on
If this component is not showing on the screen.
SEE also isShowingO-
example This example creates a number of
components inside a frame. Clicking
any of the components displays its
absolute location on the screen. See
Figure 85.
import java.awt.*:
import java.awt.event.*:
class Main extends Frame {
Main () {
gelLocationOnScree
.................--------—...
FIGI RE 85: Determining a Component’s
Location.
super(ugetLocationOnScreen example"):
Component c;
MouseEventHandler ml = new MouseEventHandlerO;
add(c = new But ton ( “Qu 1t”) , BorderLayout.NORTH);
c.addMouseLi stener(ml);
addtoMiew CanvasQ, BorderLayout.CENTER);
c.addMouseLi stener(ml);
addConew ScrollbarQ, BorderLayout - EAST) ;
c.addMouseListener(ml);
Component
getMaximurnSizef)
java.awt
add(c-new Labe I("Ready”)T BorderLayout. SOUTH);
c.addMouseLi stenerCml);
setSize(200, 200);
pack();
showQ ;
}
class MouseFventHandler extends MouseAdapter {
public void nousePressed(Mousebvent evt) {
Component src - (Component)evt.getSourceO:
System.out.printin(src.getLocationOnScreen());
}
}
public static void main(String Я args) {
new Main();
}
getMaximumSize()
PURPOSE Calculates this component's maximum size dimensions.
SYNTAX public Dimension getMaximumSize()
DESCRIP 1ION This method returns the maximum si/e that this component wants to be. B\ default, this method returns a width of Short.MAX_VALUF and a height Short.MAX.VALUE.
RETURNS A new non-nul 1 dimension object containing this component's maximum size.
SEE Al SO Contai ner. getMaximumSi zeO , getMi ni mumSi ze() , getPreferredSizeO > getSizeO.
getMinimumSizef)
PURPOSE Calculates this component s minimum size dimensions.
SYNI AX public Dimension getMinimumSize()
DESCRIPTION For native components, the result of this method depends on whether its peer exists. If the peer doesn't exist, this component's current size is returned. If the peer exists, the peer's minimum size is returned (this may also be this compo- nent's current size). For the most accurate result, this component's peer should be created before minimum size information is calculated (see Window.add Noti fy 0).
342
getNar
For lightweight components, this method returns 1-x-1 by default. For the lightweight to behave exactly like a native component, the lightweight should override getMinimumSizeO and return the current size.
RETURNS Л new non-nul 1 dimension object containing this component's minimum size. If this component is a container, see Container.getPreferredSizeO for more information on how the preferred size is calculated.
SEE ALSO Container .getMinimumSizeO , getMaximumSizeQ , getPreferredSizeO, getSize().
example See the class example.
getName()
PURPOSE: Retrieves this component’s name.
SYNTAX public String getNameO
DESCRIPTION The component’s name is a non localized string that can be used by a prograrr to identify the component. For example, when a program receives an event, i could retrieve the event's source and use its name io determine which compo- nent fired the event.
RETURNS Л possibly null string containing this component's name.
SEE: Al 30 setNameO.
EXAMPLE: This example creates a checkbox group that has i three localized labels. l he locale of the compo- nent is set dynamically by mainO. The Main component uses this locale to get the localized labels and uses setNameO to record their non- deux localized names. The item listener for the Main component uses nonlocalized names for the C trois checkboxes in order to determine which check- box has been selected. See Figure 86. MGLRL86, Simple ° Component Localization.
import import import import java.awt.*; java.awt.event.*; java.util.ResourceBundle; java.util.Locale;
public class Main extends Frame {
Main() {
} super(“qetName Example’*);
void init(ItemListener 1) {
// Get localized labels for checkboxes
Component
getName()
java.awt
в
('
D
E
F
G
H
J
J
К
L
ResourceBundl e rb = ResourceBundle.getBundleC^MyBundle", getLocale());
String one = rb.getString(“checkboxOne”);
String two - rb.getString(“checkboxTwo”);
String three rb.getString(“checkboxThree”);
// Create checkboxes
CheckboxGroup eg = new CheckboxGroupO;
Checkbox cl = new Checkbox(one, eg» true);
Checkbox c2 = new Checkbox(two, eg, false);
Checkbox c3 new Checkbox(three. eg, false);
// Set internationalized identifiers for checkboxes
cl. setNameC'one*’) ;
c2.setName("two”);
c3.setName(“three”);
// Add listener for checkboxes
cl.addltemListenerO);
c2.addltemli stener(l);
c3 .addltemListenerO);
// Add checkboxes to frame
add(cl, Borderlayout.NORTH);
add(c2, BorderLayout.CENTER);
add(c3, Borderl ayout.SOUTH);
setSize(100, 100);
show();
M static public void main(String[] args) {
Main m = new Mai n();
N
// Set locale of component
О m.setLocale(locale.FRANCE);
m.init(new TtemEventHandlerO);
P }
}
Q
class ItemEventHandler implements ItemListener {
R public void itemStateChanged(ItemEvent evt) {
Component src = (Component)evt .getSourceQ;
S String target = src.getNameQ ;
int number - 0;
T
if (target.equals("one”)) {
L number = 1;
} if (target.equals(“two”)) {
V number - 2;
} if (target.equals(“three”)) {
W number -= 3;
}
X System.out.println(“number=” + number);
}
Y }
344
gctParentf
getParent() — _
PURPOSE Retrieves this component's parent.
SYNTAX public Container getParentQ
DESCRIPTION This method retrieves this component’s parent. It returns null if this compo- nent does not have a parent. If this component hierarchy is part of a stand- alone application rather than an applet, the top-level window can be deter- mined by following the parent chain until a component without a parent is found.
returns The parent of this component; nul 1 if this component does not have a parent.
EXAMPLE See Button.setLabel().
getPeerQ DEPRECATED
PURPOSE Should not manipulate peers directly.
SYNTAX public ComponentPeer getPeerO
RETURNS This component's peer; nul 1 if this component does not have a peer.
getPreferredSizef)
PURPOSE Calculates this component's preferred size dimensions.
SYNTAX public Dimension getPreferredSize()
DESCRIPTION f or native components, the result of this method depends on whether its peer exists. In particular, if the peer doesn’t exist, this component's current size is returned. If the peer exists, the peer's preferred size is returned (this may also be this component s current size). For the most accurate result, this compo- nent's peer should be created before the preferred size information is calcu- lated (see Wi ndow.addNoti fy()). For lightweight components, this method returns 1-x-l by default. For the lightweight to behave exactly like a native component, the lightweight should override getPreferredSizeO and return the current size. If this component is a container, see Container .getPreferredSizeO for more information on how the preferred size is calculated.
RETURNS A non-nul 1 dimension object containing this component's preferred size.
SEE ALSO Contai ner. getPreferredSizeO , getMaximumSizeO , getMinimumSizeO» getSi ze().
example See the class example.
Component
gciSize()
java.awt
getSize()
pi kposi. Retrieves the size of this component.
syntax public Dimension getSizeQ
descrip riox Che size of this component is derived from this component’s bounds. In partic-
ular. getSi zeQ .width -= getBoundsO .width and getSize().height ==
getBoundsO - hei ght.
retirxs A non-nu 11 Dimension object containing the size of this component.
see also set Size О.
example See the class example.
getToolkit()
pi RPOSh Retrieve'' this component's toolkit.
svmax public Toolkit getloolkitO
description Л toolkit (see Tool ki t) provides a portable interface on many system services
that are related to the AWT For example, w ith a toolkit instance you can create
a print job or get information about lhe screen dimensions. This method
retrieves this component’s toolkit. If this component’s peer exists, the peer
returns this component s toolkit. Otherwise, this method searches up the com-
ponent hierarchy looking for a component whose peer exists and uses the peer
to return a non-null toolkit. If none is found, this method returns
Toolkit.getDefaultToolkit(). Note that if a component is moved from
one frame to another, the returned toolkit in the new frame differ from lhe orig-
inal, since the frames may be on different screens.
reti’RSS A non-nul 1 reference to this component's toolkit.
sfe also Toolkit.
example See Tool ki t .getlmageO-
getTreeLockl)
pt rposi: Retrieves the lock object for the entire AWT component tree.
syntax public final Object getTreeLockO
346
got Focus
descript io\ fhe tree lock must be held whenever you need to walk or modify the hierar-
chy. This method retrieves the lock object for the entire AWT component tree.
See the class description for more information.
returns The non-nul 1 lock object for the entire AWT component tree.
example Here is a simple example that ualks the ancestor chain looking for a frame.
Fora more elaborate example, see LayoutManager.
Frame getFrame(Component c) {
synchronized (c.getlreeLockO) {
Component p - c . getParentО;
while (p != null && ! (p instanceof Frame)) {
p p.getParentQ ;
}
return (Frame)p;
}
}
gOtFOCUS() DEPHECATEl)
PURPOSE Use the FocusLi stener interface instead.
SYNTAX public boolean got!ocus(Event evt, Object arg)
PARAMETERS
arg evt An object whose contents depend on the component that fired the event. The non-nul 1 event.
RETURNS fal se if the event should be passed up to the component's parent: true other- wise.
DEPRECATION Formerly, you would override the deprecated methods gotFocusQ and lostFocusO in order to receive focus events. import java.awt.*; class Old extends Frame { TextField tf = new TextH e ld(20); 01d() { super(“Deprecated Focus example"); add(new TextFieldO» Borderl ayout.NORTH); add(tf, BorderLayout.SOUTH); setSize(100, 100); pack(); $how(); } public boolean gotFocus(Event evt. Object what) { if (evt.target -= tf) { System.out.pr i nt In (“got focus'’) ; return true; } return false;
java.awt
Component
handleEventf)
public boolean lostFocus(Event evt, Object what) {
if (evt.target == tf) {
System.out.println(“lost focus");
return true;
}
return false;
}
public static void main(String[j args) {
new 01 d() ;
}
}
Replace the usage of the deprecated methods got FocusО and lostFocusO
by defining a FocusLi stener and then adding it as a listener to the compo-
nent of interest.
import java.awt.*;
import java.awt.event.*;
class New extends Frame {
TextField tf = new TextField(20);
New() {
super("New Focustvent example");
add(new TextFieldO, BorderLayout-NORTH);
add(tf, BorderLayout.SOUTH);
setSize(100, 100);
tf.addFocusListener(new FocusEventHandler());
pack О ;
showQ ;
}
class FocusEventHandler implements FocusListener {
public void focusGained(FocusEvent evt) {
System, out .pri ntlnC'got focus") ;
}
public void focusLost(FocusEvent evt) {
Systern.out.println(“lost focus");
}
}
public static void main(St ring[] args) {
new New();
}
}
addFocusListenerO, java.awt.event.FocusAdapter,
java.awt.event.FocusEvent, processFocustventO,
remove FocusLi stenerO.
w handleEvent() depreca ted
purpose Replaced by processEventO.
syntax public boolean handleEvent(Event evt)
Z
PARAMETERS
evt The non-nul 1 event.
348
jciva.awi
hidt
returns false if the event should be passed up to this component's parent: true other- wise.
deprecation Formerly, the component would override hand! eEvent О to handle any event received by the component. Replace the usage of handleEvent0 by processEventO or by defining listeners for the various events of interest and adding them as listeners for the component.
SEE ALSO AWTEvent.
hideQ DEPRECATED
PURPOSE Replaced by setVi si ble().
SYNTAX public void hide()
DEPRECATION Replace the usage of this deprecated method, as in hi de0; with setVisible(false) ;
imageUpdateO
PURPOSE Called to deliver status information about the loading of an image.
SYNTAX public boolean imageUpdate(Image img, int infoflags, int x, int y, int wt int h)
DESCRIPTION This method is called if this component requested some information about the image img and the information was not yet available. For example, if this com- ponent called Image.getWidthО and the width information was not yet available (that is, the method returned -1). the imageUpdateO method will be called as soon as the width becomes available. See ImageObserver.imageUpdateO for more details.
PARAMETERS height img infoflags wi dth X У Depends on the status bits enabled in infoflags. The non-null image being updated. A set of status bits. Depends on the status bits enabled in infoflags. Depends on the status bits enabled in infoflags. Depends on the status bits enabled in infoflags.
Returns true if no further calls to imageUpdateO are needed.
example See the java.awt.image.ImageObserver example.
Component
inside()
java.awt
D
E
Я
J
К
M
N
О
P
Q
R
S
T
t:
w
x
Y
inside() DEPRECATED
PLRPOS1 Replaced by contai ns().
SYNTAX PARAMETERS public boolean inside(int x, int y)
X The r-coordinate relative to this component.
У The у-coordinate relative to this component.
RETURNS true if x and у are within this component’s bounds.
DEPRECA1 ION Replace the usage of this deprecated method, as in if (hitarea.inside(x.y)) { flag =- true; } with if (hitarea.contains(x,y)) { flag = true; }
invalidate()
PURPOSE Invalidates this component.
SYM AX public void invalidateO
DESCRIPTION This method invalidates this component and all of its ancestors. See the class description and the validate() method for more details about the valid state.
SE'.E ALSO isValid(). validateQ.
EXAMPLE See val i date ().
isEnabled()
Pt RPOSE Determines if this component is enabled.
SY MAX public boolean isEnabledO
DESCRIPTION A component can be either enabled or disabled. See the class description for more information about a component's enabled state.
REITR.NS true if this component is enabled; false otherwise.
SEE ALSO setEnabled().
EXAMPLE See the Canvas class example.
350
i s Foe u sTra v e rsa hle(
isFocusTraversable()
purpose Determines if this method is focus-traversable.
syntax public boolean isFocusT raversableO
description A component is focus-traversable if it is enabled, it is visible, and its
isFocusTraversableO method returns true, the focus can be moved
around focus-traversable components when the user hits the Tab or Shift-Tab
keys. Tab moves the focus forward, while Shift-7'ab moves the focus back-
wards. The order of the traversal is exactly the order of the components in the
container. For example, if lhe component at index 0 has lhe focus, then hitting
the Tab key moves the focus to the component at index 1 (assuming it is focus-
traversable).
A disabled component should return false,
Even if this method returns false, this component can still gain the focus by
using requestFocusO.
By default, a native component is focus-traversable if its peer is focus-travers-
able. Lightweight components are. by default, not focus-traversable.
returns true if the focus of this component is traversable via the lab or Shift-Tab
keys.
see also java.awt.event.FocusFvent, requestFocusO. transferFocusО
example This example creates three focus- tra-
versable components: two text fields
and a FocusCanvas (Canvas, by
default, is not focus-traversable). To
make Canvas's focus traversable, you
must override i sFocusTravers-
able() to return true and call
requestFocusO when lhe mouse is
clicked. FocusCanvas changes its
background color to blue when it
gains focus. Notice that the order of
the focus traversal is the order of lhe
components in the frame. See Figure
87.
import java.awt.*;
import java.awt.event.;
’ isFocusT raversable
| TextFieldl
FIGURE X7: Focus Traversal.
class Main extends Frame {
Main О {
super(“isTocusTraversable example");
java.awt
Component
isFbctisTraversablef)
// Create components that are focus traversable by defc
add(new 7extField(“TextFieldl'1) , BorderLayout.NORTH);
add(new TextField("TextField2”), BorderLayout.SOUTH);
// Create focus traversable
add(new FocusCanvas(200, 100), BorderLayout.CENTER);
setSize(200, 200);
packO;
show();
}
D public static void main(String[] args) {
new Mai n() ;
V. }
F
class FocusCanvas extends Canvas {
G boolean hasFocus = false;
FocusCanvasCint x, int y) {
H super();
setSize(x, y);
I
// Listen for events.
J addMouseListener(new MouseEventHandlerO);
addFocusLi stener(new FocusEventHandlerO);
К 1
L // Implement focus traversable,
public boolean isFocusTraversableO {
M return true;
}
N
class MouseEventHandler extends MouseAdapter {
О public void mousePressed(MouseEvent evt) {
requestFocus();
P }
Q
// Change background color to blue when focus is gained.
R class FocusEventHandler extends FocusAdapter {
public void focusCained(FocusEvent evt) {
S hasFocus = true;
repai nt О;
T }
public void focusLost(FocusEvent evt) {
L' hasFocus = false;
repaintO ;
V }
}
w
public void paint(Graphics g) {
X if (hasFocus) {
setBackground(Color.blue);
Y } else {
setBackground(Color.white);
Z }
}
1
352
isShowii
feShowing()
PURPOSE Determines if this component is visible and showing on the screen.
SYNTAX public boolean isShowingO
description This method is used to determine if this component is visible on the screen. A component can be “visible" even though it doesn't appear on the screen. How- ever. if this component's visible state is true and this component has a peer, this component will appear on the screen.
returns true if this component is visible and has a peen
SEE ALSO isVisibleO , setVi si ble().
isValidO
PURPOSE Retrieves this component s valid state.
SYNTAX public boolean isValidO
DESCRIPTION Each component maintains a valid state to indicate whether it needs to be re- laid out by the layout manager. See the class description and the validateO method for more details about the valid state.
RETURNS true if this component is valid; false otherwise.
SEE ALSO invalidateO. validateO.
EXAMPLE See validateO-
is Visi ble()
PURPOSE Retrieves this component's visible state.
SYNTAX public boolean isVisibleO
description By default, most components are created visible. Top level windows such as frames are created invisible.
RETURNS true if this component is visible; fal se otherwise.
SEE A [.SO isShowingO, setVisibleO-
example See setVisibleO.
java.awt
Component
key Dow n()
keyDown() DEPRECATED
PURPOSE Use the KeyLi stener interface instead.
SYNTAX public boolean keyDown(Event evt, int key)
PARAMFI FRS evt key The non-nul 1 event. The key that was pressed.
RET I R\S fal se il the event should be passed up to this component's parent: true other- wise.
DEPRECATION Formerly; this component would override this method to handle events fired when the user presses a key. import java.awt.*; class Old extends Frame { TextArea ta = new TextArea(10, 40); 01d() { super(“Deprecated key example”); add(tat Borderlayout.CFN1FR); pack(); show О; } public boolean keyDown(Event evt, int key) { if (evt .target ta) { System.out.println(“Pressed: “ + (char)key); return true; } return false; } public boolean keyUp(Event evt, int key) { if (evt.target == ta) { System, out. pri ntl n(‘‘Released: ” + (char)key); return true; } return false; } static public void mai n(St ri nq[] args) { new 01d(); } } Replace the usage of the deprecated methods keyllpO and keyDown() by defining a KeyLi stener and adding it as a listener for this component. import java.awt.*; import java, awt. event.; class New extends Frame { TextArea ta - new TextArea(10, 40); NewO { super(“New KeyEvent example”); add(ta, BorderLayout.CENTER); ta.addKeyLi stener(new KeyEventHandler()); pac:k();
354
key I pt
showQ; } class KeyEventHandler implements Keylistener { public void keyTypedfKeyEvent evt) { System.out .println(‘Typed: “ + evt. getKeyCharQ) ; } public void keyPressed(KeyFvent evt) { System.out.pri ntln(,kPressed: “ + evt.getKeyCharQ); } public void keyReleased(Keytvent evt) { System, out. pri nt 1 nQRel eased: “ * evt.getKeyCharQ); } } static public void main(String[] args) { new NewQ; } }
SEE ALSO addKeyListenerQ, AWTFvent, java.awt.event.KeyAdapter, java.awt.event.KeyEvent, processKeyEventО, removeKeyListenerQ.
keyUpO DEPRECATED
PURPOSE Use the Keylistener interface instead.
SYNTAX public boolean keyllp(Fvent evt, int key)
PARAMETERS evt key The non-null event. The key that was released.
RETURNS fal se if the event should be passed up to this component’s parent; true other- wise.
DEPREX'A'I ION See keyDownQ for an example of how to replace the usage of this deprecated method.
see: also addKeyLi stenerQ, AWTEvent, java.awt.event.KeyAdapterr java.awt.event.KeyEvent, processKeyEventQ, removeKeyListenerQ.
layoutf) DEPRECATED
purpose: Replaced by doLayoutQ.
SYNTAX public void layoutQ
OEPRECA'I ION Replace the usage of this deprecated method, as in layout Q; with dolayoutО;
java.awt
Component
LEFT_A1JGNMENT
LEFT ALIGNMENT
Pl RPOSL Constant indicating alignment along a component's left edge.
SYNTAX public static final float LEFT-ALIGNMENT
A DESCRIP 1 ION This constant specifies that the л-coordinate of the component s alignment
В point be at the component's left edge. Its value is 0.0f.
Si r- ALSO CENTER ALIGNMENT, getAl1gnmentXO, RIGHT.ALIGNMENI.
D I X AMPLE See the I ayoutManager2 class example.
E
E list()
Ci
u Pl RPOSE-1 Prints out information about this component.
SVNI AX public void list()
1 public void 1ist(Printstream out)
J public void 1ist(PrintStream out, int indent)
public void 1ist(PrintWriter outwriter)
К public void 1ist(PrintWriter outwriter, int indent)
L DESCRIPTION 'This method prints the results of calling toString() to the print stream out
M or print writer outwri ter.
If this component is a container, this method recursively prints the results of
N calling toStringO on each of the container's descendants. The component
О hierarchy is traversed in depth-first order. Children that are further down the
p hierarchy are printed with more indents. The first line of output is printed with
indent spaces.
Q If neither out nor outwriter is specified, it defaults to Sy stem. out. If
R i ndent is not specified, it defaults to 0.
S PARA METERS
T i ndent The indentation of the first line of output.
out The non-nul 1 output stream in which to print.
L’ outwri ter I'he non-nul 1 output writer in which to print.
V SEE Al SO java.io.Printstream, java.io.PrintWriter, java,1ang.System.out,
W toStringO.
X EXAMPLE- See Contai ner. 1 i stO.
Y
Z locate() DEPRECATED
Pl RPOSL Replaced by getComponentAt().
356
locatior
SYNTAX PARAMET prs X У public Component locatefint x, int y) The л-coordinate relative to this component's bounds. The v-coordinate relative to this component's bounds.
returns The subcomponent at x. у or this component itself if no component is at x. у but x, у is in this component. Returns null if x. у is not in this component.
deprecation Replace the usage of this deprecated method, as in Component comp = locatefx, y); with Component comp - getComponentAt(x, y);
locationf) DEPRECATED
PURPOSE Replaced by getLocationO,
SYNTAX public Point locationO
RETURNS A new non-null point containing this component's location relative to this component's parent.
DEPRECATION Replace the usage of this deprecated method, as in Point pt = locationf); with Point pt getLocationf);
lOStF OCUS( ) DEPRECA TED
PURPOSE Use the FocusListener interface instead.
SYNTAX public boolean lostfocusfEvent evt» Object arg)
parameters arg evt An object whose contents depend on the component that Tired (he event. The non-null event.
RETURNS false if the event should be passed up to this component's parent: true other- wise.
DEPRECATION See gotFocusO for an example of how to replace usage of lostFocusf) using FocusListener.
SEE ALSO java.awt.event.FocusAdapter, java.awt.event.FocusEvent , processFocusEvent0-
java.awt
Component
minimumSizct)
minimumSize()
DEPRECATED
Pl RPOSL SYNTAX Replaced by getMi nimumSize(). public Dimension minimumSize()
A R HUR NS A new non null dimension object containing this component's minimum size.
[J DEIPREX'AI'ION Replace the usage of this deprecated method, as in Dimension min = minimumSize();
D with
E Dimension mi n = getMi nimumSizeO ;
F mouseDown() depkei a ied
G
H Pl RPOSI Use Mousel i stener interface instead.
f I SYNTAX PARAMETERS public boolean mouseDown(Event evt, int x, int y)
j evt The non null event.
К X The л-coordinate of the cursor relative to this component's bounds at the lime
L of the mouse event.
M У The y-coordinale of the cursor relative to this component’s bounds at the time
of the mouse event.
N RETURNS fal se if the event should be passed up to this component s parent: true other-
О wise.
P DEPRECA'I ION Formerly, this component would override mouseDown(), mouseUp().
Q R mouseExitQ. and mouseEnterO to handle events fired when the u>er presses a mouse button. import java.awt.*;
S class Old extends Frame { Old О {
1 super(“Deprecated Mouse Events example”); setSize(100, S0) ;
L show();
V public boolean mouseEnter(Fvent evt, int x, int y) { System.out. println(‘‘Mouse Enter(“ - x + “, ” 4 у +
W return true; 1
X j public boolean mouseExit(E-vent evt, int x, int y) { System, out. printlnC'Mouse Exit(“ + x + “, ” 1 у + “)’*);
V return true;
z public boolean mouseDown(Fvent evt, int x, int y) { System.out.println(“Mouse Down(‘‘ + x + ” ," 4 у * return true; }
358
IclVil.itWl
SEE ALSO
mouseDnigt
public boolean TouseUp(Event evt, int x, int y) {
System.out. print ln(,lMouse Up(“ * x + “+ у ♦
return true;
}
public static void mai n(Stri ngLJ args) {
new 01d();
}
}
Replace the usage of these deprecated methods by defining a MouseLi stener
and then adding it as a listener for the component’s mouse events.
import java.awt.*;
import java.awt.event.*;
class New extends Frame {
NewO {
super("New MouseFvent example");
setSize(100, 50);
thi s.addMouseli stener(new MouseEventHandler());
show();
}
class MouseEventHandler implements MouseListener {
public void rrouseEntered(MouseEvent evt) {
System. out. pri ntl n ("Mouse Enter(" + evt.getXO * +
evt.getYO + V);
}
public void mouseFxited(MouseEvent evt) {
System, out. pri ntl n(“Mouse Fxit(“ + evt.getXO + " ,*
evt.getYO + “)”);
}
public void mousePressed(MouseFvent evt) {
System, out. pri nt ln(“Mouse Down(" ♦ evt.getXO i- *
evt.getYO * “)”);
}
public void mouseReleased(MouseEvent evt) {
System.out.println(“Mouse UpC + evt.getXO + *
evt.getYO * “)’’);
}
public void mousedicked(MouseEvent evt) {
System.out.println(“Mouse Clickedf" + evt.getXO + *
evt.getYO + “)’'):
1
}
public static void Tain(String[] args) {
new NewO ;
}
}
addMouseListenerО, java.awt.event.MouseAdapter,
java.awt.event.MouseEvent, processMouseEventO,
removeMouseLi stenerО.
mouseDragf)
DEPKECAIED
PURPOSE
I’se the MouseMotionLi stener interface instead.
Component
mouseDrag()
java.awt
SY VI AX public boolean mouseDrag(Event evt, int x, int y)
PARAMI 11 RS
evt The non-nul 1 event.
X The л-coordinate of the cursor relative to this component's bounds at the lime of the mouse event.
У The v-uoordinate of the cursor relative to this component s bounds at the time of the mouse event.
RIJ-I RNS fal se if the e\ent should be passed up to this components parent; true other- wise.
DEPRECATION. Formerly, this component overrode mouseDragO and mouseMoveQ to handle e\cnts fired when the user drags the mouse as a mouse button is held down. import java.awt."; class Old extends Frame { Old 0 { super(“Deprecated Mouse Motion Events example”); setSize(100, 50); show() ; J public boolean mouseDrag(Event evt, int x, int y) { System.out.println(“Mouse Drag(“ 4 x * + у ♦ “)”); return true; } public boolean mouseMove(Event evt, int x, int y) { System.out.println(“Mouse Move('* 4 x + 4- у + “)”); return true; 1 public static void main(String[2 args) { new 01d(); } }
Replace the usage of these deprecated methods by defining a MouseMotion-
Li stener and adding it as a listener for this component’s mouse motion
events,
import java.awt.-;
import java,awt.event.*;
class New extends Frame {
New() {
super('*New Mouse related MouseEvent example”);
setSize(100, 50):
this.addMouseMotionLi stener(new MouseMotionEventHandl er ());
showO;
}
class MouseMotionEventHandler implements MouseMotionlistener {
public void mouseDragged(Mouselvent evt) {
System.out.println("Mouse DraggedC* + evt.getXQ + 4
evt.getY() ч-
}
public void mouseMoved(MouseFvent evt) {
360
JUVU.ilWl
mouse Erne
System.out.println(“Mouse Moved(“ * evt.getXQ + 4-
evt .getYQ + “)”);
}
}
public static void main(Stringn args) {
new New();
}
}
SBEalso addMouseMotionListenerО» java.awt.event.MouseMotionAdapter,
java.awt.event.MouseEvent,processMouseMot ionEvent(),
removeMouseMotionListener().
mouseEnter() deprecated
PURPOSE Use the MouseLi stener interface instead.
SYNTAX public boolean mouseEnter(Event evt, int x, int y)
PARAMETERS evt The non-nul 1 event.
X The л-coordinate of the cursor relative to this component’s bounds at the time of the mouse event.
У The у-coordinate of the cursor relative to this component's bounds al the time of the mouse event.
RETURNS fal se if the event should be passed up to this component’s parent; true other- wise.
DEPRECATION- See mouseDownO for an example of how to replace deprecated usage of this method.
SEE ALSO addMouselistenerQ, java.awt.event.MouseAdapter, java.awt.event.MouseEvent, processMouseEventO, removeMouseLi stener().
DEPRECATED
mouseExitf)
purpose Use the MouseLi stener interface instead.
syntax public boolean mouseExit(Event evt, int x, int y)
PARAMETERS
evt rhe non nul 1 event.
X 'Fhe л-coordinate of the cursor relative to this component’s bounds at the time of the mouse event.
У The у-coordinate of the cursor relative to this component’s bounds at the time of the mouse event.
Component
mouse Mo vet)
java.awt
returns fal se if the event should be passed up to this component's parent: true other-
wise.
de-pruu.x no\ See mouseDownO tor an example of how to replace deprecated usage of tins
method.
see also addMousetistener(), java.awt.event.MouseAdapter,
java.awt.event.Mousetventt processMouseFventO.
removeMouseLi stenerC).
mouseMove()
DEPRECATE!)
I purpose-: Use the MouseMotionl i stener interface instead.
G S'! M AX public boolean mouseMoveCEvent evt, int x, int y)
H PARAMETERS
evt The non-nul 1 event.
I X The v-coordinate of the cursor relathe to this component's bounds at the time
.1 of the mouse event.
К 1 У I'he v-coordinate of the cursor relathe to this component's bounds at the time of the mouse event.
RETURNS fal se if the event should be passed up to this component s parent: true other-
M wise.
N DEPRLCXI ION See mouseDragO for an example of how to replace deprecated usage of this
() method.
P SEE ALSO addMouseMotionLiStenerQ , java.awt.event.MouseMotionAdapter, java.awt-event.MouseEvent, processMouseMotionEventO,
Q remove.MouseMot ionLi stener ().
R
S mouselJp() DEPRECATED
T PLRPOSb I’se the MouseLi stener interface instead.
r SYN1A\ public boolean mouseUpftvent evt, int x, int y)
V PA R AMI H RS
w evt l he non-nul 1 e\ent.
X X I'he r-coordinate of the cursor relative to this component's bounds at the time of the mouse event.
Y У The у-coordinate of the cursor relative to this component's bounds at the lime
7. of the mouse event.
RE rt'RNS false if the exent should be passed up to this components parent: true other- wise.
362
mo
deprecation See mouseDownO for an example of how to replace deprecated usage of this method.
SEE ALSO addMouseLi stenerO, java.awt.event.MouseAdapter, java. awt. event . v>ou set vent r processvouseEvent() , remove^ouseLi stenerO .
moveO DEPRECATED
purpose: Replaced by setLocationO. syntax public void move(int x, int y) PARAMETERS x The new ^coordinate. у The new y-coordinaie. deprecation Replace the usage of this deprecated method, as in movefx, y); with setLocation(x, y);
DEPRECATED
nextFocus()
purpose Replaced by transferFocusQ.
syntax public void nextFocusC)
deprecation Replace the usage of this deprecated method, as in nextFocusO; with transferFocusQ ;.
paint()
PURPOSE Called to repaint this component.
syntax public void paint(Graphics gc)
description This method should be overridden if this component wishes to paint, h will be called by the AWT system whenever it detects that some area has been dam- aged and needs to be repainted. The graphics context gc should be used to repaint the damaged area. This method is similar to update0. except that the system automatically clears the damaged area with this component's back- ground color before calling pai nt O: the damaged area is not cleared when
Component
a\ a.aw l
paintAII()
update() is called. Sec the class description on “Painting" tor more informa-
tion.
The damaged area is not necessarily the whole area ol this component. To dis-
cover the damaged area, call gc. getCl i pBounds(). Note that w hen this com-
ponent is made larger, the clipping area may only include the new area. If by
enlarging this component some other part of the component changes and needs
to be repainted, a call to repaint() must be made so that the area can be
repainted.
If this is a native component, three properties of gc are initialized with values
taken from the same three properties of this component. 1'he properties ate the
background color, the foreground color, and the font.
PARAMLTl RS
gc The non-nul 1 graphics context in which to paint this component.
si-i: also getBackgroundO. repaintf). updateQ.
r.XAxiPi r Sec createlmagef).
paintAllf)
PURPOSt
SYM \.\
1)1 SCRIP! I()\
Cal led to repaint this component and its descendants,
public void paintAl1(Graphics gc)
This method should be over-
ridden if a component
wishes to paint. This method
will be called by the AWT
system in response to a
request to paint all visible
descendants of this compo-
nent. If this method is over-
ridden. this component
should paint itself on the
graphics context gc and
then, if this component is a
container. invoke the
pai ntAl 1 () method on all
of its children.
* printA.ll Example
Paint Preview I [Print Preview
item 0
item 1
I IGI RI 88: Paint and Print Previewer's
Control Panel.
method, by' default, calls cither paintf) (if this component is a lightweight
component) or its peer's paint() method (if this is a native component).
364
paintАП(
PARAMETERS
g<=
SHE ALSO
example
The non-nul1 graphics context in which to paint this component and its
descendants.
pai ntQ-
This example demonstrates how to implement a paint or print pre viewer for a
frame using paintAllO and printAllQ- The example frame contains a
number of miscellaneous components (see Figure 88). If the user clicks the
button labeled Paint Preview, an off-screen image is created and all of the
frame contents are painted to the image. The image is then displayed in a sepa-
rate viewer. If Print Preview is pressed, the frame contents are printed to the
off-screen image and then displayed in the viewer (Figure 89).
Note that the results are
not necessarily identical
to what’s displayed on the
screen. In particular, the
borders around the frame
and native components
are not painted or printed.
This will get better over
time.
Note: In Java 1.1.2. Con
tainer.paintCompo-
nentsO contains a bug.
so the viewer created by
the PrintPreview button
will not show any native
components.
»Viewer
Pairrt Preview | [Рг1ЙРгей»ч1
item 0
item 1 r----i
j item 0
TextField
I- Checkbox
FIGURE 89: Paint and Print Previe wen
import java.awt.*;
import java.awt.event;
class Main extends Frame implements Act iont istener {
Main() {
superC'pri ntAl 1 Example”);
// Create the paint and print buttons and listen for events.
Button b =- new Button(“Paint Preview”);
b.addActionLi stener(th i $);
add(b);
b = new ButtonC'Trint Preview”);
b.addActionlistenerCthi s);
add(b);
// Now create and add a bunch of miscellaneous components
// in no particular order.
List 1 - new List();
java.awt
Component
paintAIK)
1.addltem("item 0");
1.addltem(“i tem 1”);
add(l);
Choice ch = new ChoiceO;
ch.addltem(”iterr 0”);
ch. addltemC'i tem 1”);
add(ch);
add (new Text Field (’‘Text Field’’));
Panel p = new Panel (new FlowLayout ()) ;
p.add(new Checkbox("Checkbox”));
// Add a lightweight component.
p.addfnew ImageComponentC'duke.gif”));
add(p);
// Layout and show.
set!ayout(new FlowLayout());
pack();
showQ ;
}
// Color just the inset area.
public void paint(Graphics g) {
Insets insets = getlnsetsQ;
g.setColor(Color.1i ghtCray);
g.fi11Rect (insets.left T inset s.top,
getSizeО.width insets,left-insets.right,
getSi zeО.height-insets.top-i nsets.bottom);
// Don’t forget to paint the lightweights.
super.paint(g);
public void actionPerformed(ActionEvent evt) {
// Create an off-screen image and a graphics context on it.
Image image - create!mage(getSize().width, getSizeO . height) ;
Graphics g = image.getCraphics();
// A workaround for a clipping bug in
// Contai nor. pai ntComponentsO and Contai ner. pri ntComponentsQ .
g.setClip(0, 0, Short.MAX VAIUE, Short.MAX .VAI UE);
// Paint or print the components in the graphics context.
if (evt .getActionCommandO - equal s(“Paint Preview”)) {
pai ntAll(g);
// The following is almost the same except that the frame’s
// paint() method is not be called.
//pai ntComponents(g);
// The following only invokes the paint() method of the frame
// and any lightweight children.
//paint(g);
// Create the viewer to see the results.
new Previewer(image, “Paint");
} else if (evt.getActionCommandO .equals("Print Preview”)) {
printAl1(g);
// The following is almost the same except that the frame’s
366
ptiimAII'
// print О method is not be called,
//pri ntComponents(g);
// The following only invokes the printO method of the frame
// and any lightweight children.
//print(g);
// Create the viewer to see the results,
new Previewer(image, “Print”);
}
g .di sposeO;
}
public static void main(String[j args) {
new Mai n();
}
}
class ImageComponent extends Component {
Image image;
ImageComponent(String filename) {
image - getToolkit().getlmage(filenane);
// Load the image with a media tracker because
// we need the dimensions immediately.
MediaTracker tracker - new MediaTracker(this);
try {
tracker,addlmage(image, 0);
tracker.wai tForAl1(0);
} catch (Exception e) {
e.pri ntStacklrace();
}
}
public Dimension getPreferredSizeO {
return new Dimension^mage.getwidth(nu)1), image.getHeight(nul1));
}
public void paint(Graphics g) {
g.drawlmage(image, 0t 0, this);
}
}
class Previewer extends Frame {
Image image;
Previewer(Image image, String title) {
super(title + “ Viewer'1);
int w - image.getwidth(nul1);
int h ~ image.getHeight(nul1);
this.image = image;
// This call creates the frame’s peers.
// Without this call, getlnsetsC) will return invalid values.
addNoti fyО;
// When the frame's insets.
Insets insets = getlnsetsO:
Component
paramString()
java.awt
1)
E
Г
G
H
J
К
L
M
N
G
P
Q
R
T
I’
V
W
X
Y
Z
// Adjust the dimensions of the frame to account for the insets,
w insets.left + insets.right;
h ^-= insets, top + insets .bottom;
// Size and show the viewer.
setSize(w, h);
showO ;
// Shows the image.
public void paint(Graphics q) {
Insets insets = getlnsetsO;
g.drawlmage(image, insets.left, insets.top, this);
}
}
paramString()
Pl RPOSL
SYNTAX
PLSCRIP I ION
RETI’RNS
SI.I ALSO
EX AM PI E
Generates a siring representation of this component’s state.
protected String paramStringQ
The default string representation of a component consists of its name, a- and y-
coordinates, width, height, and whether it is valid, hidden, or enabled.
A subclass of this class should override this method and return a concatenation
of its state with the results of super.paramString(). This method is called
by the toStri ng О method and is typically used for debugging.
A non-nul 1 string representing this component's state.
toStri ng()
This example shows how a subclass should override the paramString()
method. The override appends three extra pieces of state to the superclass’s
state.
myBool - false;
boolean
int mylnt = 59;
String myStr ’'Testing”;
protected String paramString() {
String str - super.paramStringO :
str += ", myBool =’’ + myBool;
str '\mylnt-'’ + mylnt;
if (myStr != null) {
str +- " ,myStr=” + myStr;
}
return str;
}
36»
postlivenU'
DEPRECATED
PURPOSE Replaced by dispatchEventO.
SYNTAX public boolean postEvent(Event evt)
parameters evt The nun-null event.
returns false if the event should be passed up to this component's parent: true other- wise.
deprecation Replace the usage of this deprecated method, as in postEvent(evt); with dispatchEvent(awtEvt);
SEE ALSO AWTEvent.
preferredSizef) deprecated
PURPOSE Replaced by getPreferredSizeO.
SYNTAX public Dimension preferredSize()
RETURNS A non-nul 1 dimension object containing this component's preferred si/e.
deprecation Replace the usage of this deprecated method, as in Dimension ps preferredSizeO ; with Dimension ps = getPreferredSizeO ;
preparelmagef)
PURPOSE Triggers the loading of image data for an image.
SYNTAX public boolean preparelmage(lmage img, Imageobserver obs) public boolean preparelmage(lmage img, int w, int h, TmageObserver obs)
DESCRIPTION This method starts the loading or production of image data associated with image img or a scaled version of img. If w and h are 1. no scaling of img is done. If w and h are non-negative, img is loaded and scaled so that its width is w and its height is h. The image observer obs will receive image update notifi- cations as the image is being loaded or produced.
Component
printf)
java.awt
This method is typically used to preload image data lor an image or a scaled
version of an image so that Graphi cs. drawlmage() can operate as quickh as
possible.
If w and h are not specified, they default to -1. that is. the image should not be
scaled.
PARAMETERS
h 1 or the scaled height of the returned image in pixels.
img 'lhe non-nul 1 image to load.
obs The non-null image observer.
E w -1 or the scaled width of the returned image in pixels.
Г RETURNS true if all of the image data for img is available: false otherwise
G SF.F Al SO java.awt.image.ImageObserver.
li EXAMPI F. See checkimage0.
1 print()
к
pi rpost. Prints this component on a graphics context.
L
svmax public void pri nt (Graphi cs gc)
M
discriptiox By default, this method calls paint(gc). It this component does not look lhe
N same when it is displayed on the screen and when it is printed, this method
О should be overridden to render the printed appearance of this component.
p PARAMETERS
gc The non-null graphics context on which to print.
see also pai nt О , printAHO, Pri nt lob.
R
example See pai nt Al 1 ().
S
T
и print All()
V PURPOSE Prints this component and its descendants on a graphics context.
w SV M AX public void printAl1(Graphics gc)
X DI-SCRIPTIOX This method prints this component and its descendants on the graphics context
Y gc. If a component is a container, this component is first validated and then it
z PARAM! IE RS gc and all of its descendants are also printed on gc. The non-nul 1 graphics context on which to print.
370
processComponent Eve
SEE also Container .printComponentsO , printO, validateO-
example See paintAl1().
processComponentEvent()
PURPOSE Processes a component event enabled for this component.
SYNTAX protected void processComponentEvent(ComponentEvent evt)
DESCRIPT ION Component events are fired when this component is resized, moved, or made visible or invisible. See ComponentEvent for more details. This method pro- cesses component events for this component by calling any registered ComponentLi stener. This method is invoked only if component events have been enabled for this component. This can happen either when a component listener is added to this component or when component events are explicitly enabled via the use ofenableEvents(). Typically, a component controls how its component events are processed. It does this by adding or removing component listeners, h overrides process- ComponentEventO only if it needs to do processing in addition to that per formed by the registered listeners. When a component does override processComponentEventQ. it should call super.processComponentEventQ to perform the processing intended by its base class (such as dispatching the listeners).
PARAMEI ERS evt The non-nul 1 component event.
SEE ALSO addComponentLi stenerQ , enableFventsO , di sableEventsQ , java.awt.event.ComponentAdapter, java,awt.event.ComponentLvent, java.awt.event.ComponentIistener, processEvent(), removeComponentLi stenerQ.
EXAMPLE See AWTEventMulti caster.componentHi ddenQ
processEvent()
purpose Processes an event enabled for this component.
syntax protected void processEventfAWTEvent evt)
description This method is called to deliver the event evt to this component. Depending
on the class of evt, this method calls another method in this class. For exam-
ple, if evt is an instance of ComponentEvent, this component's processCom-
ponentEvent() method is called with evt. The event types handled by
Component
processEventt)
java.awt
default are ComponentEvent, FocusEvent, KeyEvent. and MouseEvent (a
MouseEvent is handled either by processMouseEventO or processMouse-
Moci onEvent О )
This method is invoked only if evt is an event type that has been enabled for
this component. This can happen either when a listener of that type is added to
this component or when the event type is explicitly enabled via the use of
enableEventsO.
Typically, a component controls how its events are processed by adding or
removing the appropriate listeners. It overrides processEvent() only if it
needs to handle other types of events in addition to the four basic types. If a
component needs to perform special processing for one of the four basic types,
it should override one of the type-specific methods, such as processCompo-
nentEventQ-
When a component does override processEventO. it should call
super. processEventO to perform the processing intended by its base class
(such as dispatching the listeners for the five basic event types).
PARAMETERS
evt The non-nul 1 event.
SEE ALSO addComponent I i stenerO , addFocusListenerO , addKeyl i stenerO f addMouseLi stenerO , addMouseMot! onl i stenerO , enableEventsO, disabletventsO , processComponentFventO , processFocusFvent () , processKeyEventO, processMouseEventO , processMouseMotionEvent(), removecomponent1i stenerO. removeFocusl i stenerO t removeKeyLi stenerO , removeMouseLi stenerO t removeMouseMotionL i stenerO.
EXAMPLE This example creates a subclass of “11 List—Mai nLi st--that overrides pro- НнйЯННВЙЯвН|ВЛ|вИ£1 cessEventO to print debugging infor- litem 0 mation about the events received by the , .. c hem 2 i ist. See Figure 90. |m For other examples of processEventO. Г see the class example and dispatch- n — Event О. FIGI RE 90: Debugging Events Using processEventO.
import import java.awt.-; java. awt . event. ••;
class Main extends Frame {
public static void main(String argsfl) {
Frame f = new Frame(“processEvent Example");
Maint ist 1 - new Maini ist(4, true);
for (int i=0; i<4; i++) {
1 .additem(,litern “+i);
372
processFocusEv
}
f.add(l, BorderLayout.CENTER);
f.pack();
f.show();
}
class MainList extends List {
public MainList(int rows, boolean multipl eMode) {
super(rows, multi pl eMode);
enableEvents(-l); // Enable all events.
}
protected void processEvent(AWTEvent evt) {
int id = evt.getIDO ;
if (id >= ActionEvent.ACTION-FIRST && id <= ActionEvent.ACTION-LAST) {
System.out.println(“action eventC'+id+”)");
} else if (id >= AdjustmentEvent.ADJUSTMENT-FIRST
&& id <- AdjustmentEvent.ADJUSTMENT-LAST) {
System.out.println(“adjustment event(“+id+”)”);
} else if (id >= ComponentEvent.COMPONENT_FIRST &&
id <- ComponentEvent.COMPONENT-LAST) {
System.out.println(“component event(“+id+”)“);
} else if (id >= ContainerFvent.CONTAINER-FIRST &&
id <= ContainerEvent.CONTAINER-LAST) {
System.out.println(“container event(“+id+”)”);
} else if (id >= WindowEvent.WINDOW-FIRST &&
id <= WindowEvent.WINDOW-LAST) {
System.out.println(“window event(“+id+“)”);
} else if (id >= FocusEvent.FOCUS-FIRST &&
id <= FocusEvent.FOCUS-LAST) {
System.out.println(“focus event(“+id+”)’*);
} else if (id >= ItemEvent.ITEM-FIRST && id <= ItemEvent.ITEM.LAST) {
System.out.printlnC'item event”+id+'’)“) ;
} else if (id >- KeyEvent.KEY-FIRST && id <= KeyEvent.KEY.LAST) {
System.out.printin(“key event”+id+“)”);
} else if (id >= MouseEvent.MOUSE-FIRST &&
id <= MouseEvent.MOUSE-LAST) {
System.out.println(“mouse event”+id+")");
} else if (id >= TextEvent.TEXT-FIRST && id <= TextEvent.TEXT_LAST) {
System.out. pri nt In (“text event ” + id+H) ;
}
super.processEvent(evt);
}
processFocusEvent()
purpose Processes a focus event enabled for this component.
syntax protected void processFocusFvent(FocusEvent evt)
Component
processKeytvenu )
java.aw I
DFsCklPIIOX A component fires focus events when it gains or loses keyboard focus. See FocusEvent for more details. This method processes focus events foi this component by delivering them to any registered listeners. This method is invoked only if focus events have been enabled for this component. This can happen either when a focus listener is added to this component or when focus events are explicitly enabled via the use of enableEvents0 Typically; a component controls how its focus events are processed by adding or removing focus listeners. It overrides processFocusFvent О only if it needs to do processing in addition to that performed by the registered listeners. When a component does override processFocusEvent0. it should call super. processFocusEventO to perform lhe processing intended by its base class (such as dispatching the listeners).
PARAMETERS evt I’he non-null focus event.
SEI ALSO addFocusLi stenerO, enableEventsO, disableEventsO , java.awt.event.FocusAdapter, java.awt.event.FocusEvent, java.awt.event.FocusLi stener, processEvent О т removeTocusListenerO.
EXAMPLE See AWT EventMulti caster.focusGai nedО
processKeyEvent()
PURPOSE Processes a key event enabled for this component.
SV X 1 AX protected void processKeyEvent(KeyEvent evt)
DISC RIPOOX Key events are fired when a key has been pressed, or released in a component. See KeyEvent for more details. This method processes key events for this component by calling any registered Key Li stener. This method is invoked only if key events have been enabled for this component. This can happen either when a key listener is added to this component or when key events are explicitly enabled via the use of enableEventsO. Typically, a component controls how its key events are processed by adding or removing key listeners. It overrides processKeyFvent () only if it needs to do processing in addition to that performed by the registered listeners. When a component does override processKeyEvent(). it should call super. processKeyEventO to perform the processing intended by its base class (such as dispatching the listeners).
PAR AM El ERS evt The non-null key event.
374
proce ss М о и se Е v<
SEEALSO addKeyListenerO , enableEventsO, di sableEventsO,
java.awt.event.KeyAdapter, java.awt.event.KeyEvent,
java.awt.event.KeyLi stener, processEvent(), removeKeyL i stenerO.
example See AWTEventMulticaster. keyPressedO.
processMouseEvent()
PURPOSE Processes a mouse event enabled for this component.
SYNTAX protected void processMouseEvent(MouseFvent evt)
description Mouse events are fired when the mouse enters or exits a component or when a mouse button has been pressed, or released on a component. See MouseEvent for more details. This method processes mouse events for this component by calling any registered MouseLi stener. This method is invoked only if mouse events have been enabled for this component. This can happen either when a mouse listener is added to this component or when mouse events are explicitly enabled via the use of enabl eEvents Q. Typically, a component controls how its mouse events are processed by adding or removing mouse listeners. It overrides processMouseEvent0 only if it needs to do processing in addition to that performed by the registered listeners. When a component does override processMouseEventО, it should call super. processMouseEventО to perform the processing intended by its base class (such as dispatching the listeners).
PARAMETERS evt The non-nul 1 mouse event.
SEE ALSO addMouseLi stenerO , enableEventsO , di sabl eEvents О , java.awt.event.MouseAdapter, java.awt.event.MouseEvent, java.awt.event.MouseListener, processEventO, removeMouseLi stenerO ,
EXAMPLE See add().
processMouseMotionEvent()
purpose Processes a mouse motion event enabled for this component.
syntax protected void processMouseMotionEvent(MouseEvent e)
description Mouse motion events are fired when the mouse has been moved or dragged.
See MouseFvent for more details. This method processes mouse motion
events for this component by calling any registered MouseMotionLi stener.
java.awt
Component
removef)
This method is invoked only if mouse motion events have been enabled for
this component. This can happen either when a mouse motion listener is added
to this component or when mouse motion events are explicitly enabled via the
use of enabl eEvents О
Л Typically, a component controls how its mouse motion events are processed by
в adding or removing mouse motion listeners. It overrides processMouse-
MorionEventQ only if it needs to do processing in addition to that performed
by the registered listeners.
D When a component does override processMouseNloti onEvent (). it should
E call super.processMouseMotionEvent() to perform the processing
E intended by its base class (such as dispatching the listeners).
PARAMEI LRS
<j evt The non-nul1 mouse motion event.
H see also addMouseMotionListenerQ , enableEventsQ ♦ disableEventsQ,
1 java.awt.event.MouseEventT java.awt.event.MouseMotionAdapterT
java.awt.event,MouseMotionListener, processEventO,
J removeMouseMotionLi stenerQ.
К example See AWTEventMul ti caster .mouseDraggedQ.
L
M remove()
N o PVRPOSF. Removes a popup menu from this component.
p SYNIAX public synchronized void remove(MenuComponent popup)
DESCRIPTION A component can have a list of popup menus that can be dynamically dis-
Q played on the component. This method removes the popup menu popup from
R the list of popup menus for this component. If popup is not on the list, this
S method does nothing.
т PARAMETERS
popup The popup menu to remove.
и SEL Al SO PopupMenu, addQ.
V EiXAMPLt See add Q,
w
X
removeComponentListener()
PVRPOSE Removes a listener from receiving this component's component e\ents.
SYNTAX public synchronized void removeComponentLi stener(ComponentLi stener 1istener)
376
|<д v a.a w l
removeFocusListen
description /\ component fires component events when it is resized, moved, or made visi- ble or invisible. See ComponentEvent for more details. After this method is called, the component listener listener will no longer receive component events from this component. If 1 istener is null, this method does nothing.
parameters listener The possibly null component listener to remove.
SEE ALSO addComponent Li stenerO, java.awt.event.ComponentAdapter, java.awt.event.ComponentEvent, java.awt.event.ComponentLi stener.
example See removeActionListenerO in Menuitem.disableEventsO.
removeFocusListenerf)
purpose: Removes a listener from receiving this component's focus events.
SYNTAX public synchronized void removeFocusListener(Focustistener listener)
DESCRIPTION A component fires focus events when it gains or loses keyboard focus. See FocusEvent for more details. After this method is called, the focus listener listener will no longer receive focus events from this component. If listener is null, this method does nothing.
PARAMETERS listener The possibly null focus listener to remove.
SEE ALSO addFocusListenerO, java.awt.event.FocusAdapter, java.awt.event.FocusEvent, java.awt.event.FocusListener.
EXAMPLE See removeActionLi stenerO in Menuitem.disableEventsf).
removeKeyListenerf)
PURPOSE Removes a listener from receiving this component's key events.
SYNTAX public synchronized void removeKeyListener(KeyListener listener)
description Key events are tired when a key has been pressed, or released in a component. See KeyEvent for more details. After this method is called, the key listener listener will no longer receive key events from this component. If 1 istener is null, this method does nothing.
parameters 1i stener The possibly null key listener to remove.
java.awt
Component
reinoveMouseListenert )
SEI ALSO addKeylistenerO, java.awt.event,KeyAdapter, java.awt.event.KeyГvent, java.awt.event.KeyListener.
EX AM Pl .E See removeActionLi stenerO in Menuitem.disabletventsO.
removeMouseListener()
Pl RPOSL Removes a listener from receiving this component's mouse events.
SV XT.AX public synchronized void removeMouseListener(Mouse!istener 1i stener)
DLSCRIPHOX Mouse events are fired when tlie mouse enters or exits a component or when a mouse button has been pressed, or released on a component. See Mousetvent for more details. After this method is called, the mouse listener li stener will no longer receive mouse events from this component. If listener is null, this method does nothing.
PARAMETERS 1i stener 'I'he possibly null mouse listener to remove.
SEE Al SO addMouseListenerO. java.awt,event.MouseAdapter, java.awt.event.Mousefvent, java.awt.event.MouseListener.
EXAMPLE See removeActionListenerO in Menuitem.disableEvents().
removeMouseMotionListener{)
PERPOSE Removes a listener from receiving this component's mouse motion events.
SV XI AX public synchronized void addMouseMotionli stener(MouseMotionListener li stener)
DESCRIP HOX Mouse motion events are fired when the mouse has been moved or dragged. See MouseEvent for more details. After this method is called, the mouse motion listener listener will no longer receive mouse motion events from this component. If listener is null, this method does nothing.
PARAMEI ERS 1 i stener The possibly null mouse motion listener to add.
SEE ALSO addMouseMotionLislener(), java.awt.event.MouseMotionAdapter, java.awt.event.MouseEvent, java.awt.event.MouseMotionLi stener.
EXAMPL E Sec removeActionListenerf) in Menuitem.disableEventsO.
378
j«4vu.awi _______ ___________ — г ---
removeNoi
removeNotifyO _
PURPOSE Destroys this component's peer.
SYNTAX public void removeNotifyO
DESCRIPTION The default implementation of this method invokes removeNotifyO on any popup menus for this component. This method must be overridden by a com- ponent subclass in order to destroy the peer. This method can be called directly only if this component is a top-level window, such as a frame or dialog (see Wi ndow. addNoti f у О )
SEF.Al.SO addNotifyO. getPeerQ.
EXAMPLE See setVisibleQ.
repaint()
PURPOSE Makes a request to repaint this component.
SYNTAX public void repaintO public void repaintflong ms) public void repaintfint x, int y, int width, int height) public void repaintflong ms, int x, int y, int width, int height)
DESCRIPTION This method makes a request to repaint the rectangular area of this component specified by x, y, width, and height. If x, y. width, and height are not spec- ified, they default to the bounds of this component. The scheduled repaint will occur no later than ms milliseconds later. If ms is not specified, it defaults to 0. The AWT system will repaint this component by calling the updateO method.
PARAMETERS height ms width X У The height of the rectangular area to repaint. Maximum delay in milliseconds before the updateO method is called. The width of the rectangular area to repaint. The л-coordinate of the rectangular area to repaint. The у-coordinate of the rectangular area to repaint.
SEE ALSO updateO.
example This example paints various four-leaved roses and cardoids. As a figure is painted, a path of the figure is left behind. A thread is used to update (he loca- tion of the dot and then to invoke the repaint method to paint the dot every 50 ms. See Figure 91.
java.awt
Component
repaint! )
FIGI RE 91: Cardoids.
import java.awt.’'’;
import java. awt. event. ;
class Main extends Frame implements Runnable {
int curX = -100, curY = -100;
double newX, newY;
double angle = 0.0;
double maxX, maxY, minX, minY;
int figure;
boolean clearBg = true;
Main() {
super(“repaint Example”);
setSize(200, 200);
this.addMouseLi stener(new MouseEventHandl er О);
show() ;
(new Thread(thi s)). startO ;
}
public void update(Graphics g) {
int dotSize = 10;
Insets insets = getlnsetsC);
int x = insets.left, у = insets.top;
int w = getSize().width-insets.1eft-insets.right dotSize;
int h = getSize().height-insets.top-insets.bottom-dotSize;
if (clearBg) {
g.clearRect(x, y, getSize().width, getSize().height);
curX = curY = -100;
clearBg = false;
} else {
g. setColor(Col or.red);
g.fi1lOval(x+curX, y+curY, dotSize, dotSize);
g.setColor(Col or.black);
curX = (i nt) (newX’‘w) ;
curY = (int)(newY-h);
g.fi 11 Oval (x+curX, y+curY, dotSize, dotSize);
}
}
class MouseEventHandler extends MouseAdapter {
380
java.aw i
./Uiiipvuviai
req ues tPocusf
public void mousePressed(Mousetvent evt) {
figure++;
angle = 0;
clearBg - true;
}
double plot(double theta) {
switch (figure % 5) {
case 0:
maxX - .8; maxY = .8; minX - -.8; minY = -.8;
return Math.sin(2 * theta);
case 1:
maxX = 1; maxY = 1; minX = -1; minY = -1;
return Math.cos(2 * theta);
case 2:
maxX = 2; maxY = 2; minX = -1.3; minY = 2;
return Math.cos(theta/2) + 1;
case 3:
maxX = 3; maxY = 3; minX = -1.5; minY = -3;
return 2 * Math.cos(theta/2) + 1;
case 4:
maxX = 4; maxY = 4; minX = -2; minY = -4;
return 3 * Math.cos(theta/2) - 1;
}
return 0;
1
public void run() {
while (true) {
double r = plot(angle);
newX = (r * Math.cos(angle)-minX)/(maxX-minX);
newY = (r * Math.sin(angle)* minY)/(maxY-minY);
repaint();
try { Thread.sleep(50); } catch (Exception e) {};
angle += .2;
}
}
static public void main(String[J args) {
new MainО;
}
requestFocusO
PURPOSE Requests that the focus be given to this component.
SYNTAX public void requestFocusO
description This method requests that the focus be given to this component. If the request is granted, a focus event (see FocusEvent) will be posted to this component. The conditions under which a component is granted or denied the focus is plat - form-de pendent.
SEE ALSO i sFocusTraversable(), java.awt.event.Focustvent, processFocusEventO , transferFocus().
example See the class example, i sFocusTraversable().
java.awt
Component
reshape!)
reshape()
DEPRECATED
Pl RPOSL Replaced by setBoundsQ.
SYNTAX public void reshapefint x, int y, int w, int h)
A
PARAMETERS
в h The new height of this component in pixels.
w I he new width of this component in pixels.
X The new x-coordinate of this component in pixels.
и У The new у-coordinate of this component in pixels.
E DLPRH ATION Replace the usage of this deprecated method, as in
E reshapefx, y, w, h);
(; with
setBounds(x, y, w, h);
H
1 resize() DEPRECATED
J
К Pl RPOSL Replaced by setSizeQ.
S> STAX public void resize(int w, int h)
L public void resize(Dimension d)
M PARAMETERS
N d The non-nul 1 component dimension.
h The new height of this component in pixels.
w The new w idth of this component in pixels.
P DP PRECATION Replace the usage of this deprecated method, as in
Q resize(w, h);
resi ze(dimension);
R with
S setSize(w, h);
T setSize(dimension):
T
у RIGHT ALIGNMENT
w PURPOSE Constant indicating alignment along a component's right edge.
X SYNTAX public static final float RIGHT ALIGNMENT
Y DESCRIPTION This constant specifies that the r-coordinate of the component's alignment
7 point be at the component's right edge. Its value is 1.0f.
SEE A [.SO 1 EFT.ALTGNMENI, CFNTER_ALIGNMENT, getAlignmentXO.
EXAMPLE See the LayoutManager2 class example.
382
set В ас к gm u nd (1
setBackgrouncU)
purpose Sets this component's background color.
SYNTAX public void setBackground(Color c)
description This method sets this component's background color to c. 'The background
color affects each component differently. For example, a button is painted in
the background color, while its label is painted in the foreground color. See
Figure 92.
If c is null, this component will inherit its background color from the closest
ancestor whose background color has been set.
If this component is already displayed, the repaint() method must be called
to force this component to redraw itself using the new hackground color.
PARAMETERS
c The new background color, which can be nul 1.
SEE ALSO
EXAMPLE
getBackgroundQ,
setForegroundQ.
This method creates
a text area that has a
black background
and white fore-
ground. The white
foreground causes
the text to be painted
in white. Also, the
text area is set w ith a
very' large font.
set Background Example E3 '
Hey, this text a
is white I
on black!
4
FIGI RE *>2: White on Black Text /krea.
import java.awt.":
class Main extends Frame {
MainO {
super(“setBackground Example");
TextArea ta = new lextAreaQ;
ta.setBackground(Color.bl ack);
ta.setForeground(Color.white);
ta.setFont(new Font(“Monospaced", Font.BOLD. 30));
add(ta, BorderLayout.CENTER);
setSize(200, 200);
show();
}
static public void main(Strinq[] args) {
new MainO ;
}
}
Component
java.awt
serBounds()
setBounds()
purpose Moves and resizes this component.
SYNTAX
В
D
E
F
G
H
1
J
К
L
DESCRI? HON
parameters
h
rect
w
X
У
SEE ALSO
EXAMPLE
public void setBounds(int x, int y, int w, int h)
public void setBounds(Rectangle rect)
This first form of this method moves this component to position x. у and
resizes it to have width w and height h. x and у are relative to this component's
parent bounds. The second form of this method moves this component to the
position specified by the new bounding rectangle rect.
This method may be ignored if this component is embedded in an applet con-
text. See the Applet class for more information about applet contexts.
The new height of this component in pixels.
I'he new bounding rectangle.
The new width of this component in pixels.
The new л-coordinate of this component in pixels.
The new y-coordinate of this component in pixels.
getBoundsO, setLocation(). setSize().
See lhe Contai ner class example.
N
setCursor()
о----------------------------------------------------------------------------
p purpose Sets this component's cursor image.
q syntax public synchronized void setCursor(Cursor cursor)
R description This method sets the cursor image for this component to be cursor.
s parameters
cursor The non-null cursor image.
I
see also Cursor, getCursor().
example See the class example.
V
w
v setEnabled()
A __ ______________________________________________
Y purpose Enables or disables this component.
Z syntax public void setEnabled(boolean cond)
384
setFontf)
JdVd.clWl
DESCRIPTION If cond is true, this method enables this component; otherwise, it disables this component. When enabled, this component is able to respond to user input. When disabled, this component not only will not respond to user input, bin it also becomes transparent to user input. For example, if the user clicks a dis abled component, the AWT system determines the top-most enabled compo- nent that contains the cursor position and posts an event for that component. See the class description for more information about a component s enabled state.
PARAME'I LRS cond If true, this component is enabled; otherwise, this component is disabled.
SEB ALSO isLnabledQ.
EXAMPIT: See the Button class example.
setFontQ
PURPOSE Sets this component’s font.
SYNTAX public synchronized void setFontfFont f)
DESCRIPI ION If f is not nul 1. this method sets this component's font so that if this compo- nent paints any strings, it will paint them in the font f. Moreover, any graphics context that is created on this component will be initialized to f. If f is null, this component's font is cleared. This means that this compo- nents font will be inherited from the closest ancestor whose font has been set.
PARAMETERS f The font. This parameter can be null.
SEE ALSO getFontO.
EXAMPLE See the class example and di spatchEventO.
setForegroundf)
PURPOSE Sets this component s foreground color.
SYNTAX public void setForegroundCColor c)
DESCRIPTION This method sets this component's foreground color to c. The foreground color affects each component differently. For example, a button is painted in the background color, while its label is painted in the foreground color. If c is null, this component will inherit its foreground color from the closest ancestor whose foreground color has been set.
Component
setLocalc( I
ja\ a.awt
If this component is already displayed, repai nt () must be called io force this
component to redraw itself using the new foreground color.
PARAMETERS
c The new foreground color, which can be null.
see also getForegroundО. setBackgroundO-
exampi t See setBackgroundO.
setLocale()
pl rp()se Sets this component's locale.
svmax public void setLocaleG oca le locale)
di scriptiox This method sets the locale of this component to locale. See the class
description for more information on component locales. If locale is nul 1. this
component will use the locale of lhe closest ancestor that has been assigned a
locale. If no ancestor has been assigned a locale, this component's locale will
be Locale.getDefault().
PARAMETERS
locale The locale to use.
M see also java.uti1.Locale, getLocaleO.
N exampie See getNameO.
setLocationf)
Q PURPOSE Moves this component.
R S SAXTAX public void setLocationfint x, int y) public void setlocation(Point pt)
T u V w DESCRIPTION PARAMETERS This method moves this component such that its top-left corner coincides with lhe point specified by pt or x, у in the bounds of this component's parent. Note that unlike with graphics and events, whose coordinates are relative to a component's inset area, move coordinates are relative to a component's bounds.
X Pt The point of lhe new location.
Y X The new л-coordinatc.
Z У SEE ALSO EXAMPLE l he new y-coord inate. getBoundsO. setBounds(). setSizeQ. See the Contai ner class example.
386
set\an
setName() — — — ... —
PURPOSE Sets this component's name.
SYNTAX public void setName(String name)
DESCRiriK >N The component's name is a nonlocalized string that can he used by a program to identify the component. For example, when a program receives an event, it could retrieve the event's source and use its name to determine which compo- nent fired the event. This method sets the name of this component to name.
PARAMETERS name This component's possibly null new name.
SEE ALSO getNameO.
EXAMPLE See getNameO.
setSizef)
PURPOSE Sets this component's size.
SYNTAX public void setSize(int w, int h) public void setSize(Di mens ion d)
DESCRIPTION This method resizes this component so that it has width w and height h. If dimension d is specified instead, this component will have width d.width and height d. height. The current location of this component is not altered. This method may he ignored if this component is embedded in an applet con- text. See the Applet class for more information about applet contexts.
PARAMETERS d h The non-nul 1 component dimension. The new height of this component in pixels.
w The new width of this component in pixels.
SEE ALSO getBoundsO. setBoundsQ. getSizeO.
example See the Contai ner class example.
setVisible()
PURPOSE Makes this component visible or invisible.
SYNTAX public void setVisible(boolean vis)
Component
setVisible()
java.awt
description If vis is true, this component is made visible, if not already visible. Other-
wise. this component is made invisible, if not already invisible. Some layout
managers completely ignore invisible components, so when this component is
made visible, it appears at the wrong location and size. To update this compo-
nent's bounds, this component’s container should be invalidated and then vali-
dated immediately after this component is made visible.
PARAMEIERS
vis If true, this component is made visible; otherwise, this component is hidden.
SEEALSO isShowing(), isVisi ble().
EXAMPLE
This example creates two buttons. One
has a blinking label, and the other shows
or hides the blinking button. See Figure
93.
The blinking button overrides the
addNotifyO method to start the
blinking thread that periodically sets and
clears die button's label. 'Ibe blinking but
ton also overrides the removeNoti fy()
method to remove the thread.
show Example MR В j
EIGLRE93: Component Visibility
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ActionListener {
BlinkButton blink - new BlinkButton(“Blink”);
Main О {
super(“setVisible Example”);
Button ctl -- new Button(“Show/Hide");
ctl.addActionl1stenerCthis);
add(ctl, Borderlayout.NORTH);
add(blink, BorderLayout.SOUTH);
packO ;
show();
public void actionPerformed(ActionEvent evt) {
if (blink, isVisible()) {
blink.setVi si ble(false);
} else {
blink.setVi si ble(true);
i nvali date();
validate();
J
}
static public void mai n(St ri ng [J args) {
new Mai n();
class BlinkButton extends Button implements Runnable {
String label;
Thread thread;
BlinkButton(String label) {
super(label);
this.label - label;
}
public void addNotifyO {
super.addNotifyO;
(thread = new Thread(thi s)).startO ;
}
public void removeNotifyO {
thread = nul1;
super.removeNotifyO;
}
public void runO {
boolean on - false;
while (thread Thread. currentThreadO) {
if (on) {
setLabel(label);
} else {
setLabel(““);
}
on = Ion;
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
StlOWO DEPRECATED
PURPOSE Replaced by setVisibleO.
SYNTAX public void show() public void show(boolean vis)
PARAMETERS vis If true, this component is made visible: otherwise, this component is hidden.
deprecation Replace the usage of this deprecated method, as in show(); show(false); with setVisible(true) ; setVi si ble(false);
Component
size()
ja\ a.awt
size() DEPRECATED
Pl RPOSE Replaced by getSize().
SYNTAX public Dimension sizeQ
RETI’RNS non-null Dimension object containing the si/с of this component.
DETRI CA] ION Replace the usage of this deprecated method, as in Dimension sz = size(); with Dimension sz ~ getSizeO;
TOP-ALIGNMENT
PLRPOSli Constant indicating alignment along a component's top edge.
SY VI AX public static final float TOP-ALIGNMENT
DESCRIPTION This constant specifies that lhe у-coordinate of lhe component's alignment point be at the component's top edge. Its value is 0.0f.
SEE ALSO BOTTOM Al1GNMEN7, CENTER..Al IGNMENT , get Al i gnmentYO .
E X AMPLE'. See the LayoutManager? class example.
toStringO — —
Pt RPOSE Generates a string representation of this component's state.
SYNTAX public String toStringO
DESCRIPTION The result string contains this component's class name and the results of call- ing paramStri ng О. The Java compiler automatically generates code to call this method when it needs to translate this component instance to a string. This method is typically used for debugging.
Rt-TL’RNS /X non-nul 1 string representing this component's state.
OVERRIDES java.lang.Object.toStri ng().
SEP. ALSO paramString О.
EXAMPLE; See java.lang,Object.toStringO.
390
transferFoc
transferFocusO_______________________ _____
purpose Moves the focus to the next focus-traversable component.
syntax public void transferFocusO
description This method transfers the focus to the next focus-traversable component in the
container after this component. This component need not have the focus. See
“Focus Traversal*' in the class description for more information.
see also i sFocusTraversableO , java.awt.event.IocusFvent,
processFocusEventO, requestFocusQ.
example See the class example.
update() ___________ ____________
purpose Called to repaint this component without the background's having been cleared.
syntax public void update(Graphics gc)
description This method is called by the AWT system in response to a call to repaint()
by a native component. Like pai nt(), this method is intended to icpaint sume
area of this component because that area has been damaged or has changed.
Unlike with pai nt(). when this method is called, the background of this com-
ponent has not been cleared by the caller. See ‘'Painting" in the class descrip-
tion for more information.
This method is typically overridden to avoid the clearing of the background
the clearing of the background is critical to flicker-free animation. The clip-
ping area of gc (see getCIipBoundsO I contains the area that needs to be
updated, and gc should be used to update the area. Note that it is possible for
two or more repaint() method calls to be batched into a single call to the
update() method. When this happens, the resulting clipping area is enlarged
to include all of the smaller areas that need to be updated.
If not overridden, this method clears the background and calls pai nt ().
Three properties of gc are initialized with values taken from the same three
properties of this component. The properties are the background color, the
foreground color, and the font.
PARAMETERS
9C The non-nul 1 graphics context on which to paint this component.
SEE also paint(). repaint().
Component
update!)
java.awt
F-X AMPLE
A
В
C
D
E
F
G
H
1
J
К
1.
M
N
()
P
Q
R
S
T
L
V
W
X
Y
Z
This example dem-
onstrates how io
implement a simple
scrolling image. The
image is repeated
horizontally as often
as necessary to fill
the screen. The
image is loaded
from a file and a
thread is created to
move the location of
' update Example ВНЗЕЗ
I IGI RE 94: Scrolling image.
the image I pixel every 100 ms. See Figure 94.
In the update О method, the first image is drawn, regardless of whether the
dimension or pixel information is available. However, if the width of the image
is not yet available, it does not paint the subsequent images.
import java.awt.*;
class Main extends Frame implements Runnable {
int x; // Continuously moving x location of the image.
Image image;
Ma in(St ring filename) {
super( “update Example’ );
// Get the image.
image = getToolkit().getTmage(fi1 ename);
(new Thread(thi s)). startO ;
setSize(300. 160);
show() ;
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
int w - image.getWidth(this);
// Draw left-most image.
g.drawlmage(image, x, get Insets().top, this);
if (w > 0) {
// Draw additional images to fill the display.
for (int i-1; i<=getSize().width/w+1; i++) {
q .drawlmage(image, x+i5fw, getlnsetsO . top, this);
}
}
}
public void run() {
392
validat<
try {
while (true) {
int w = image.getWidth(this);
if (w > 0) {
x - (x-1) % w;
repaintO;
}
Thread.sieep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length «= 1) {
new Mai n(args[0]);
} else {
System.err.println(“Usage: java Main <image-file>”);
}
}
validate()
PURPOSE Validates this component.
SYNTAX public void validate()
DESCRIPTION This method validates this component if it is invalid. Subclasses of Component override val i date() to perform the validation. If this component is a con- tainer, it validates its child components and recomputes their layout. However, note that for efficiency, the validateQ method is not invoked on valid chil- dren. So if the valid child contains an invalid child, the invalid child will not be validated. This situation rarely arises because, by default, calling invalidate О on a component also invalidates all of its ancestors. This method is normally used on components that are containers. See the Container class for more information about layouts.
SEE ALSO Container.validate() , invalidate(), doLayoutO.
example This example demonstrates that layouts are not automatically validated. In the program, when a button is clicked its font is increased by 1 point and the but- ton is invalidated; the button label has become too big and needs to be vali- dated. Clicking the Validate button invokes (he val i date() method on (he frame, thereby validating (he entire component hierarchy.
java.awt
Component
validate)
Figure 95(a) shows a button whose label has increased in si/e and is therefore
invalid. Figure 95(b) shows the same button after the component hierarchy has
been validated.
- validate Example
№JEH
’ validate Example
Validate
Validate
North
North
North'
Norm
West East
East
West
South
South
South
(a)
FIGI RE 95; Validating Layouts.
North
Norm
таг
North
west East
East I
South
South
import java, awt ;
import java.awt.event;
class Main extends Frame implements ActionListener {
Button ctl - new Button("Validate");
Main() {
superC“validate Example");
ctl.addActionlistenerCthis);
add(ctl, BorderLayout.NORTH);
add(makePanel(BorderLayout.EAS1,
makePanel(Borderlayout.SOUTH,
makePanel(BorderLayout.WtST,
makePanel(nul1, null)))),
BorderLayout.CENTER);
setSize(300, 300);
show();
}
Panel makePanel(String name, Component c) {
Panel p - new Panel(new BorderLayout());
Button b;
p.add(b » new Button(“North"), Borderlayout.NORTH);
b.addActionLi stenerCthi s);
p.add(b - new Button(“South"), Borderlayout.SOUTH);
b.addAct ionlistenerCthis);
p.add(b -* new Button(“West") , BorderLayout.WEST);
South
394
validate!)
b.addActionLi stener(thi s);
p.add(b * new Button('*East") , BorderLayout.FAST);
b.addActionLi stener(thi s);
if (name *= null) {
p.add(c, name);
}
return p;
}
public void actionPerformed(ActionEvent evt) {
Object src - evt.getSource();
if (src ctl) {
validate!);
} else {
Font f - ((Component)src).getFont!);
f = new Font(f.getFami 1 y() , f,getStyle(), f.getSize()+l);
((Component)src).setFont(f);
((Component)src).i nvali date();
}
}
static public void main(StringH args) {
new Mai n();
}
}
java.awt.event
ComponentAdapter
в
Syntax
D public abstract class ComponentAdapter implements ComponentListener
E
Description
The component adapter is a component listener in which all callback methods are empty
Cj implementations. The purpose of the component adapter is to make it more convenient tor an
H object to listen for component events. In particular, by using the component adapter, you can
implement only those callback methods in which you are interested. Without the component
। adapter, you are required to implement all callback methods, even if the method is empty.
J To use a component adapter, you create a subclass of ComponentAdapter and override
the desired callback methods. You then create an instance of the component adapter subclass
and call the component's addComponentListenerО method to register it for receiving coin-
L ponent events. The component adapter subclass is typically an inner class.
M
* MEMBER SUMMARY
Methods
Called after a component has been hidden.
Called after a component has been moved.
Called after a component has been resized.
Called after a component has been made visible.
S
T
u See Also
Y ComponentEvent, ComponentLi stener,
java.awt.Component.addComponentLi stenerО.
w
X
Y
Z
° Component Event Callback
p componentHiddenQ
componentMovedO
componentResi zed()
r componentShownO
396
Example
This example shows
how to implement a
“slave” frame that fol-
lows its master frame
wherever it goes. lhe
slave frame alwavs
stavs a fixed distance
from the master frame,
except if some part of
the slave frame would
appear outside the
screen bounds. Sec Fig-
ure 96.
It defines an
adapter that overrides
the component-
I IGl RE 96: Master/Shne Emines.
MovedQ method to update the location of the frame.
One use for this tunctionality is to have the slave frame be a palette of tools that can be
used on objects in lhe master frame.
Note: This example docs not work when the master frame is ieonitied, 'l he location of the
slave frame will be incorrect when the master frame is iconificd and deiconificd. This is
because in the current implementation, lhe process of iconification fires spurious component
events that have not been specified. Since there is no wav to test whether a window is iconi-
fied, the master frame docs not know to ignore the spurious component events. (Watching for
WINDOW_ICONIFIED events docs not help because these events max come before or after lhe
spurious component events.)
import java.awt. ;
import java.a^t.event:
i mport java.text. ' ;
import java.util. •;
class Main extends Frame {
Main() {
superC"Master”j:
setSizef20O. 200j:
shov.C) :
public static void Tj-nfStrnngH args.) {
/' Create master frame.
Frarne f = пел Ma i n Г ) ;
// Create slave frame.
hpu Slav^Frampffj;
Component Adapter
java. awt.event
class SlaveFrame extends Frame {
Frame master;
Point fromMaster;
SIaveFrame(Frame master) {
superC'Sl ave");
this.master = master;
// Listen for events.
ComponentLventHandler ceh - new ComponentEventHandlerQ ;
master.addComponentLi stener(ceh);
D addComponentListener(ceh);
E // Initialize the slave so that on the right side of the frame.
fromMaster - master.getlocation();
F fromMaster.translatefmaster.getSizeO.width, 20);
setLocation(fromMaster.xt fromMaster.y);
G updatelocation(this);
H setSize(100, 100);
showQ;
I }
j void updatelocation(Component componentMoved) {
Dimension screenSize = getToolkit().getScreenSize();
К
if (componentMoved == master) {
L Point newloc - master.getLocationQ ;
M // Determine the new location,
newloc.translate(fromMaster.x, fromMaster.y);
N
// Ensure that slave is within the screen bounds.
() newloc.x Math.max(0,
Math.min(newloc.x, screenSize.width-getSizeO.width));
P newloc.у - Math.max(0,
Math.min(newloc.у, screenSize.height-getSize().height));
Q
// Move the slave to the new location.
R setLocation(newloc.x, newloc.y);
S // Correct the offset from master in case it changed,
fromMaster ~ master.getLocationQ;
T fromMaster.translate(newloc.x, newloc.y);
L // Keep the slave above the master.
toFrontQ ;
v } else {
// Update the offset from master.
W fromMaster = getLocationQ;
fromMaster,translate(
X master.getl ocationQ .x, -master .getLocationQ .y) ;
}
Y }
Z class ComponentLventHandler extends ComponentAdapter {
public void componentMoved(ComponentEvent evt) {
// Master or slave moved.
updateLocation((Component)evt.getSourceQ);
398
com ponent Hidden ()
componentHiddenO
PURPOSE Called after a component has been hidden.
SYNTAX public void componentHidden(ComponentEvent evt)
DESCRIPTION This method is called after the source component is made invisible by a call to Component.setVisible(false). This method is not called if the component was made invisible because its parent became invisible. This method by default has an empty implementation.
PARAMETERS evt The non-nul 1 component event.
EXAMPLE See the ComponentEvent class example.
componentMoved()
PURPOSE Called after a component has been moved.
SYNTAX public void componentMoved(ComponentEvent evt)
DESCRIPTION This method is called after the source component is moved. The source com- ponent can be moved either by the user or by calling Component. setLoca- tion(). Moreover, this method is called regardless of the component s visible state. The source component's new location can be retrieved by calling Compo nent. getLocationQ This method, by default, has an empty implementation.
PARAMETERS evt The non-nul 1 component event.
EXAMPLE See the ComponentEvent class example.
componentResizedf)
Pl’RPOSH Called after a component has been resized.
SYNTAX public void componentResized(ComponentEvent evt)
java.awt.event
ComponentEvent
Syntax
public class ComponentEvent extends AWTEvent
Description
Component events are fired by a component (see Component) whenever the component is
moved, resized, hidden, or made visible. For more general information about events, see
AWTEvent.
Listening for Component Events
To listen for component events from an object, the listener must implement lhe Compo-
nents stener interface. After that, the listener must be registered with the object. An object
is registered by calling (he object s addComponentLi stenerO method.
An alternative, and possibly more convenient, way of receiving component events is to
use a component adapter. See ComponentAdapter for more details.
As with most events, a component event is delivered to its listeners after the operation has
taken place.
ComponentEvent
java.awt.c vent
D
E
F
G
H
I
.1
К
L
M
N
Component Event Elow
Figure 97 shows how component events
typically flow through the system. First, the
event is fired by some component peer in
response to some user gesture. This event is
posted on the event queue (see Event -
Queue). When the event makes its wav to
the front of the queue, it is given to the
component via its dispatchEventQ
method. Fhe main purpose of this method is
to discard the event if the component event
type is not enabled or if (here are no compo
nent event listeners. Otherwise, dis-
patchEventQ calls processEventO,
which calls different methods depending on
the event type. Since this is a component
event, processComponentEventO is
called. The main purpose of this method is
to notify the component event listeners.
A component can override process-
ComponentPeer
System
Event
Queue
ComponentEvent
di spatchEventO
I
processEvent()
I
i processComponentEventO
OzA
Component!.!stener О
Component
FIGURE’П; Component Event Flow.
ComponentEventО to process component events before they are delivered to its listeners
The overridden method should call super.processComponentEventO to ensure that event?
are dispatched to the component s listeners.
A
В
c
()
p MEMBER SUMMARY
Q R Constructor ComponentEvent() Constructs a ComponentEvent instance.
S i т ! Component Method i getComponentO Retrieves the component that fired this event.
1 1 • Component Event Constants
I COMPONENT.FIRST Constant specifying the first id in the range of component event ids.
V COMPONENT-HIDDEN Event id indicating that a component was hidden.
w COMPONENT LAST COMPONENT-MOVED Constant specifying the last id in the range of component event ids. Event id indicating that a component was moved.
X COMPONENT-RESIZED Event id indicating that a component was resized.
Y Z COMPONENT-SHOWN Event id indicating that a component was made v isible on the screen.
Debugging Method paramStri ng() Generates a string representing the component event's state.
402
See Also
ComponentAdapter, Component!.i stener, j ava.awt.AWTEvent,
java.awt.Component, java.awt.Component.dispatchEvent(),
java.awt.Component.processComponentEvent()T
java.awt.Component.processEvent О -
Example
This example demonstrates how to listen to and han-
dle component events from a component. The exam
pie creates a frame that listens for component events
on itself. In response to a component event, the spe-
cifics of the event are printed. Also printed is the
new value that has changed (this shows that the val-
ues have been updated before the event is delivered
to the listeners). See Figure 98.
< ComponentEvent Ex...
Hide Me '
. ___ .....................
л ..- №--- - -------------
FIGURE 98: ComponentEvent.
import java.awt.w;
import java.awt.event.*;
class Main extends Frame implements Component!, i stener, Actionlistener, Runnable
{
MainQ {
superC’ComponentEvent Example") ;
Button b = new Button(”Hide ve“);
add(b, BorderLayout.CENIER);
// Listen for events.
b.addActionListener(this);
addComponentl istener(this);
setSize(100, 100);
show();
}
public void componentResized(ComponentEvent evt) {
System.out .pri nt ("COMPONENT-RESIZED: ") ;
System.out.pr i ntln("new bounds="-+evt. qetComponentO .getBoundsO) ;
public void componentMoved(ComponentEvent evt) {
System.out.print("COMPONENT MOVED: ");
System.out. printlnC'new bounds="+evt.getComponent() .getBoundsO) :
public void componentShown(ComponentEvent evt) {
System.out.print("COMPONENT SHOWN: ");
System.out.printlnC’new visible state-" ♦
evt. get Component () . i sVi sibleO);
public void componentHidden(ComponentFvent evt) {
System.out.print("COMPONENI_HIDDEN: ”):
Syster.out,println("new visible state-" +
evt .getComponentO . i sVi sibleO) ;
}
ComponentEvent ja\ a.awt.event
COMP()NE\T_HRST
// Hide the frame and start the thread.
public void actionPerformed(Actionlvent evt) {
setVi si ble(false);
(new Thread(this))-startO ;
}
// This thread waits for 2 seconds and then shows the frame.
public void run() {
try {
Thread.sieep(2000);
} catch (Exception e) {
}
// This causes a COMPONENT.MOVED event to be generated even though
// the frame is not visible.
setLocation(100, 100);
setVi sible(true);
}
public static void main(String argsf]) {
new Main О:
}
1
COMPONENT FIRST
PCRPOSI Constant specifying the first id in the range of component event ids.
SYMAX public static final int COMPONFNT_FTRST
DESCRIPTION All component event ids must be greater than or equal to COMPONENT FIRST (value 100).
SEE .ALSO COMPONENT-LAST.
EXAMPLE See java.awt .Component.processEventO.
COMPONENT HIDDEN
PERPOSE Event id indicating that a component was hidden.
SYMAX public static final int COMPONENT .HIDDEN
DFSCRIPI ION An event with this id (value 103) is fired by a component after it is made invisible by a call to Component .setVi si bl e (false). A component does nor fire this event if it was made invisible because its parent became invisible.
SEE ALSO java.awt.Component.setVi si ble().
EXAMPLE See the class example.
404
COMPONENT-LAST
COMPONENT JAST
PURPOSE Constant specifying the last id in the range of component event ids.
SYNTAX public static final int COMPONENT LAST
description All component event ids must be less than or equal to COMPONENT-LAST (value 103).
SEEALSO COMPONENT-FIRST.
example See java.awt.Component.processEvent().
COMPONENT-MOVED
PURPOSE Event id indicating that a component was moved.
SYNTAX public static final int COMPONENT-MOVED
DESCRIPTION An event with this id (value 100) is fired by a component when it is moved. A component can be moved either by the user or by calling Component. setLo- cationQ- Moreover, the event is fired regardless of the components visible state. The component's new location can be retrieved by calling Compo- nent .getLocati on().
SEE ALSO java.awt.Component.getLocation0 » java.awt.Component.setLocation().
EXAMPLE See the class example.
COMPONENT-RESIZED
PURPOSE Event id indicating that a component was resized.
SYNTAX public static final int COMPONENT-RESIZED
DESCRIPTION An event with this id (value 101) is fired by a component when it is resized. A component can be resized either by the user or by calling Component.set- Size(), Moreover, the event is fired regardless of the component's visible state. The component's new size can be retrieved by calling Component.get- SizeQ.
SEE ALSO j ava,awt.Component.gets i ze О•
example See the class example.
java.awt.event
Com po nen t E ven t
COMPONENT SHOWN
COMPONENT-SHOWN
PIRPOSE Event id indicating that a component was made visible on the screen.
SYNTAX public static final int COMPONENT.SHOWN
DESCRIPTION In the simplest terms, a component fires an event of this id (value 102) when ever it appears on the screen or, more technically, is shown. /\ component is showing if it is visible, its peer exists, and its parent is showing. For more information about the showing property, see Component, isShowingQ. However, a component does not fire this event in all cases. In particular, it will Tire the event only if Component. setVi si bl e() or Wi ndow. show() is called on the component. In other words, a component does not fire this event if the component becomes shown because some ancestor became show n.
SEE Al SO java.awt.Component.isShowing О, java.awt.Component.setVisible(), java.awt.Window.show().
EXAMPLE; See the class example.
ComponentEventO
Pl’RPOSE Constructs a ComponentEvent instance.
SYNTAX public ComponentEventfComponent source, int id)
DESCRIPTION This method creates a new component event instance w'ith source as the com ponent firing this event. After the component event is created, the source object can distribute the event to its listeners by calling the component event-related methods in AWTEvent Multicaster. If the event is not created by source, the creator can deliver the event to the source component cither by posting the event to the event queue (see EventQueue. post Event ()) or by calling the source component s Component. di spatchEvent() method directly.
PARAMETERS source i d The non-null component that is firing this component event. One of the component event ids.
SEE ALSO java.awt.AWTEvent.getID(), java.awt.AWTEventMulticaster, java.awt.EventQueue, java.util.Eventobject.getSource().
406
getCompone
getComponentO
PURPOSE Retrieves the component that fired this event.
SYNTAX public Component getComponentO
description This method returns the component that fired the component event. This is the same object returned by Eventobject ,getSource().
RETURN'S The non-nul 1 component that fired this event.
SEE ALSO j ava.awt.Component, java.util.Even tObject.getSou rce().
example See the class example.
paramStringO
PURPOSE Generates a string representing the component event s state.
SYNTAX public String paramStringO
DESCRIPTION The returned string contains the name of the component event and, if appropri- ate, the new bounds of the component. Л subclass of this class should override this method and return a concatenation of its state with the results of super.paramStringO. This method is called by the AWTEvent. toStri ngQ method and is typically used for debugging.
RETURNS A non-nul 1 string representing the component event’s state.
OVERRIDES java. awt. AWTEvent. paramStri ng().
SEE ALSO java.awt. AWTEvent. toStringO , java .lang .Object. toStringO .
example Seethe java.awt .AWTEvent class example.
java.awt.event
ComponentLi stener
A
В
D
e
F
Cl
H
1
J
К
L
M
N
О
P
Q
R
S
T
I
V
Component I. iяtener
Syntax
public interface ComponentListener extends EventListener
Description
When an object (listener) wishes to receive component events from a component (the source
component), two things must be done:
I. I he listener must implement this interface and all the methods required by this interface.
2. The listener must be registered with the source component. It becomes registered b\ niak
ing a call to the source component's addComponentLi stenerO method.
For more information about component events, see ComponentEvent.
W
Y
408
componentHiddenf
ИРЙЕК SUMMARY
Component Event Callback Methods
componentHi dden 0 compone n tMoved Q componentResizedQ componentShown О Called after a component has been hidden. Called after a component has been moved. Called after a component has been resized. Called after a component has been made visible.
See Also
ComponentAdapte r, Component Event, j ava.awt.AVfTEventMulti caste r,
java.awt. Component. addComponentLi stenerQ , java. uti 1. Event Li stener.
Example
See the ComponentEvent class example.
componentHiddenO
PURPOSE Called after a component has been hidden.
SYNTAX public void componentHidden(ComponentEvent evt)
DESCRIPTION This method is called after the source component is made invisible by a call to Component. setVi si bl e (f al se). This method is not called if the component was made invisible because its parent became invisible.
PARAMETERS evt The non-nul 1 component event.
EXAMPLE See the ComponentEvent class example.
componentMoved ()
PURPOSE Called after a component has been moved.
SYNTAX public void componentMoved(ComponentEvent evt)
DESCRIPriON This method is called after the source component is moved. The source com- ponent can be moved either by the user or by calling Component.set- LocationQ. Moreover, this method is called regardless of the component's visible state. The source component’s new location can be retrieved by calling Component.getLocati on().
java.awt.event
ComponentListener
eomponentResized()
This method defines the code that is to be executed when this listener receives
ComponentEvent.COMPONENT-MOVED events. See ComponentEvent.COMPO-
NENT-MOVED for details.
paraml O RS
evt
I X AMPL 1
The non null component event.
See the ComponentEvent class example.
D
componentResized()
p pi Rposk Called alter a component has been resized.
q syntax public void componentResized(ComponentFvent evt)
pi di st rii’Hon This method is called after the source component has been resized. A compo-
nent can be resized either by the user or by calling Component. setSi zeO-
1 Moreover, this method is called regardless of the component's visible state,
j The component's new size can be retrieved by calling Component.get-
v SizeO.
lx
L PARAML rtRS
evt The non-nul 1 component event.
M
l.xampll See the ComponentEvent class example.
N
()
p componentShown()
Q Pl ’RPOSF. Called after a component has been made \ isible.
R SYNTAX public void componentShown(ComponentEvent evt)
S DESCRIPTION T U In the simplest terms, this method is called whenever the source component appears on the screen or, more technically. is shown. A component is лАси ше if it is visible, its peer exists, and its parent is showing. For more information about the showing property, see Component. i sShowing().
V However, this method is not called in all cases. In particular, it will be called
XV only if Component. setVi si ble() or Window.show() is called on the com-
X ponent. In other words, the method is not called if the component becomes shown because some ancestor became shown.
PARAML I ERS
Z evt The non null component event.
EX XMPl 1. See the ComponentEvent class example.
410
java.awi.pecr
ComponentPeer
Syntax
public interface ComponentPeer
Description
A component such as a button uses the platform's native implementation of a button. For
example, on Solaris, the AWT button uses the Motif button widget, while on Windows 95. the
AWT button uses the button control. So that the AWT button component behaves the same on
all platforms, the button is assigned a pea that takes care of translating the behavior of the
platform's native button to (he behavior of the AWT button.
Every component in the AWT has a peer associated with it. Just as the Component class is
the superclass of all AWT components, the ComponentPeer class is the superclass of all peer
classes.
AWT programmers normally do not directl\ use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AW I to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
See Component and Toolkit for additional information about component peers.
Com ponentPeer
java.awt .peer
MEMBER SUMMARY
Peer Methods checkimage О createlmageO disposeO getColorModel() getFontMetricsO getGraphi cs() getLocationOnScreenO getMinimumSizeO getPreferredSizeO getToolkitO handleEventQ 1s FocusTrave rsable О paintO preparelmageO printQ repaint О requestFocusO setBoundsO setBackgroundO setCursorO setEnabledO setFontO setForegroundO setVisi ble() Retrieves the construction status of an image. Creates an off-screen image or an image from an image pro- ducer. Destroys a component. Retrieves the component’s color model. Retrieves the font metrics for a font. Creates a graphics context for the component. Retrieves the component’s location on the screen. Calculates the component’s minimum size dimensions. Calculates the component’s preferred size dimensions. Retrieves the component’s toolkit. Called when the component receives an event. Determines whether this component’s focus can be traversed using the Tab or Shift-Tab keys. Called to repaint the component. Triggers the loading of image data for an image. Prints the component on a graphics context. Makes a request to repaint a component. Requests that the focus be given to the component. Moves and resizes a component. Sets the component’s background color. Sets the component’s cursor image. Enables or disables a component. Sets the component's font. Sets the component’s foreground color. Makes the component visible or invisible.
Deprecated Methods di sabl eO enableO hi de О minimumsizeО preferredSizeO reshapeО showO Replaced by setEnabledO. Replaced by setEnabledO. Replaced by setVi si bleO- Replaced by getMi ni mumSi ze (). Replaced by get Pref erredSi ze(). Replaced by setBoundsO. Replaced by setVi si ble().
See Also
j ava.awt.Component, j ava.awt.Tool kit.
412
checklmage()
PURPOSE Retrieves the construction status of an image.
SYNTAX int checkimageflmage image, int width, int height, TmageObserver obs)
PARAMETERS height image obs If >= 0, specifies the height of the scaled version of the image to check. The non-nul 1 image to check. If non-nul 1, specifies the image observer to be notified whenever the status changes.
width If >= 0, specifies the width of the scaled version of the image to check.
RETURNS The combination of status bits as defined by the Imageobserver interface.
SEE ALSO j ava. awt. Component. checklmageO.
createlmage()
PURPOSE Creates an off-screen image or an image from an image producer.
SYNTAX Image createlmage(int width, int height) Image createlmageflmageProducer prod)
PARAMETERS height prod wi dth The height of the off-screen image in pixels. I'he non-nul 1 image producer. The width of the off-screen image in pixels.
RETURNS A new off-screen image.
SEE ALSO j ava.awt.Component.c reatelmageO.
disable() DEPRECATED
PURPOSE Replaced by setEnabledf),
SYNTAX void disableO
deprecation Replace the usage of this deprecated method, as in peer .di sableO; with peer.set£nabled(false);.
ComponentPeer
disposcf)
java.awt.peer
PURPOSE Destroys this component.
syntax void disposeQ
DESCRIHION This method releases any resources associated with this component.
SFF ALSO java.awt.Component.removeNoti fy().
DEPRECATED
enable()
pikpose Replaced by setEnabled().
syntax void enable()
deprecation Replace the usage of this deprecated method, as in
peer.enableO;
vi ith
peer.setLnabled(true);
getColorModel()
Pl RPOSE Retrieves the component’s color model.
SYNTAX ColorModel getColorModelО
RETURNS A non-nul 1 color model instance.
SEE AL,SO java.awt.Component.getColorModel().
getFontMetrics()
Pl RPOSL
SYNTAX
PARAMETERS
font
REILRNS
SEE ALS<)
Retrieves the font metrics for a font.
FontMetrics getFontMetrics(font font)
The non-nul 1 font.
I’he non-nul 1 font metrics for font.
java.awt.Component.getFontMetri cs().
getGraphics()
purpose Creates a graphics context for the component.
414
getl.ocationOnScreenf)
syntax ‘ RETURN» Graphics getGraphics() A graphics context for the component.
’ SEE ALSO j ava.awt.Component.getCraphi cs О.
getLocationOnScreen()
PURPOSE: SYNTAX RETURNS SEE ALSO Retrieves this component's location on the screen. e Point getLocationOnScreenO A new non-nul 1 point containing this component s location relative to the screen. j ava.awt.Component.getLocati onOnSc reen(). ( 1
getMinimumSize()
PURPOSE, Calculates the component's minimum size dimensions.
SYNTAX Dimension getMinimumSize()
RETURNS A non-nul 1 dimension object containing the component’s minimum size.
SEE ALSO java.awt.Component.getMi nimumSi ze().
( getPreferredSize() !
purpose: Calculates the component’s preferred size dimensions. (
SYNTAX Dimension getPreferredSizeO I
RE-TURNS A non-nul 1 dimension object containing the component’s preferred size.
SEE ALSO java.awt.Component.getPreferredSi ze().
getToolkit() t
PURPOSE: \ Retrieves the component’s toolkit.
SYN'I ДХ Toolkit getToolkitO
RETURNS A non-nul 1 reference to the component’s toolkit.
sei: ai so java.awt .Component .getToolкi tO- java.awt. tool ki t. 2
ComponentPeer
handleEventt)
java.awt.peer
handleEvent()
purpose Called when the component receives an event.
syntax boolean handleEvent(AWTEvent evt)
parameters
evt The non-null AWT event.
returns false if the event should be passed up to the component's parent; true other-
wise.
see also java.awt.AWTEventt java.awt.Component.processEventO.
hide()
DEPRECATED
H purpose Replaced by setVisible().
syntax void hide()
deprecation Replace the usage of this deprecated method, as in
peer. hideC) ;
with
peer.setVi si ble(false);
M
N isFocusTraversable()
0 PURPOSE Determines whether this component's focus can be traversed using the lab or
P Shift-Tab keys.
Q SYNTAX boolean isFocusTraversableQ
R SEE ALSO java.awt.Component.i sfocusTraversable().
S
T minimumSize() deprecated
u PURPOSE Replaced by getMi nimumSizeO-
V SYNTAX Dimension minimumSizeO
w RETURNS A non-null dimension object containing the component's minimum si/e.
X DEPRECATION Replace the usage of this deprecated method, as in
Y Dimension min = peer.minimumSize();
with
z Dimension min = peer.getMinimumSize();
416
paint I I
paintQ — _ —
purpose: Called to repaint the component.
SYNTAX PARAMETERS gc SEE ALSO void paint(Graphics gc) The non-nul 1 graphics context in which to paint the component, j ava.awt.Component.pai nt ().
preferredSize() deprecated
PURPOSE Replaced by getPreferredSizeO.
SYNTAX Dimension preferredSize()
RETURNS A non-null dimension object containing the component’s preferred size.
DEPRECATION Replace the usage of this deprecated method, as in Dimension pref = peer.preferredSize(): with Dimension pref = peer.getPreferredSizeO;
preparelmage()
PURPOSE: Triggers the loading of image data for an image.
SYNTAX boolean preparelmage(Image img, int w, int h, Imageobserver obs)
PARAMETERS h img obs w -1 or the scaled height of the returned image. The non-nul 1 image to load. The non-nul 1 image observer. -1 or the scaled width of the returned image.
RETURNS true if all the image data for img is available: false otherwise.
SEE ALSO java.awt.Component.preparelmagef).
print()
Pi'Rpost: Prints the component on a graphics context.
SYNTAX void print(Graphics gc)
В
D
E
E
G
H
I
J
К
1.
M
N
О
P
Q
R
S
I
U
V
W
X
Y
Z
Component Pee г
repaint( }
PAR A METERS
java.au {.peer
gc The non-null graphics context on which to print.
seealso java.awt.Component.print ().
repaint()
pi-rpose Makes a request to repaint a component.
S'ivrw void repaint(long ms, int x, int y. int w, int h)
PAR \METLRS
h I'he height of the rectangular area to repaint.
ms Maximum delay in milliseconds before the update() method is called.
w The width of the rectangular area to repaint.
x d he А-coordinate of the rectangular area to repaint.
у I'he у-coord inate of the rectangular area to repaint.
see also java.awt.Component.repai nt().
requestFocusO
purpose Requests that the focus be given to the component.
ssniax void requestFocusO
see also java.awt.Component.request Iocus().
reshapel)
pirposl Replaced by set Bounds О.
s>\tax void reshape(int x. int y, int w, int h)
PARAMPIERS
DEPRECATION
DEPRE(
l'he new height of the component in pixels.
I'hc new width of the component in pixels.
The new л-coordinate of the component in pixels.
The new у-coordinate of the component in pixels.
Replace the usage of this deprecated method, as in
peer.reshape(x. y, w, h);
w ith
peer.setBounds(x, y, w, h);.
418
setBackgroundf 1
setBackgroundO
PURPOSE Sets the component s background color.
SYNTAX parameters c void setBackground(Color c) The new background color, which can be null.
SEE ALSO java.awt.Component.setBackground 0•
setBounds()
PURPOSE Moves and resizes a component.
SYNTAX void setBounds(int x, int yr int w, int h)
PARAMETERS h w X У The new height of the component in pixels. The new w idth of the component in pixels. The new л-coordinate of lhe component in pixels. The new v-coordinaie of the component in pixels.
SEE ALSO java.awt.Component.setBounds().
setCursor()
PURPOSE Sets the component's cursor image.
SYNTAX void setCursor(Cursor cursor)
PARAMETERS cursor The non-null cursor image.
SEE ALSO j ava.awt.Component,setCursor().
setEnabled( •
PURPOSE Enables or disables a component.
SYNTAX void setEnabledfboolean cond)
PARAMETERS cond If true, this component is enabled; otherwise, this component is disabled.
SEE Al SO java.awt.Component. setFnabledO-
Component Pee г
ja\a.awt peer
setFontf)
setFont()
PURPOSE SYMAX PAR.AMEIERS f SEE ALSO Sets the component's font. void setFontfront f) The font. This parameter can be nul 1. java.awt.Component.setFontC).
set Foregrounds)
PURPOSE Sets the component's foreground color.
SYM AX void setForeground(Color c)
PARAMEIERS
C The new foreground color, which can be null.
SEE At.SO java.awt.Component.setForeground().
setVisible()
Pl RPOSE Makes the component visible.
SY MAX void setVisiblefboolean cond)
PARAMETERS
cond If true, makes the component visible; if false, makes the component invisi-
ble.
SEE ALSO java.awt.Component.setVi si bl e().
show() DEPRECATED
PURPOSE Replaced by setVisi ble().
SV M AX void showO
DEPRECA'iiON Replace the usage of this deprecated method, as in
peer.showO;
with
peer.setVi si ble(true);
420
java.awt
Container
Syntax
public abstract class Container extends Component
Description
A container is a component that can contain other components. A container has a list of child
components and a layout manager to lay out the children.
Layout Management
A container can have a layout manager associated with it to determine the size and placement
of its components. A container maintains a valid state, which indicates whether the children of
the container are properly laid out. Actions such as removing or adding a component to a con-
tainer cause the container to become invalid. Only when the user causes the resizing of the
container (by resizing the top-level window) is the layout manager automatically invoked by
the system. In all other situations, such as after adding a new button, the layout manager must
be invoked explicitly with a call to validate().
When the layout manager is invoked on a container, it first checks whether the container is
valid. If so, it does not lay out the container. If not, it lays out all the children and then invokes
the layout manager of any invalid children. l he layout process continues recursively until all
Container
java.awt
reachable components are valid. Note that it a component is invalid but is embedded in a valid
container, the layout process will not be applied to the invalid component.
Although the layout manager recursively traverses the component hierarchy, it does not
recurse below valid components. Note that with this behavior, an invalid component will not
be validated if it is in a valid container. To remedy this, you need either to invoke the lav out
manager directly on the invalid component or to invalidate the component s container.
Certain operations on the container automatically invalidate the container. However, in
many cases the container needs to be explicitly invalidated. Lor example, it a component's size
is changed (such as by changing its label), its container is not automatical lx marked invalid.
See layout О and validateO for more details.
Insets
An ш.\с/ is a distance from a rectangle's edge (see Insets). A container maintains four
insets left. top. right, bottom—that correspond to the edges of the container. The insets are
applied to a container's bounds to yield another, typically smaller, area called (he inset area. in
which the container's components are constrained. Insets are most often present in containers
that have borders, such as the frame (see Frame). They are primarily used by layout managers
to ensure that the components are laid out to stay within the container's borders.
Disabled Containers
Disabling a container intercepts the delivery of all mouse and keyboard events made by the
user to (he container s child components. Disabling the container is not (he same as disabling
all components in the container. For example, most components look different when disabled.
In a disabled container, the components will appear as though they were enabled.
The Alignment Property
The alignment property’ is a pair of floating-point values -one that specifies the v-aligninent
and one that specifies the у-alignment. Together the л- and v-alignment values specify an
alignment point on the container. This alignment point affects how some layout managers
place the components in a container. More specifically, the alignment point on a container c is
(x alignment " c.width, y_alignrrent * c,height)
Unlike the alignment property for a component, the alignment property for a container
depends on how its children are laid out. In particular, the layout manager is responsible for
determining the container's alignment value. See LayoutManager2 for more details.
Events
A container event (see ContainerEvent) is fired when a component is added or removed
from a container. In addition to container events, a container fires all of the events fired by the
Component class. See the Component class for details. See (he AWTtvent class fur general
information on events and how to filter or handle them.
422
^Ordering
The /-ordering of components in a con-
tainer specifies lhe front-to-back order-
ing of overlapping components. For
example, the First component in the z-
order will appear above all other sib-
lings; the last component in the z-order
will appear behind all other siblings. It
turns out that the z-order is exactly lhe
order in which components appear in a
container (see Figure 99). That is, the
component at index position 0 will
index
position
Components
FIGURED: /^Ordering.
appear in front of all of its siblings. By changing the position of the component in its container,
you can control how it will overlap with respect to its siblings. For example, if you want to
bring a component up front, you would remove it from its current position and insert it at index
position 0.
Focus Traversal
Most platforms support a gesture for
moving the focus from component to
component. For example, on Windows
you press the Tab key to move the focus
forward and Shift-Tab to move the
focus backwards. When the gesture is
invoked, the AWT system must deter-
mine which component should receive
the focus. A component that can receive
the focus in this way must be focus-
traversable, A component is focus-
traversable if it is enabled, it is visible,
and its IsFocusTraversableO
method returns true.
The order of focus traversal is
exactly the order of the components in a
container. If a component has the focus
Not Focus'Traversable Component
|[ ]| Container
FIGI RE 100: Focus Traversal.
and is at index position l\ the AWT system will search for the next focus-traversable compo-
nent starting at P+1 and continue forward either until one is found or that last component in the
container is reached. In the latter case, the AWT system resumes the search at index position 0
and continues until one is found or the component at index position P is reached (in which
case, no focus-traversable components were found). If one of the components is a container,
the component the AWT system starts to search for focus traversable components inside that
container al the component at index position 0. See Figure l(X).
Container
ja\ a.aw t
Native and Lightweight Containers
There are two kinds of containers: native and light weight. <\ native container has a peer that
uses a container supplied by the platform. Panel and Frame are examples of native contain-
ers. A lightweight container behaves just like a native container, except that its peer docs not
use any system resources. Its advantage is more efficient use of the platform’s resources. You
can freely mix lightweight and native components in a lightweight or native container. How-
ever, a lightweight container requires the use of one native container in order to function. Spe-
cifically, one of its ancestors must be a native container.
At present, the AWT does not supply any lightweight containers. However, the light-
weight support is fully implemented and you can (and are encouraged to) create your own
lightweight containers. To create a lightweight container, you must have your container extend
from Contai ner.
There are small differences between lightweight containers and native containers. Here
arc some of them:
1. When a lightweight container overrides paintQ. paint() should do its painting and
then call super, pai nt(). Calling super,pai nt () causes any lightweight children to be
painted.
2. When a container contains lightweight and native components, the lightweight compo-
nents will alway s appear behind the native components, regardless of the /-ordering of
the components. However, the relative /.-ordering within each group (lightweight or
native) is preserved. So if a lightweight LI is in front of a lightweight L2 w ith many
native components in between. LI will appear in front of L2 even though both LI and L2
appear behind rhe native components. Mouse events are delivered to the native compo-
nents before the lightweight components regardless of their /-orderings. When light-
weight and native components are mixed in a container, it is highly recommended that a
nonoverlapping layout manager is used to avoid confusion. See Component for informa
tion about lightweight components.
3. If you call repai nt() on a lightweight container, the AWT responds by calling its
paintf) method. In the case of a native container, the AWT will call its updateO
method. This means that the background for the lightweight is always cleared. Special
steps must be taken to avoid flickering; it is not enough for the lightweight to implement
double-buffering.
4. When a graphics context is created on a lightweight container, either by the AWT system
or by a call to getGraphics(), the graphics context is not initialized with values from
the container. Instead, its background color, foreground color, and font are initialized w ith
the values from its closest native container. This means that when the pai nt() method is
called on a lightweight container, the colors and fonts must be properly initialized.
424
ER SUMMARY
Constructor ContainerО Constructs a new instance of Container.
Alignment Methods getAl ignmentXQ Retrieves this container’s preferred alignment along the ,v- axis.
getAl ignmentYQ Retrieves this container's preferred alignment along the y- axis.
Component Methods addO addimp1() getComponentO getComponentAtО О getComponentCoun t() getComponentsQ isAncestorOf() removeO removeAllО .Adds a component to this container. Adds a component to this container. Retrieves a component in this container. Locates the component at a point in this container. Retrieves the number of components in this container. Retrieves all the components in this container. Determines if this container is an ancestor of a component. Removes a component from this container. Removes all components from this container.
Event Methods addContai nerLi stenerQ processEventO processContainerEvent0 removeContai ne rLi stenerQ Adds a listener to receive this container's container events. Processes an event enabled for this container. Processes a container event enabled for this container. Removes a listener from receiving this container's container events.
Layout Methods doLayoutQ getlnsetsQ getLayoutQ getMaxi mumSi ze() getMi nimumSizeО getPreferredSizeO invalidateО setLayoutQ validateQ validateTreeQ Invokes the layout manager on this container. Retrieves this container's insets. Retrieves this container's layout manager. Calculates this container's maximum size dimensions. Calculates this container’s minimum size dimensions. Calculates this container's preferred size dimensions. Invalidates this container. Sets the layout manager for this container. Validates this container by laying out its components again. Called by validateQ to again layout the components in this container.
Rendering Methods paintQ pai ntComponentsO Paints this container on a graphics context Paints this containei's components on a graphics context. Continued
Container
java.awt
л
В
С
Г)
г
I
G
Н
I
J
К
I.
м
N
О
Р
Q
R
S
Г
и
V
W
X
Y
Z
MEMBER SUMMARY
Rendering Methods (Continued)) printO pri ntComponentsO Prints this container on a graphics context. Prints this container's components on a graphics context.
Peer Methods addNoti fyО removeNot i fу() Creates the peers for this container and its descendants. Destroys the peer hierarchy of this container and its descen- dants.
Debugging Methods listO paramSt ri ng() Prints a listing of this container’s component hieiarchy. Gene rates a string representing the container's state.
Deprecated Methods countcomponents() deliverfvent() i nsets() 1ayout() locateO minimumSizeO preferredsize() Replaced by getComponentCountO. Replaced by Component. d i spatchEvent О. Replaced by get I nsets О Replaced by doLayout(). Replaced by getComponentAt(). Replaced by getMi nimumSi ze(). Replaced by getPreferredSizeQ
Example
This example pro-
gram implements
a rudimentary user
interface builder.
Using it. the user
can create AWT
components on the
canvas and then
move them about.
The Add menu
contains the names
of various compo
nents that, when
HGl’RK 101: Container.
selected, create the component on (he canvas. See f igure 101. The components are created dis-
abled so that they can respond to mouse events. Any mouse event directed at a disabled com
ponent is delivered to its parent. In this case, the program catches the mouse event and
determines if it occurred over a component. If so. one of several actions can occur. If the left
426
mouse button was pressed, the component can be dragged around. If the right mouse button
was pressed, the component is resized. И both the Shift and Control keys were held down dur-
ing the mouse click. the component is removed.
The Edit menu
contains two com-
mands: Remove All
and Test. See Figure
102. Remove All re-
moves all the com-
ponents on the can-
vas. Test changes the
enabled state of all
the components on
the canvas. When
the program is in test
mode, the compo-
nents are enabled
FIGI RE 102: Container: Edit Menu.
and so behave nor
mally; the components cannot be moved or resized. When the program is not in test mode, the
components are disabled and can be moved and resized.
import java.awt.";
import java, awt .event ;
class Main extends Frame {
CheckboxMenuItem testCB - new CheckboxMenultem('‘Test”);
Main() {
super(“Container Example”);
MenuBar mb = new MenuBarO;
ActionListener actionListener = new ActionEventHandler();
MouseEventHandler mouseListener - new vouseEventHandlerO;
// Initialize Edit Menu
Menu m = new MenuCTdi t”):
m.add(“Remove All”);
testCB.addltemL i st ener(new ItemEventHandl er());
m.add(testCB);
mb.add(m);
m.addActionListener(actionli stener);
// Initialize Add Venu
m - new Menu(“Add’');
m.add('‘Button”):
m.addC'Checkbox”);
m.add(“Choi ce”):
m. addC‘1 i st”) ;
m.addC’Scrol Ibar”);
m.add(“TextArea”);
m. addC'TextF ield”);
m.addC'l ightweight”) ;
Container
ja\a.awt
mb.add(m);
// Set the menubar.
setMenuBar(mb);
// Listen for events.
m.addActionLi stener(actionLi stener);
addMouseLi stener(mouseListener);
addMouseMotionLi stener(mouseLi stener);
D
i:
h
H
I
J
к
1.
M
N
()
P
Q
R
S
T
u
V
X
Y
Z
// Remove the default layout manager.
setLayout(nul1);
setSize(400, 200);
show();
}
Component dragging;
Component stretching;
Point offset;
class N"ouseEventHandler extends MouseAdapter
implements MouseMotionlistener {
public void mousePressed(MouseFvent evt) {
i nt x - evt. getXO ;
int у - evt.get Y();
Component c - getComponentAt(x, y);
if (c != null && c != Main.this) {
if (evt.isShiftDown() && evt. i sCont ro IDownO) {
remove(c);
} else if (evt.isAltDown()) {
stretching = c;
// Bring to front.
remove(c);
add(c, 0);
} else {
offset = new Point(x-c.getLocationO.x,
у c.getLocation О.у);
dragging - c;
// Bring to front.
remove(c);
add(c, 0);
}
}
}
public void mouseReleasod(MouseEvent evt) {
stretching - dragging = null;
}
public void mouseDragged(Mousefcvent evt) {
int x = evt.getX();
int у - evt.getYQ ;
if (dragging != null) {
dragging.setLocation(x-offset.x, у offset.у);
} else if (stretching !- null) {
stretching.setSize(x st ret chi ng.getBoundsO-x,
у stretching.getBoundsO .у) ;
428
}
}
public void mouseMoved(^ouseFvent evt) {
}
}
int newX, newY;
class ActionFventHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
newX = Math .max (getlnsetsO . left, newX);
newY - Math.max(getlnsets().top, newY);
Component c = null;
String arg - evt.getActionCommand() ;
if (“Button".equals(arg)) {
add(c = new ButtonC'Button"));
} else if (“Checkbox”.equals(arg)) {
add(c - new Checkbox(“Checkbox"));
} else if ("Choice”.equals(arg)) {
add(c = new ChoiceO);
} else if ("Li st”.equals(arg)) {
add(c = new List());
} else if ("Scrollbar”.equals(arg)) {
add(c - new Sc roll bar());
} else if (“TextArea”.equaIs(arg)) {
add(c ~ new TextArea("TextArea”, 3, 20));
} else if (“TextField”.equa1s(arg)) {
add(c new TextField(“TextField”));
} else if (“Lightweight”.equals(arg)) {
add(c = new LightweightO);
} else if (“Remove Al1 ”. equals(arg)) {
removeAl1();
// The following is needed to clear the lightweights,
repai nt();
}
if (c ’= null) {
Dimension d - c.getPreferredSize();
c.setBounds(newX, newY, d.width, d.height);
c . settnabled(testCB. getStateO);
newX += 20;
newY 20;
if (newX > getSizeO .width*3/4) {
newX = 0;
}
if (newY > getSize().height*3/4) (
newY - 0;
}
}
class ItemEventHandler implements Itemlistener {
public void iteTStateChanged(ItemFvent evt) {
Component!] all - getComponentsO ;
boolean newState - (evt.get StateChangeO -- ItemFvent. SEL1
// Enable all the components.
for (int i-0; i<al 1 . length; i+-0 {
all Li J.setEnabled(new$t ate);
Container
java.awt
}
}
static public void main(StringJ args) {
new Mai n(l;
}
}
class Lightweight extends Component implements FocusListener {
boolean hasFocus;
I ightweightO {
// listen for focus events.
addFocusListener(this);
setSize(80, 80);
}
public void paint(Graphics g) {
if (hasFocus) {
g. set('olor(Color. green);
} else {
g.setColor(Color,red);
}
g.fi1lOval(0, 0, getSize().width, getSize().height);
g.setColor(Color,bl ack);
g.drawOval(0t 0, getSize().width-1, getSizeO .height 1) ;
}
public Dimension getPreferredSize() {
return gerSizeQ;
}
public boolean isFocusTraversable() {
return true;
}
public boolean contains(int x, int y) {
int midX = getSize().width/2;
int midY = getSize().height/2;
// This formula doesn’t really work for ovals.
return (midX-x)*(midX x) + (midY-y)*(midY-y) <= midX-mid)
}
public void focusGainedCTocustvent evt) {
hasFocus - true;
repai nt();
}
public void focusLost(FocusEvent evt) {
hasFocus - false;
repaint О;
1
}
430
addf
add()
pijrposi:
SYNTAX
Adds a co тропе ni to thi ,s container.
public Component add(Component comp)
public void add(Component comp, Object constraints)
public void add(Component comp, Object constraints, int pos)
public Component add(Component comp, int pos)
public Component add(String name, Component comp)
description 4'his method adds the component comp to the container at position pos. If pos
is 0, the new component will be the first component in the container. If pos is
-1. the new component will be the last component in the container. If pos is
not specified, it defaults to -1.
If comp is already in another container, it is removed from its old container and
added to this container. If this container has a peer, a peer is created for comp
and added to the peer hierarchy of this container.
The component s layout constraints, as specified by name or constraints,
are used by the container's layout manager. Alter the component is added to
the container, the container's layout manager is notified of the addition. The
addition of a component always invalidates the layout. A container event is
fired, and if container events have been enabled for this container, any con-
tainer listeners for this container are notified.
Use of the last form of this method (the one that accepts name) is not recom-
mended. Its use should be replaced by use of the more generic forms that
accept constraints in place of name.
PARAMETERS
comp The non-nul 1 component to be added to the container.
constraints The object specifying layout constraints,
name The component name, which may be null.
pos The position at which to insert the component. 0 means the firsi position; -1
means the last position.
RETCrns The component being added (comp). (Note that the return type of two forms of
this method are void and so return nothing.)
EXCEPTIONS
Il legalArgumentException
If pos is greater than the number of components in this container, or if comp is
a w indow, or if comp is a container that contains this container.
SEE ai.so add [mpl () , addContai nerl i stener(),
java.awt.event.Contai nerEvent,
java.awt.event.ContainerListener, LayoutManager, LayoutManager?
example See the class example.
Container
java.awt
addContainerListenert )
addContainerListener()
F4 RPOSL Adds a listener for receiving this container's container events.
SYXTAX public synchronized void addContainerListener(Containerl istener listener)
DESCRIP I ION Container events are fired when a component is added or removed from a con- tainer. See ContainerEvent for more details. After this method is called, the container listener listener will receive container events fired b> this con- tainer. If 1 istener is null, this method does nothing.
PARA ME I ERS 1i stener I'hc possibly null container listener to add.
StЛ ALSO java.awt.event.ContainerAdapter, java.awt.event.Containertvent, java.awt.event.Contai nerLi stener, removeContai nerIi stener().
FXAMPI.F See java.awt.event.Contai ne rEvent.
addlmpK) — _ — *
Pl RPOSE Adds a component to this container.
SV XI AX protected void addlmpl(Component comp, Object constraints, int pos)
DF.SCRIPHOX This method is used by add О to add a component to this container. A subclass that wants to perform additional processing during an add() should override this method. The overriding method should call super.addlmpl () to ensure that the component is added properly to the container.
P.ARAME.TCRS
comp The non-nul 1 component to be added to the container.
constraints The object specifying layout constraints.
pos The position at which to insert the component. 0 means the first position: -1 means the last position.
F XCEPIIOXS
Illegal Argument Except i on
SEI. ALSO If pos is greater than the number of components in this container, or if comp is a window, or if comp is a container that contains this container. add(), addContainerLi stenerO, java.awt.event.ContainerEvent, java.awt.event.ContainerListener, Layout^anager, tayoutManager2.
432
addNolilyi >
exampi f hi4' example creates a l'ram<
rides addlmpl () to print on
information. See Figure 103.
< addlmpl Example
North
import java. awt . ;
import java.awt.event;
class Main extends Frame
implements ActionListener {
Main() {
super(“addlmpl Example’’);
Button b;
// Add buttons
add(b = new Button(“North”), BorderLayout.NORTH);
b.addActionLi stener(thi s);
add(b = new Button(“South“), BorderLayout.SOUTH);
b.addActionLi stener(thi s);
add(b = new Button(“Center”), BorderLayout.CENTER);
b.addActi onLi stener(thi s);
add(b = new Button(“West"), BorderLayout.WEST);
b.addActi onLi stener(thi s);
add(b = new Button(“East“), BorderLayout.EAST);
b.addActi onListener(this);
setSize(300, 150);
show();
}
protected void addlmpl(Component comp, Object constraints, int index) {
System.err.println(“adding “ + comp + “ with constraints “ + constraints
+ “ at index “ - index);
super.addlmpl(comp, constraints, index);
}
// Action handler for buttons
public void actionPerformed(ActionEvent evt) {
System.out.pri ntln(evt.getActi onCommand());
}
static public void main(String[] args) {
new Main();
}
}
West
Center
South
East
I
I КЛ RE 103: Container .addlmpl ()
I
I
]
(
1
I
addNotify()
purpose Creates rhe peers tor this container and its components.
SYNtw public void addNotifyO
ja\ a.awt
Container
Contained )
descripiion This method creates the container s peer if it does not exist. Since Container
is an abstract class, the actual peer created is based on a subclass of Con-
tainer. This method also calls addNotifyO on all the container’s children.
overrides Component .addNoti fyO-
seealso Component, Toolkit.
lx ample Sec Component. setVi si bl e О.
D
к
h
G
H
I
J
К
L
M
N
О
Contained)
pi rposi Constructs a new instance of Container.
syntax protected Container()
ntscRiPiiox This constructor is used when implementing a lightweight container. light-
weight container can contain lightweight or native components. The light
weight container must have an ancestor that is a native component. See the
Component class description for details on lightweight and native components.
see also Component.
example See class ItemSelectable. Il creates a lightweight container ButtonPanel
that contains AWT Button components.
Q
R
S
T
l
v
w
x
Y
z
countComponents()
pirpose Replaced by getComponentCountQ.
syntax public int countComponentsO
reti’rxs The number of components in the container.
deprecation Replace the usage of this deprecated method, as in
int howmany - container.countComponentsO ;
with
int howmany container.getComponentCount();
DEPRECATED
deliverEvent()
purpose Replaced by Component .di spatchEventO.
svniax public void deliverEvent(Event e)
PARAMETERS
e The non-nul 1 event to be delivered.
DEPRECATED
434
doLayouK)
OVERRUNS Component.deliverEvent О.
SEE ALSO Component.handleEvent().
doLayout() _
PURPOSE Invokes the layout manager on this container.
SYNTAX public void doLayoutQ
description This method invokes the layout manager to resize and position the container s components. Unlike validateQ, this method ignores the valid state of the container. Moreover, val idateO attempts to validate all of the descendants of the container, while doLayoutQ does not. Programs typically should not cull doLayoutQ directly; instead, they should call validated.
OVERRIDES Component. doLayoutQ.
SEE ALSO getLayoutQ. setLayoutQ, validated-
EXAMPLE See Component.di spatchEventQ. This example causes the components in the frame to change font size. doLayoutQ is called on the frame to resize all of its components and to again lay them out.
getAlignmentXf)
PURPOSE Retrieves this container’s preferred alignment along lhe v-axis.
SYNTAX public float getAlignmentXQ
DESCRIPTION This method returns the container’s л-alignment value, which is used by some layout managers to help place container’s components. Unlike the alignment property for a component, the alignment property for a container depends on how the container s children are laid out. In particular, lhe layout manager is responsible for determining the container's alignment value. See LayoutManager? for more details. If the layout manger for this container is not an instance of LayoutManager?, this method returns Component. CENTER AL IGNMEN1. For a different л-align- ment value to he returned, this method must he overridden.
RETURNS This component's .v-ulignment in the range 0<0f to 1,0f.
OVERRIDES Component.getAlIgnmentXQ.
SEE- ALSO get Al 1 gnmentYQ , LayoutManager? . getLayoutAl i gnmentXQ.
EXAMPI E See the LayoutManager? class example.
Container
getAlignmentYf I
java.awt
getAlignment Y()
РГRPOSE Retrieves this container's preferred alignment along they axis.
SYMAX public float getAl ignmentYQ
description This method returns the container's у-alignment value, which is used by some layout managers to help place the container's components. 1 nlike the align ment property for a component, the alignment property for a container depends on how the container's children arc laid out. In particular, the layout manager is responsible for determining the container's alignment \alue. See LayoutManager2 for more details. If the layout manger for this container is not an instance of LayoutManage r2. this method returns Component .CENTER-ALIGNMENT. For a different v-align- ment value to be returned, this method must be overridden.
RETt RMS This component's у-alignment in the range 0.0f to l,0f.
OVERRIDES Component .getAl ignmentYO.
SEE ALSO getAl i gnmentXO , LayoutManage r2 . get Layout Al ignmentYO .
EXAMPI Г See the LayoutManager2 class example.
getComponentO
pt rpose: Retrieves a component in this container.
SYNTAX public Component getComponent(int n)
DESCRIPTION This method retrieves the component at index n in this container. The index is zero-based, so the index of the first component is 0.
PARAMETERS
n The zero-based index of the component in this container.
RETERNS The non-nul 1 component at index n.
EXCEPI IONS
ArraylndexOutOfBoundsException
If n does not refer to a component.
SEE ALSO getComponentCountO, getComponentsO .
EXAMPLE See Component .di spatchEventO.
436
gctComponentAtt
getComponentAt)
PURPOSE Locates the component at a point in this container.
SYNTAX public Component getComponentAt(int x, int y) public Component getComponentAt(Point pt)
DESCRIPTION This method is used to determine which, if any, component is at the pixel coor- dinate specified by pt or x. y. The coordinates must be relative to this con- tainer's bounds, not to its insets. The returned component is a direct descendent of this container: that is, it does not recurse down the component hierarchy to find the actual component at the point. So, for example, if the container contains another container which in turn contains buttons, then getComponentAt0 can return only the subcon- tainer, not any of the subcontainer's buttons.
PARAMETERS Pt X У The point in this container. The л'Coordinate relative to this container's bounds. The V'Coordinate relative to this container's bounds.
RETURNS The component at the specified point, or the container itself if no component is at the point but the point is in the container. Returns null if the point is not in the container.
OVERRIDES Component.getComponentAt().
EXAMPLE See the class example.
getComponentCount()
PURPOSE Retrieves the number of components in this container.
SYNTAX public int getComponentCountO
RETURNS The number of components in this container.
example See Component.di spatchEventО.
getComponents()
PURPOSE Retrieves all of the components in this container.
SYNTAX public Component[] getComponentsC)
description This method retrieves all of the components in this container. The length of the returned array indicates the number of children in the container.
Container
java.awt
get In set s()
RLTIR4S set also E X WIPE E A non-null array of all the components in this container. getComponentO, getComponentCount(). See the class example.
A
В getlnsetsO
Retrieves this container's insets, public Insets getlnsetsO
Г) п Pl RPOSI: SX MAX
F tM SC RIPIIOS It this container's peer has not been created, the returned insets will be (0. 0. 0. 0).
G A container can override this method to modify the container\ default insets.
II I The override should take into account the peer's insets (i.e.- the override should call super.insetsO)- Therefore, if lhe override increases the default insets, the container should first retrieve lhe peer's insets and then add the
J extra insets.
К L A container’s insets are primarily used b\ the layout manager. Other objects such as mouse events and graphics contexts are based on the container peer s insets and ignore the results of an overridden insetsO method. In particular.
M the mouse coordinate (0. 0) is situated at
N О (boundsО .x+peer.insetsO -left, bounds() .y+peer. insetsO .top).
P Also, when a graphics context is created on the container, (0. 0) of the graphics
Q context is at the same location.
RFJl RXS
R A non-null instance of the container's insets, inixll This instance should not be modified because it
S used by cop\ that
1 can be modified, use cl oneО -
I SEE: ,\E.S()
V w EXAMPLE: This example creates a frame that contains a 1 1 panel with a grid layout manager. See Figure 1 1 104. The frame overrides the getlnsetsO 3 1
x
Y V This causes the grid layout panel to be posi- tioned and resized within the new insets. *l<’1 kh 104: _ Container.getlnsetsO .
438
getlnse(s(
The frame also paints a 3-1) border around (he grid layout panel. This is to
demonstrate that the origin of mouse coordinates do not depend on the frame's
getlnsetsO override and are still relative to the peer's insets.
import java.awt.";
import java.awt.event. *;
class Main extends Frame {
int borderSize =- 8;
Main О {
super(“getlnsets Example”);
// Listen for mouse events
addMouseMotionLi stener(new vOuseMotionEventHandl er());
Button b ' new ButtonC'Button”) ;
addfb, BorderLayout.CENTER);
// Disable button to let mouse motion events pass through
b.setEnab1ed(false);
setSize(150, 200);
show() ;
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseFvent evt) {
System.out. printlnfevt .getXO * “, ” * evt.getYO);
}
}
public Insets getlnsetsO {
Insets insets - (Insets) (super.getlnsetsO) .clone();
insets.top borderSize;
insets.left +- borderSize;
insets.bottom +- borderSize;
insets.right += borderSize;
return insets;
}
public void paintfCraphics g) {
Insets insets = super.getlnsetsO ;
int w - getSizeO .width-insets, left insets.right;
int h - getSizeO.height-insets.top insets.bottom;
g.setColor(new Color(200, 100, 100));
for (int i=0; i<borderSize; i++) {
g.draw3DRect(i+insets.left, i+insets.top,
w-2*i -1, h-2*i-l, i<borderSize/2);
}
}
static public void main(String[] args) {
new Mai n();
}
}
Container
getLayout()
java.awt
getLayoutO
PURPOSE SYNTAX Retrieves this container's layout manager, public LayoutManager getLayoutO
A в D RETURNS SEE A [.SO EX AMPLE This container's layout manager. The return value may be null. doLayoutO. setLayoutO. See setLayoutO.
E F G H I J К L M N 0 P Q R S T getMaximumSize()
purpose Calculates this container's maximum size dimensions. syntax public Dimension getMaximumSize() description By default, this method determines the maximum size of this container based on the layout's maximum size. In particular, if the layout manager is an instance of LayoutManager2 and is not null, the result of calling the layout manager’s maximumLayoutSize() method is returned. Otherwise, the dimen- sion returned is that of Component.getMaximumSizeО. Note that if this method is overridden, the maximum si/e must include the con- tainer's insets. returns A new non-nul 1 dimension object containing this component's maximum size. overrides Component .getMaximumSizeO. seealso getMinimumSizeO, getPreferredSize(), Component.getSize(), 1ayoutManager2,maximumLayoutSize(). getMinimumSize()
u V w X Y z PURPOSE SYNTAX DESCRIPTION Calculates this container’s minimum size dimensions. public Dimension getMinimumSizeO By default, this method uses the container’s layout manager to determine the container’s minimum size. In particular, if the layout manager is not null, the result of calling the layout manager’s minimumLayoutSizeO method is returned. Note that if this method is overridden, the minimum size must include the con tainer’s insets. For example, if the container must display a 10-x-lO pixel
440
geiPreferredSizef)
image and has an inset border of 3 pixels on all edges, then the minimum size is 16 x-16.
RETURNS A non null dimension object containing the container s minimum size.
OVERRIDES Component.getMi nimumS i ze().
SEE ALSO getMaximumSizeO , getPreferredSizeO , Component. getSi zeO , LayoutManager.minimumtayoutSi ze().
example See the LayoutManager class example.
getPreferredSize()
PURPOSE Calculates this container's preferred size dimensions.
SYNTAX public Dimension getPreferredSi zeO
DESCRIPTION By default, this method uses the container's layout manager to determine this container's preferred size. In particular, if the layout manager is not null, the result of calling the layout manager's prefer redLayoutSizeQ method is returned. Note that if this method is overridden, the preferred size must include the con- tainer's insets. For example, if the container must display a IO-x-lO pixel image and has an inset border of 3 pixels on all edges, then the preferred size is 16-X-16.
RETURNS A non-nul 1 dimension object containing the container’s preferred size.
OVERRIDES Component.getPreferredSizeO.
SEE ALSO getMaximumSizeO, getMinimumSizeO, Component .getSizeO , LayoutManager.preferredLayoutSize().
example See the LayoutManager class example.
insets() DEPRECATED
PURPOSE Replaced by getlnsets0.
SYNTAX public Insets insetsO
returns A new non null instance of the container’s insets.
deprecation Replace the usage of this deprecated method, as in Insets ins - cont. i nsetsQ ; with Insets ins = cont.getlnsetsO;
Container
invalidate*)
java.awt
invalidated)
Pl RPOSL Invalidates this container.
SYMAX public void invalidate()
DLS( RIP l ЮХ This method invalidates this container and all of its ancestors. See “Layout Management” earlier in the class description discussion and the val idateO method for more details about the valid state.
OVPRRIDF s Component. i nval idateO .
SUL \l SO L ayoutManager?.inva1i da telayout?О, validate().
LA XMPl 1 See Component.setVi si ble().
isAncestorOft)
pi rposl Determines if this container is an ancestor of a component.
SYNTAX public Doolean isAncestorOf(Component comp) dlscripiion This method determines whether the component comp is in the hierarch} of components rooted at this container. PARAML I LRS comp The component to check. rktcrns true if this container is an ancestor of comp: false otherwise. SF-F. also Component.getParent(). t v Л. к A f »l Г_ 1 lit «1 1*Мл1 £ & i * n A Ilt.bL f I T г V i • t 1 1 1 T 1 1 tl L. ~
Г ЧЛМГ1 Г 1 lin L.A4.I]II|/JC LI I W V tVHUI 1 J J 1 1 (panels) of buttons (see Figure ’ 105) and keeps count of how man} times buttons on each col- umn are clicked using a shared action listener. The listener checks whether the button clicked is con- tained in the hierarchy ot the left panel, fhe same effect could have 1 . isAncestorOf example EJ
button! button!
button2 button?
buttons t — t |buttonsi
left hits=2 right hits-4
been achieved using separate action listeners, one for each HGI panel. RK 105: Container. isAncestorOf О .
import java.awt.*;
import java.awt.event . ;
class "Main extends Frame implements ActionListener {
int leftHits - 0. rightHits - 0;
442
java.awt voniainer
layoutt )
Label scoreBoard = new Iabel(“left hits-0 right hits=0");
Panel left;
MainQ {
super(“isAncestorOf example");
// create left buttons
left = new Panelfnew GridLayout(О, 1));
Button b;
left.add(b - new ButtonCbuttonl"));
b.addActionListener(this);
left.add(b - new Button(“button2"));
b.addActionl istener(thi s);
left.add(b = new Button(“button3")):
b.addActionLi stener(thi s);
// create right buttons
Panel right = new Panel(new GridLayout(0, 1));
right.add(b ~ new ButtonCbuttonl")) ;
b.addActionListener(this) ;
right.add(b new Button("button2’'));
b.addActionLi stener(thi s) ;
right.add(b - new Button("button3”));
b.addActionLi stener(this):
add(right, BorderLayout.EAST);
addfleft, BorderLayout.W'FST);
add(scoreBoard, BorderLayout.SOUTH);
setSize(300, 150);
show();
}
// Action handler for buttons
public void actionPerformed(ActionEvent evt) {
if (left.isAncestorOf((Component)evt.getSource())) {
++leftHi ts;
} else {
++ri ghtHi ts;
}
scoreBoard.setText(“l eft hits-" + leftHits ♦ “ right hits=" * right
Hits);
}
static public void main(String[] args) {
new Main О;
}
}
layoutf)
DEPRECATED
PURPOSE
syntax
DEPRECATION
Replaced by doLayoutQ.
public void layoutO
Replace the usage of this deprecated method, as in
container. layoutO ;
with
Container
ja\ a.aw t
list( )
contai ner. doLayoutO ;
o\errides Component. layouts).
list()
В -
pi rpose: Prints a listing of this container's component hierarch}.
1) Е F Ci syntax public void 1ist(PrintStream out, int indent) public void 1ist(PrintWriter outwriter, int indent) description This method rccursixel\ prints the —rzn—i Inix| results ol calling toStri ng() on each of the container’s descendants. OK [ Cancel | The component hierarch} is tra-
H 1 versed in depth-first order. Children that are deeper down the hierarch}
J are printed with more indents. The first line of output is printed with
К i ndent spaces.
L PARAMETERS
M indent The indentation of the first line of
N out The non-nul 1 output stream in
() which to print.
i> outwriter The non-nul 1 output writer to 1 IGl RI 106: Container.1 ist() .
i Q which to print. overrides Component.1ist().
R S see At so Object.toString(). example "This example creates a frame with main nested containers. Sec Figure 106.
1 I’ Pressing Г1 prints the frame’s entire component hierarch}, import java.awt.";
V import java.awt.event.*; class Main extends Frame {
w Main() { super(“l'st Example”);
X Panel p == new Panel (new BorderLayout());
Y Panel card = new Panel(new Card!ayout()); add(card, BorderLayout.NORTH);
Z p •= new Panel (new FlowLayout ()) ; p.add(new Button(”0K”)); p.add(new Button(“Cancel”)); card.add(p, “1”);
444
г
list()
р = new Panel(new GridLayout(l, 0));
p.add(new BoxO);
card.add(p, “2”);
p = new Panel();
p.setLayout(nul1);
for (int i=0; i<10; i++) {
p.add(new BoxO);
}
p.add(new ButtonC'Button”))
add(p, BorderLayout.CENTER);
setSize(350, 350);
this.addKeyListener(new KeyEventHandlerQ);
show();
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() — KeyEvent.VK_F1) {
1i st(System.out);
}
}
static public void main(String[] args) {
new MainO ;
class Box extends Component {
Color c - new Color(random(256), random(256), random(256));
Box() {
setBounds(random(150), random(150)t 25, 25);
int random(int r) {
return (int)(Math.floor(Math.random()*r));
public void paint(Graphics g) {
g.setColor(c);
g.fi1IRect(0, 0, getSize().width, getSizeO.height);
g.setColor(Color.black);
protected String paramStringO {
String str = super.paramStringO ;
return str + “,color=” + c;
}
}
OUTPUT
Mai n[0,0,218x241,layout»java.awt.BorderLayout,resizable,ti tle=li st Example]
java.awt.Panel[4,23,210x34,layout®java.awt.CardLayout]
java.awt.Panel[4,23,210x34,layout®java.awt.FlowLayout]
Container
locate!)
java.awt
java.awt.Button[63,5,32x24,label=OKj
java. awt .Button [100, 5,46x24 , label -^Cancel ]
java,awt.Panel[0,0,0x0,hidden,layout=java.awt.GridLayout]
Box [4,23,0x0, col or-java. awt .Color [r=.?45, g=49,b-99j 1
java.awt.Panel[4,57,210x180]
Box[115,0,25x25,col or-java.awt.Color[r-147,g=183,b=170l1
Box[55,47,25x25,col or-java. awt. Color [r-68, g-=42 , b-86] ]
Box[39,5,25x25,col or-java.awt.Color[r-174,g=169,b-240]]
Box[132,93,2 5x2 5,color=java.awt.Col or[r=70,g-101,b-217Jj
Box[58,19,25x25.color-java.awt.Col or[r-182,g=236,b-10711
Box[122,105,2 5x25,colorsjava.awt.Col or[r-255,g-140,b=l21]]
Box[13,55,25x25,colorsjava.awt.Color[r-97,g-88,b=233]J
Box[30,133,25x25,color=java.awt,Color[r=152, g^l8,b=87]]
Boxfl,145,25x25.color-java.awt.Color[r-187,g=l76,b-4211
Box [117,136,25x25 , co lor-java, awt. Color [r-147,gM 34, b=l 771 '>
java.awt.Button[0,0,0x0,1abel=Button]
G H locate() DEPRECATED
1 Pl’RPOSE; Replaced by getComponentAtO.
J SV MAX public Component locate(int x, int y)
К PARAMETERS
I. X The v coordinate relative to the container's hounds.
У The у-coordinate relative to the container's bounds.
M
K' Rl ll R\S The component at x. у, or the container itself if no component is al x. у but x.
sx у is in the container. Returns null if x, у is not in lhe container.
0 DEPRECATION Replace the usage of this deprecated method, as in
p Component target - contai ner. 1 ocate(x , y};
with
Component target = container.getComponentAt(x, y);
R OVERRIDES Component.locate().
S
T minimumSize() depreca ted
U v pirpose: Replaced by getMinimumSizeO.
vv X S> NT XX Rl;!l RNS DEPRECATION public Dimension minimumSizeO A non-null dimension object containing the container s minimum si/e. Replace the usage of this deprecated method, as in
Y Dimension dim - container.minimumSize():
Z with
Dimension dim = container.getMinimumSizeO ;
OVERRIDELS Component.mi nimumSize().
446
paintf
paintQ___________________ ________________________ _______________________
purpose Called io repaint ibis container.
syntax public void paint(Graphics gc)
description This method is called whenever some part of this container needs to be
repainted. The graphics context gc should be used to repaint the damaged area.
The system automatically clears the damaged area with this container's back-
ground color before calling this method.
This method» if not overridden, looks for any lightweight children that inter-
sect ge’s clipping area. If any are found, their paint() methods are called.
The damaged area is not necessarily the whole area of this container. To dis-
cover the damaged area, call gc.getClipBoundsO Note that when this con-
tainer is made larger, the clipping area may include only the new area. If as a
result of enlarging this component some other part of the container changes
and needs to be repainted, a call to repaint() must be made so that the area
can be repainted.
If this is a native container, three properties of gc are initialized with values
taken from the same three properties of this component. The properties are the
background color, the foreground color, and the font.
If this method is overridden, it should call super. pai nt () after painting itself
to ensure its lightweight descendants are painted properly.
PARAMETERS
g<=
OVERRIDES
SEE ALSO
example:
rhe non-nul 1 graphics context on which to paint this component.
Component. pai ntQ.
Component.repaintO, Component.update О, paintComponentsf).
This example demonstrates how a native
container can implement double-buffering
to eliminate the flickering of its light
weight descendants. The example defines
a button that blinks when you rollover the
button. It places the buttons so that they
overlap each other. See Figure 107.
Without the double-buffering, all the but
tons would flicker as the current burton
blinked. The double-buffer is created in
the frame s pai nt О method. If the
dimensions of the frame increases, a new
buffer is created.
* Container.pai..
FIGURE 107: Container .paintО .
Container
java.awt
paint()
import java.awt.-;
import java. awt. event . :
class Main extends Frame {
Main() {
super(”Container.paint Fxample”);
// The method causes getlnsetsQ to return correct results.
addNoti fy();
// Get the frame’s insets.
Insets insets = getlnsetsO;
// Add a few buttons.
for (int i-0; i<4; i+*) {
FakeButton fb = new FakeButton(”Push Me”);
add(fb, 0);
fb.setBounds(insets.left+iA20, insets.top*iA‘20t 100, 101
1
// Show the frame.
setLayout(nul1);
setSize(300, 300);
show();
}
public void paint(Graphics g) {
update(g);
}
Image bbuf;
Graphics bbufG;
public void update(Graphics g) {
FontMetrics fm = g.getFontMetrics();
int w = getSize().width;
int h = getSize().height;
// Create or enlarge the double-buffer if necessary,
if (bbuf == null
I i bbuf.getWidth(null) < w
II bbuf.getHeight(nul1) < h) {
bbuf createlmage(wf h) ;
bbufG = bbuf.getGraphics():
}
// Needed to workaround a bug in lava 1.1.2.
bbufG.setClip(0, 0, w, h);
// Paint all of the lightweight’s children.
super.pai nt(bbufG);
// Show the double-buffer.
g.drawlmage(bbuf, 0, 0, this):
}
public static void main(String[] args) {
new Main();
}
}
448
paint
class FakeButton extends Component implements Runnable {
String label;
boolean blink - false;
boolean blinkOn;
FakeButton(String 1) {
label = 1;
// Listen for mouse clicks.
addMouseListener(new MouseFventHandle г());
// Start the blinking thread.
(new Thread(this)) . startO ;
}
public void paint(Graphics g) {
FontMetrics fm = g.getFont^etrics();
int w = getSizeO .width;
int h = getSizeO • height;
g.setColor(Color.black);
g.fi11Rect(0, 0, w, h) ;
// Paint component text.
if (blink && blinkOn) {
g.setColor(Color.red);
} else {
g.setColor(Co lor.white);
}
// Paint label and outline.
g.drawstring(label, (w-fm.stringWidth(label))/2,
(h fm.getHeightO)/? + fm.getAscentO);
g.drawRect(0, 0, w-1, h-1);
class MouseEventHandler extends MouseAdapter {
public void mouseEntered(MouseEvent evt) {
// Start blinking,
blink true;
repaint();
}
public void mouseExited(MouseEvent evt) {
// Stop blinking.
blink = false;
repaint();
}
}
public void run() {
while (true) {
try {
blinkOn - 'blinkOn;
if (bl ink) {
repaint();
1
Thread.sleep(2S0) ;
} catch (Exception e) {
}
}
java.awt
Container
paintComponcnlst)
}
}
paintComponents()
H R POSE Paints the container s components on a graphics context.
SYNTAX public void paintComponents(Graphics gc) This method is called b\ the AWT system in response to a request to paint this container's components and all of their descendants. It can cither paint directly on gc or call each of the component’s pai ntAl “1 О methods. The main differ- ence between this method and paintAl 1 () is that this method does not cause this container pai nt О method to be invoked. I'he default implementation of this method calls Component.paintAl10 on all of this container's components. Note: In Java 1.1.2, this method does not work.
PXRAMETERS
gc I'he non-nul 1 graphics context on which to paint the container's children.
SEE XI SO Component.pai nt(). Component.pai ntAl1(), pai nr().
EXAMPLE See Component.pai ntAl1().
parainString()
Pl RPOSE Generates a string representing the container's state.
SV XTAX protected String paramStringO
DESCRIPTION The returned string includes the container's layout manager. A subclass of this class should override this method and return a concatenation of its state with the results of super.paramStringO. This method is called by the toStri ng О method and is t\ pieally used for debugging.
REI I’RNS A non-nul 1 string representing the container's state.
OVERRIDES Component. paramSt ri ngO •
Si E ALSO Component.toStri ng О, java.1ang.Object.toStri ng О.
EXAMPLE See Component.pa ramSt ring 0.
450
preferredSizetI
DEPRECATED
PURPOSE: Replaced by getPrefer redSize().
syntax public Dimension preferredSize()
returns Л non-nul 1 dimension object containing the container's preferred size.
OVERRIDES Component.preferredSize().
deprecation Replace the usage of this deprecated method, as in Dimension dim = container.preferredSizeO ; with Dimension dim container.getPreferredSize();
print()
PURPOSE: Prints this container s components on a graphics context.
SYNTAX public void printfGraphics gc)
DESCRIPTION This method prints this container onto the graphics context gc. This method, if not overridden, looks for any lightweight children that intersect gc's clipping area. If any are found, their pri nt О methods are called. If this method is overridden, it should call super.paint() after painting itself to ensure its lightweight descendants are painted properly.
PARAMETERS gc The non-nul 1 graphics context on which to print.
OVERRIDES Component.print 0•
SEE ALSO paintO , printcomponents О •
example- See the Pri nt Job class example.
printComponents()
PURPOSE Prints this container's components on a graphics context.
SYNTAX public void printComponents(Graphics gc) This method is called by the AWT system in response to a request to print this container's components and all of their descendants. This method can either print directly on gc or call each of the component's pri ntAl 1 () methods. The main difference between this method and pri ntAl 1 () is that this method does not cause this container's printO method to be invoked.
java.au t
Container
processContai nerEvenu)
I'he default implementation of this method calls Component.printAl 1 () on
all of this container's components.
PARAML HiRS
gc l he non-nul 1 graphics context on which to print the container's components.
sff also Component. print O- Component .pri ntAll ().
example See Component. pai ntAll Q,
D
F.
F
Ci
H
I
J
К
L
M
N
()
P
Q
R
S
T
t:
v
w
x
Y
Z
processContainerEvent()
pi rposl Processes a container event enabled lor this container.
syntax protected void processContai nerEvent(Contai nerEvent evt)
description Container events are fired when a component is added or removed from a con-
tainer. See ContainerEvent for more details. This method processes con-
tainer events for this container by calling any registered Contai nerLi stener.
This method is invoked only if container events have been enabled for this
container. This can happen either when a container listener is added to this
container or when container events are explicitly enabled via the use of Com-
ponent .enableEventsO.
Typically, a container controls how its container events are processed by add-
ing or removing container listeners. It overrides processContainerEvent()
only if it needs to do processing in addition to that performed by the registered
listeners.
When a container does override processContainerEvent(), it should call
super. processContai nerEventО to perform lhe processing intended by its
base class (such as dispatching the listeners).
PARAMETERS
evt l he non-null container event.
sff also addContai nerLi stenerQ , Component .enableEventsO T
Component. di sabl eEvents Q , java. awt. event.Contai nerAdapter,
java.awt.event.Contai nerEvent,
java.awt.event.Contai nerLi stener, processEvent(),
removeContai nerLi stener().
examplj- See AWTEventMul ti caster .componentAddedО.
processEvent()
purpose Processes an event enabled for this container.
452
remove!
SYNTAX protected void processEvent(AWTEvent evt)
DESCRIPTION This method extends Component.processEventO by adding support for ContainerEvent. When a container does override processEventO, it should call super.pro- cessEventO to perform the processing intended by its base class (such as dispatching the listeners).
PARAMETERS evt The non-nul 1 event.
OVERRIDES Component.processEventO.
SEE ALSO addContai nerLi stenerO < Component. enableEventsO » Component.di sableEvents(), j ava.awt.event.Contai nerFvent, java.awt.event.ContainerListener, processMouseEventО, processContainerLventQ , removeContainerl istenerO .
EXAMPLE See Component's class example.
removeO
PURPOSE Removes a component from the container.
SYNTAX public void remove(Component comp) public void remove(int pos)
DESCRIPTION When a component is removed» its peer is first destroyed and then removed from the container's list of components. Also, the layout manager is notified of the removal by way of the LayoutManager. removeLayoutComponentO method. The container and all of its ancestors are also invalidated. A container event is fired, and if container events have been enabled for this container, any container listeners for this container are notified.
PARAMETERS comp pos The non-null component to be removed. The zero-based index of the component to remove.
SEE ALSO add(), java.awt.event.Contai nerEvent, LayoutManager,removeLayoutComponentO,removeAl1().
example See the class example.
removeAHQ
purpose Removes all of the components in this container.
SYNTAX
public void removeAl1 О
Container
java.awt
removeContai ner Listened J
dlscripi ios This method removes all of the components in the container. It is equivalent to calling remove О on each component. The layout manager is notified of the removal of each by way of the LayoutManager. removeLayoutComponentO method. The container and all of its ancestors are also invalidated.
A see also add(), LayoutManager. removeLayoutComponentO. removeO.
в i x ampi f See the class example.
D E t (i removeContaincrListener() pr rpose Removes a listener from receiving this component's container events. syniw public void removeContainerListener(Containert istener listener)
11 1 description Container events are fired when a component is added or removed from a con- tainer. See Contai nerEvent for more details. After this method is called, the container listener listener will no longer receive container events from this
J container. If 1 i stener is null, this method does nothing.
К PARAMETERS
L 1 i stener l he possibly nul 1 container listener to remove. see At so addContainerl i stenerO , java.awt.event.ContainerAdapter,
M java.awt.event.ContainerEvent, java.awt.event.ContainerListener.
N О example See removeActionListenerO in Menuitem.dispatchEventsO.
P remove\otify()
О
R s plrpose Destroys the peer hierarchy of this container and all of its children. SYMAX public void removeNotifyO
I t; description This method destroys the peer hierarchy of this container and all of its chil- dren, if any. This method should never be called directly. It is normally called by the component's container.
V ovf-rrides Component. removeNotifyO.
w V see al so Component, Toolki t.
A V z setLayout() pt'rpose Sets the layout manager for this container. syntax public void settayout(LayoutManager mgr)
454
scil.ayc
description This method sets mgr to he this container's layout manager mgr can be null.
This means the components in the container will not be moved or resized.
parameters
mgr
SEE AbSO
EXAMPLE
The layout manager to set for the con
tainer.
getLayout(). layoutO.
This example creates a row of buttons
and a panel with a card layout manager.
See Figure 108. Clicking a button
causes the card layout panel to display
the component identified by the button.
For example, clicking the TextArea
button displays a TextArea compo-
nent.
FIGI. RE HIS: Container. setLayoutO
import java.awt.";
import java.awt.event.*;
class Main extends Frame implements ActionListener {
Panel flow - new Panel();
Panel card = new Panel Q;
Main() {
superCsetLayout Example”);
flow, set Layout (new FlowLayoutO);
card.setLayout(new Cardlayout());
addComp(“Button”, new Button(“Button”));
addComp(“TextArea”, new TextArea(“TextArea”));
addCompCList”, newlistO);
add(flow, BorderLayout.NORTH);
add(card, BorderLayout.CENTER);
setSize(200, 200);
show();
}
void addComp(String label, Component c) {
Button b - new Buttonflabel);
card.add(c, label);
flow.add(b);
b.addActionLi stener(th is);
public void actionPerformed(ActionEvent evt) {
String arg - evt.getActionCommandO;
CardLayout 1 ~ (CardLayout)card.getLayout();
l.show(card, arg);
}
java.awt
Container
validaie()
static public void mainCStringfl args) {
new Mai n();
г
}
I)
H
F
G
II
I
J
К
validateO
PlRPOSE
SV MAX
DESCRIPTION
OVERRIDES
si-.i: Ai so
Validates this container by again laying out its components.
public void validateO
If the container is invalid, this method validates it by calling the doLayoutO
method; otherwise, the method call is ignored. After the container is validated,
this method calls validateO on each of the container's components. How-
ever, note that for efficiency, the validateO method is not invoked on valid
children. So if the valid child contains an invalid child, the invalid child will
not be validated.
Component .validateO.
doLayoutO, invalidateO, LayoutManager, val i datel ree().
L
VI
N
()
P
Q
R
S
T
L
V
I ' validate E ВИЗ E3
Leftl Left 1 Right 1
Left 2 Left 2 Right 2
Left3 Left3 Right Э
i — *оге" >>>» . . Less... Right 4
HGI RE 109: Container, val idateO .
exampi e This example demonstrates how to dynamically show and hide a set of compo-
nents in a dialog box. When a component is shown or hidden in a container,
the container is automatically invalidated. However, vou must explicitly vali-
date the container to update the layout. See Figure 109.
W import java.awt.-;
import java.awt.event.*;
X
class Main extends Frame implements ActionListener {
Y Panel extraButtons = new Panel(new GridLayout(0, 1));
Main О {
Z super(”validate Example”);
Panel p = new Panel(new Gridl ayout (0, 1));
p.add(new Button(“Left 1"));
456
validaieTree(
p.add(new Button(“Left 2”));
p.add(new Button(“Left 3”));
Button b;
p.add(b = new Button(“More...’’));
b.addActionListenerCthi s);
addCp, BorderLayout.CENTER);
extraButtons.add(new Button(“Right 1”));
extraButtons.add(new Button(“Right 2”));
extraButtons.add(new Button(“Right 3’’));
extraButtons.add(new Button(“Right 4”));
extraButtons.setVi sible(false);
addfextraButtonsr BorderLayout.EAST);
setSize(200, 200);
show() ;
}
public void actionPerformed(ActionEvent evt) {
String arg = evt.getActionCommandO;
Button button = (Button)evt.getSourceO;
if (“More. ..11 .equals(arg)) {
button.setLabel(“Less,..“);
extraButtons.setVi sible(true);
//inval idateO ; - not necessary
validateO ;
} else if (“L ess.equals(arg)) {
button.setLabel(“More...”);
extraButtons.setVisible(false);
//invalidateO; - not necessary
validateO;
}
}
public static void main(String[] args) {
new MainO;
}
}
validateTreeO
PURPOSE: Called by validateO to again lay out the components in this container.
SYNTAX protected void validateTreeO
DESCRIPTION This method is used by validateO to recursively lay out again this con- tainer's components and their descendants. Any locking necessary should be performed by the caller of validateTreeO before invoking validate- TreeO. A method that needs to perform special processing when validating components in a tree should override this method (instead of validateO),
SEE ALSO doLayout(), invalidateO, LayoutManager, validateO,
java.awt.event
ContainerAdapter
A
я InerAdaptci
R
D
Syntax
public abstract class ContainerAdapter implements Container!..!stener
Description
1 The container adapter is a container listener in which all callback methods arc empty imple-
G mentations, lite purpose of the container adapter is to make it more convenient for an object to
listen for container events. In particular, by using the container adapter, you need to implement
only those callback methods in which you are interested. Without lhe container adapter, you
1 must implement all callback methods, even if lhe method is empty.
j To use a container adapter, you create a subclass of ContainerAdapter and oxerride the
desired callback methods. You then create an instance of the container adapter subclass and
call the container’s addContainerListenerO method with it. l he container adapter sub-
L class is typically an inner class.
M
N MEMBER SUMMARY
<> Container Event Callback Methods 1
p component Added О Called after a component has been added to a container,
component Removed О Called after a component has been removed from a container
Q --------------------------------------—---------------------- --------
R
,S
See Also
Contai nerEvent, Contai nerLi stener, java.awt.AWTEventMulticaster,
t; java.awt .Container.addContainerListenerO , java.uti 1.Eventlistener.
v
Example
See the Contai nerEvent class example for a simple usage of a container adapter.
X
V
Z
458
componentAddedO
[componentAddedO
PURPOSE Called after a component has been added to a container
SYNTAX public void componentAdded(ContainerEvent evt)
description This method is called after a component has been added to the source con- tainer. The added component can be retrieved by calling evt.getChildO- This method, by default, has an empty implementation.
parameters evt The non-nul 1 container event.
example See the ContainerEvent class example.
componentRemo ved()
purpose Called after a component has been removed from a container.
syntax public void componentRemoved(ContainerEvent evt)
DESCRIPTION This method is called after a component has been removed from the source container. The removed component can he retrieved by calling evt.get- ChildC). This method, by default, has an empty implementation.
PARAMETERS evt The non-nul 1 container event.
EX AM PL,L See the ContainerEvent class example.
java.awt.event
Contai nerEvent
".pcr.erv
containerEvent
si
Syntax
public class ContainerEvent extends ComponentEvent
Description
Container events are fired by a container (see Container) whenever a component is ad
removed from the container For more general information about events, see AWTEvent.
Listening for Container Events
To listen for container events from a container the listener must implement the Compo-
nentLi stener interface. After that, the listener must be registered with the object. It becomes
registered by calling the object's addContai nerLi stener() method.
An alternative, and possibly more convenient, way of receiving container events is to use
a container adapter See Contai nerAdapter for more details.
Like most events, a container event is delivered to its listeners after the operation has
taken place.
U
V
W
X
Y
Z
460
Container Event Flow
Figure HO shows how container events typi-
cally flow through the system. First, the event
is fired by some container peer in response to
some user gesture. This event is posted on the
event queue (see EventQueue). When the
event makes its way to the front of the queue, it
is given to the component via its di spatchEv-
entO method. The main purpose of this
method is to discard the event if the container
event type is not enabled or if there are no con-
tainer event listeners. Otherwise, di s-
patchEventO calls processEventO, which
in turn calls different methods depending on
the event type. Since this is a container event
processContainerEventO is called. The
main purpose of this method is to notify the
container event listeners.
ContainerPeer
System
Event
Queue
Contai ner
Conta inerEvent
di spatchEventO
processEventO
processContainerEventO j
Container! istener
FIGURE 110: Container Event Flow.
A component can override processCon-
tainerEventO to process container events before they are delivered to its listeners. The
overridden method should call super.processContainerEventO io ensure that events are
dispatched to the container's listeners.
|M|tMBER summary
Constructor
ContainerEventО
Property Methods
getChildO
getContainerO
Component Event Constants
COMPONENT „ADDED
COMPONENT-REMOVED
CONTAINER-FIRST
CONTAINER „LAST
Debugging Method
paramStri ngQ
Constructs a ContainerEvent instance.
Retrieves the component that was added or removed.
Retrieves the event's source component.
Indicates that a component has been added.
Indicates that a component has been removed.
Constant specifying the first id in the range of container event
ids.
Constant specifying the last id in the range of container event
ids.
Generates a string representing the container event's state.
ContainerEvent
java, aw Lev ent
See Also
ContainerAdapter, ContainerListener, java.awt.AWTEvent.
A
В
Example
L>
E
P
G
H
I
J
К
1.
M
N
О
P
Q
R
S
T
I'
V
This example demonstrates how to listen to and
handle container events. The example creates a
frame with a button (called “New Button") that
adds new buttons to the frame. The new buttons
(called “Remove Me”), when clicked, remove
themselves from the frame. Sec Figure 111.
l he frame listens for container events on itself.
and whenever a button is added or removed, the
frame gets a container event. In response to the
event, the specifics of the event arc printed. Also
< ContainerEvent Example HL"I E3
New Button | Remove Me 21
Remove Me 3 Remove Me 5
Remove Mg61
FIG I'RE 111: ContainerEvent
printed is the child that was added or removed and the new number of children in the con
tai ner.
w
X
Y
Z
import java.awt.'';
import java.awt.event;
class Main extends Frame implements ContainerListener, ActionListener {
MainQ {
superC’ContainerEvent Exampie”);
Button b -= new ButtonC’New Button");
// Listen for events.
b.addActionl i stener(thi s);
addContainerLi stener(thi s);
// Layout component
set!ayout(new FlowLayoutQ) ;
add(b);
setSize(100, 100);
show();
}
// Container event handler methods
public void componentAdded(Containerhvent evt) {
System.out.println("COMPOKLNT_ADDED: "+evt.getChi1d());
System.out.println(" There are now "
+evt .get Contai ner() . get Component Count ()+” children. ’’) ;
}
public void componentRemoved(ContainerEvent evt) {
System.out. pri nt 1 n(,,COMPONENT_REMOVFD: ”+evt. getChi 1 d()) ;
System.out.println(" There are now "
+evt.getContai ner().getComponentCount()+" chiIdren.");
}
// This increasing number is used in naming the new buttons.
int count;
462
COMPONENT ADDED
// Action event handler method
public void actionPerformed(ActionFvent evt) {
if (evt.getActionCommandO .equals("New Button1')) {
// Add a button.
Button b - new Button(,rRemove Me " + (count ь<)) ;
// Listen for events.
b.addActionListener(this);
add(b);
validateO; // relayout container
} else if (evt .getActionCommandO . startsWithC'Remove Me ’*)) {
// Remove a button.
remove((Component)evt. getSourceO);
validateO; // relayout container
}
}
public static void main(String argsLJ) {
new Main();
}
COMPONENT. A DDED
PURPOSE Event id indicating that a component has been added.
SYNTAX public static final int COMPONENT-ADDED
DESCRIPTION An event with this id (value 300) is fired by a container after a component has been added to it. The added component can be retrieved by calling get ChildO.
SEE ALSO get€hild(), java.awt.Container.add()
EXAMPLE See the class example.
COMPONENT. REMOVED
PURPOSE Event id indicating that a component has been removed.
syntax public static final int COMPONLNT_RFMOVED
DESCRIPTION An event with this id (value 301) is fired by a container after a component has been removed from it. The removed component can be retrieved by calling getChild().
SEE ALSO getChi 1d(), java.awt.Container.remove().
example See the class example.
ContainerEvent
containS’itI^F
java.awi .event
CONTAINER-FIRST
purpose Constant specifying the first id in the range of container event ids.
syntax public static final int CONTAINER FIRST
description /Ml component event ids must be greater than or equal to CONTAINER-FIRST
(value 300).
SEE At50 CONTAINER-LAST.
t xample See java.awt .Component.processEventO.
1 CONTAINER-LAST
G ....... ......... ~ [
purpose Constant specifying the last id in the range of container event ids.
H
SYNiA.x public static final int CONTAINER-1 AST
I
description All container event ids must he less than or equal to CONTAINER-LAST (value
J 301).
K SH-AISO CONTAINER FIRST.
h example See java.awt .Component.processEventO.
M
ContainerEventO
о “
p PURPOSE; Constructs a ContainerEvent instance.
Q SYNTAX public ContainerEvent(Component source, int id, Component child)
R DESCRIPTION This constructor creates a new container event instance with source as the container firing this event.
S After the container event is created, the source container can distribute the
T event to its listeners by calling the container event-related methods in
U AWTEventMulti caster. If the event is not created by source, the creator can deliver the event to the source container either by posting the event to the event
V queue (see EventQueue. post EventQ) or by calling the source container's
w Component .di spatchEventO method directly.
X PAR X METERS
child T he non-nul 1 component being added or removed.
i d One of the container e\ ent ids.
z source The non-nul 1 container that is firing this container event.
464
JU V U. a w и и will
getChildO
FjgEAbSO getChi ld() , java.awt. AWTEvent. getIDO ,
java.awt.AWTEventMulticaster, java.awt.EventQueue,
java.uti 1. Eventobject.getSourceQ
getChildO________________________________ ________________________________
purpose Retrieves the component that was added or removed.
syntax public. Component getChildO
returns The non-nul 1 component that was added or removed from the container.
example See the class example.
getContainerO
PURPOSE Retrieves the event s source component.
SYNTAX public Container getContainerO
DESCRIPI ION This method returns the component that fired the container event.
RETURNS The non-nul 1 container that fired this event.
EXAMPLE See the class example.
paramStringO
PURPOSE Generates a string representing the container event's state.
SYNTAX public String paramStringO
DESCRIPTION The relumed string contains the name of the container event and the name of the child that was added or removed. A subclass of this class should override this method and return a concatenation of its state with the results of super. paramStringO. This method is called by the AWTEvent.toString() method and is typically used for debugging.
RETURNS A non-nul 1 string representing the container event's state.
OVERRIDES java.awt.AWTEvent.paramStri ng().
SEEALSO java.awt.AWT Event.toStri ng О. java.lang.Object.toString().
example See the java.awt.AWTEvent class example.
java.awt.event
Contai nerLi stener
A
в
D
L
F
G
H
I
J
К
1.
M
N
Syntax
public interface ContainerListener extends EventListener
P
Q Description
r When an object (listener) wishes to receive container events from a container (the source con-
tainer), two things must be done:
s
1. The listener must implement this interface and all the methods required b\ this interface.
2. The listener must be registered with the source container It becomes registered by mak
U ing a call to the source container's addContainerLi stenerO method.
V For information about container events, see ContainerEvent.
w
X MEMBER SUMMARY ~~|
V Container Event Callback Methods
t component Added О Called w hen a component has been added to a container.
component Removed О (.’ailed when a component has been removed from a container.
466
component Added ()
agee Also
ContainerAdapter, ContainerEvent, java.awt.AWTEventMulticaster,
java.awt.Container.addContainerListenerO, java.uti1.EventListener.
Example
See the ContainerEvent class example.
component Added()
PURPOSE Called when a component has been added to a container
SYNTAX public void componentAdded(ContainerEvent evt)
DESCRIPTION This method is called after a component has been added to the source con- tainer. The added component can be retrieved by calling evt. getChi Id().
PARAMETERS evt The non-null container event.
EXAMPLE See the ContainerEvent class example.
componentRemo ved()
PURPOSE Cal led when a component has been removed from a container.
SYNTAX public void componentRemoved(ContainerEvent evt)
DESCRIPTION This method is called after a component has been removed from the source container, lhe removed component can be retrieved by calling evt.getChild().
PARAMETERS evt The non-null container event.
example See the ContainerEvent class example.
java.awt.peer
ContainerPeer
A
в
D
E
E
G
H
[
J
К
I
M
N
o Syntax
public interface ContainerPeer extends Componentpeer
P
Q Description
R The container component (see the Container class) in the AWT uses the platform's native
implementation of a container. So that the AWT container behaves the same on all platforms,
c
the container is assigned a peer, whose task is to translate the behavior of the platform's native
T container to the behavior of the AWT container.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
v their peers. Only someone who is porting the AWT to another platform should be concerned
w with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
See Component and Toolkit for additional information about component peers.
468
ju va.awi.peci
beginValidate()
NUMMARY < *
peer Methods beginValidateO endValidateO getlnsetsO Signifies the start of validation of components in the container. Signifies the end of validation of components in the container. Retrieves the container's insets.
Deprecated Method
insetsO Replaced by get Inset s (). ।
See Also
java.awt.Component, java.awt.Container T java.awt.Toolkit.
begin Validatef)
purpose Signifies the start of validation of components in the container.
Syntax void beginValidateO
SEE also java. awt. Contai ner. val i dateO -
end Validate()
purpose Signifies the end of validation of components in the container.
syntax void endValidateO
SEE also java.awt.Container.vali dateO.
getlnsets()
purpose Retrieves the container's insets.
syntax Insets getlnsetsO
returns Anew non-nul 1 instance of the container’s insets.
SEE also java.awt.Container.getlnsetsO, java.awt.Insets.
ContainerPeer
insets()
java.awt.peer
insetsO
Pt RPOSE Replaced by getlnsetsO.
SYNTAX Insets insetsO
Rt-TCRNS A new non-null instance ol the container s insets
DEPRECATION Replace the usage of this deprecated method, as in Insets insets = peer. insetsO ; with Insets insets - peer.getlnsetsO ;
470
CropImageFilter
...>-________i
Syntax
public class CropImageFilter extends ImageFilter
Description
This class extends the basic ImageFilter class to extract a given rectangular region of an
existing Image and to provide a source for a new image that contains just the extracted region.
It is meant to be used in conjunction with a Fi 1 teredlmageSource object to produce cropped
versions of existing images.
Here is how the crop image filter is typically used:
Image copySubImage(Tmage image, Rectangle r) {
CropImageFilter filter - new CropImageFi1 ter(r.x, r.y, r.width, r.height);
return getToolki t().createlmage(new Fi1teredlmageSourcef image.getSource О,
filter));
}
MEMBER SUMMARY
Constructor Method
CropImageFi1ter() Constructs a new CropImageFi Iter instance.
Image Consumer Methods
setDimensi ons() Called by the image producer to deliver the dimensions of the source image.
setPixelsO Called by the image producer to deliver pixels to the image con- sumer.
setProperties() Called by the image producer to deliver the properties for the source image.
CropImageFilter
java, aw t. image
See Also
Fi1teredlmageSource, ImageFi1 ter, java.awt.Toolki t.createlmage().
В
J)
E
I
G
H
1
J
К
L
M
N
О
I’
Q
R
s
T
I
V
w
X
Y
Z
Example
This example implements a small application for
copying areas in an image (see Figure 112). The appli-
cation reads in an image and allows you to select rect-
angular areas in the image. To make a selection, you
click and hold the left mouse button and drag down-
ward and to the right. The pixels in the selected area
are painted in XOR mode (see Graphics.setXOR-
ModeO).
To make a copy of the selected area, press the ‘c‘
Щ Cropimage Example
EKU > RE 112: CropImageFilter.
key. The copy is created using the CropImageFilter image filter. You can then move the
copy around the image just by moving the cursor around. To paint the cop\ on the image, click
the mouse. To delete either the selected area or the copy, press any key.
When mo\ ing the copy around the image, you ill notice a lot of flickering. You can elim-
inate the nickering by using the double-buffering techniques demonstrated in the Compo-
nent .createlmageQ example.
import java.awt.-:
import java.awt.image.
import java.awt .event.
class Main extends Frame {
MainfString filename) {
super(“CropImage Example”);
try {
Image fileimage - getToolkit().getlmage(filename);
// Use a media tracker object to wait until all the pixels
// have been retrieved.
MediaTracker tracker ~ new MediaTracker(this);
tracker.addlmage(fi1 elmage, 0);
tracker.waitForID(0);
// Now copy the retrieved image to an offscreen image.
addNotifyO; // otherwise the following code will fail.
Image image - createlmage(filelmage.getWidth(this),
fi1 elmage.getHeight(thi s));
Graphics g = image.getGraphics();
g.drawlmageffilelmage, 0, 0, this);
g.disposeO ;
add(new ImageCanvas(image), BorderLayout.CENTER):
} catch (Exception e) {
e. pri ntStackTraceO :
}
setSize(300, 300);
show():
}
472
M.CI W L.lllta^V
static public void main(String[] args) {
if (args.length == 1) {
new Main(args[0]);
} else {
System.erг.println(“usage: java Main <image file>’):
}
}
}
class ImageCanvas extends Canvas {
Image image;
Rectangle selected = new RectangleO;
Image cropimage;
Rectangle cropImageRect = new RectangleO;
ImageCanvas(Image image) {
this.image = image;
// Add listeners for mouse and key events
addMouseListener(new MouseEventHandlerO);
addMouseMotionlistener(new MouseMotionEventHandlerQ);
addKeyListener(new KeyEventHandlerQ) ;
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
g.setClip(0, 0, image.getWidth(null), image.getHeight(nul1));
g.drawlmage(image, 0» 0, this);
if (cropimage != null) {
g.drawlmage(croplmage, cropImageRect.xt cropImageRect.у, this);
} else if (!selected.i sEmptyO) {
g. setXORMode(getBackgroundO);
g.fi11Rect(selected.*, selected.y,
selected.width, selected.height);
g.setPaintMode();
}
}
// Convenience method.
void repaintRect(Rectangle r) {
repaint(r.x, r.y, r.width, r.height);
}
// Event handlers
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
if (cropimage !- null) {
// Add cropimage to main image.
Graphics g = image.getGraphicsQ ;
g.drawlmage(croplmage, cropImageRect.x, cropImageRect.у,
ImageCanvas.this);
g.disposeO :
cropimage = null;
repai ntRect(selected);
selected. setLocati on (evt.getXO , evt.getYO) ;
CropImageFilter
java.awt. image
repaintRect(seiected);
}
public void rrouseReleased(MouseEvent evt) {
repai ntRect(selected);
selected .width Math.riax(0, evt.getXO - selected.x);
se1 octed.height = Math.max(0, evt.getY() - selected.y);
repai ntRect(selected);
}
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent evt) {
repaintRect(selected);
seiected.width = Math.max(0, evt.getXQ - selected.x);
sei ected. hei ght = Math.max(0, evt.getYO - selected.y);
repaintRect(selected);
}
public void mouseMoved(MouseEvent evt) {
if (c^oplmage 1- null) {
// Move the cropped image around.
repai nt Rect(cropImageRect);
c ''opInageRect. setLocation(evt. getXO . evt. getYO);
repai ntRect(cropTmageRect);
}
}
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
char key =- evt, getKeyCharO ;
if (key — Jc’) {
if (! selected, isEmptyO) {
// Create crop image using a CropImageFi1 ter.
CropIrrageFi 1 ter imgf =
new CropImageFi1ter(selected.x, selected.y,
selected.width, selected.heigt
ImageProducer ip - image.getSourceO;
ip - new Fi1tered!mageSource(ip. imgf);
cropimage = getloolkit().createlmage(ip);
cropImageRect - new Rectang 1e(se1ected.x, seiected.у,
seiected.width,
selected.height);
}
} else if (cropimage U null) {
repai ntRect(cropImageRect);
cropimage = null;
}
// Delete the selection.
repaintRect(selected);
selected.width - selected.height = 0;
}
}
}
474
CropimagcFilterf
PURPOSE Constructs a new CropImageFi1 ter instance.
SYNTAX public CropImageFi1 ter(int x, int y, int width, int height)
description The new crop image filter extracts the pixels in the rectangular region speci- fied by x, y, width, and height of lhe source image, к will translate the loca- tions of the extracted pixels to the image consumer such that the top left pixel will have the coordinate (0, 0).
parameters height width The height of (he rectangle in pixels. The width of the rectangle in pixels.
X The л-coordinate of the left edge of lhe rectangle in pixels.
У The у-coordinate of the top of the rectangle in pixels.
EXAMPLE See the class example.
setDimensions()
PURPOSE Called by the image producer to deliver the dimensions of the source image.
SYNTAX public void setDimensionsfint width, int height)
DESCRIPTION The CropImageFiIter class implements this method as part of the Image Consumer interface. This method should not be used.
PARAMETERS height wi dth The height of the image in pixels. The width of the image in pixels.
OVERRIDES ImageFiIter.setDimens!ons().
SEE ALSO ImageConsumer.setDimensions().
setPixels()
PURPOSE Called by the image producer to deliver pixels to the image consumer.
syntax public void setPixel s(int x, int y, int w, int h, ColorModel model, byte[] pixels, int offset, int scansize) public void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int offset, int scansize)
DESCRIPTION The CropImageFiIter class implements this method as part of the Image- Consumer interface. This method should not be used.
CropImageFilter
java.awt.unage
setPropertiesO
PARAMETERS h model offset pixels scansize w X У The height of the rectangle in which the pixels are destined. The non-nul 1 color model used to translate the pixel values. The index of the first pixel in the pixel array. The non-nul 1 array of pixel values. The width to use when extracting pixels from pi xels. The width of the rectangle in which the pixels are destined. The A-coordinatc of the rectangle in which the pixels are destined. The у-coordinate of the rectangle in which the pixels are destined.
OVERRIDES ImageFiIter. setPi xelsO-
SEE ALSO ImageConsumer.setPi xels().
setProperties()
PURPOSE Called by the image producer to deliver the properties for the source image.
SYNTAX public void setProperties(Hashtable props)
DESCRIPTION The CropImageFilter class implements this method as part of the Image- Consumer interface. The method should not be used.
PARAMETERS
props A non-nul 1 hashtable of properties.
OVERRIDES ImageFi 1 ter. set Егоре rtiesQ.
SEE ALSO ImageConsumer.setProperti es C).
476
java.awt
Cursor
Syntax
public class Cursor extends Serializable
Description
A component normally has a default cursor typically an arrow—when the cursor is moved
within the component. This cursor can he changed at any time. Since each component can set
its own cursor, the cursor can also change as it is moved from one component to another. The
Cursor class is used to represent a cursor.
The exact cursor shapes available are platform-dependent. On some platforms, the cursor
shapes are also system-configurable. Table 8 shows the cursor shapes for the Windows plat-
form using a default set of system configured cursors.
CROSSHAIR_CURSOR N„RESI7F_CURSOR | SW_RFSIZE_CURSOR
DEFAULT.CURSOR NE_RE5IZE_CURSOR TFXT_CURSOR j
E_RESIZE_CURSOR NW_RESIZE_CURSOR W_RESIZL_CURSOR , >
HAND_CURSOR S„RLSIZF.CURSOR WAIT—CURSOR И ж
MOVE.CURSOR SE_.RFST7E_CURS0R
TABLE 8: Cursor Shapes for the Windows Platform,
Cursor
jav a.awl
[ MEMBER SUMMARY
A
в
D
E
F
G
H
1
J
К
I.
M
N
О
p
Q
R
S
T
и
V
w
X
Y
z
Constructor
CursorO
Cursor Types
CROSSHAIR—CURSOR
DEFAULT CURSOR
E RFSTZE .CURSOR
HAND-CURSOR
MOVE CURSOR
N_RESI7F_CURS0R
NE_RESIZt„CURSOR
NW_RESTZE. CURSOR
S.RESI7F_CURS0R
SE_RESIZL CURSOR
SW_REST7F_.CURS0R
TEXT„CURSOR
W.RESIZE. CURSOR
WAIT CURSOR
Constructs a new Cursor instance.
The cursor type specifying a crosshair cursor.
The cursor type specifying the default cursor.
The cursor type specify ing a type of resizing cursor.
The cursor type specify ing a hand cursor.
The cursor type specifying a moving cursor.
The cursor type specifying a type of resizing cursor.
The cursor type specifying a type of resizing cursor.
The cursor ty pe specifying a type of iesizing cursor
The cursor type specifying a ty pe of resizing cursor
The cursor type specifying a type of resizing cursor.
The cursor type specifying a ty pe of resizing cursor.
The cursor type specifying a caret cursor.
['he cursor type specify ing a type of resizing cursor.
The cursor type specifying an hourglass cursor
I Methods for Retrieving Cursors
getDefaul tCursorO °"
getPredefinedCursorO
Retrieves the system default cursor.
Retrieves the cursor of a predefined cursor type.
Cursor Type Method
getTypeO
Retrieves the cursor type of this cursor.
See Also
Component. getCursorf). Component. setCursorQ. java. io. Serial izable.
Example
This example creates a list containing the names of all available cursor types. Selecting a cur-
sor name from the list sets that cursor. The program also creates a background thread that
simply waits 10 sec. sets (he cursor to the default cursor, waits 2 sec. and then restores the cur-
sor to its set value. See Figure 113.
478
import java.awt.**;
i mpo rt java, awt .event. ;
class Main extends Frame implements Runnable,
ItemListener {
Li st 1 = new Li st О :
Stringf] cursors = {
“DEFAULT-CURSOR”,
“CROSSHAIR-CURSOR”,
“TEXT-CURSOR”,
“WAIT_CURSOR”,
“SW_RESIZE_CURSOR”,
“SE_RESIZE_CURSOR”,
“NW_RESIZE_CURSOR”,
“NE_RESIZE_CURSOR”,
“N_RESIZE_CURSOR”,
“S_RESIZE_CURSOR”,
“W_RESIZE_CURSOR”,
“E_RESIZE_CURSOR”,
“HAND-CURSOR”,
“MOVE_CURSOR”,};
setCursor Example
DEFAULT_CURSOR
CROSSHAIR CURSOR
TEXT_CURSOR
WAIT_CURSOR
SW_RESIZE_CURSOR
SE RESIZE CURSOR
NV/ RESIZE CURSOR
NE RESIZE-CURSOR
N-RESIZE-CURSOR
S-RESIZE-CURSOR
V/_RESIZE_CURSOR
E_R£SIZE_CURSOR
HAND_CURSOR
MOVE-CURSOR
MainQ {
super(“setCursor Example”);
for (int i=0; i<cursors.1ength ; Q + )
1.addltem(cursors[ij);
}
add(l , BorderLayout.CENTER);
FIGI RE 113: Cursor.
// Add item listener to list
1.addltemLi stener(this);
(new Thread(this)).start();
packQ ;
showQ ;
}
public void itemStateChanged(ItemEvent evt) {
setCursor(Cursor.qetPredefinedCursor(l.getSelectedlndexQ));
}
public void run() {
while (true) {
try {
Cursor cursor = getCursorQ;
setCu rsor (Cursor. getDefaul tCursor(j) ;
Thread.sieep(2000);
setCursor(cursor);
Thread.sieepf10000);
} catch ("Exception e) {
}
}
static public void main(String [] args; {
new Mai n( ) :
I
Cursor
Cursor()
java.awt
CursorO
pi rposl ('(instructs a new instance of Cursor.
syntax public Cursor(int cursorType)
A
description This method creates a new instance of Cursor for the cursor type cursor-
B Type. It typically should not be called directly. You should use getPre-
Ц defi nedCursorO instead.
PARAMETERS
cursorType The cursor type. Must be one of the cursor types defined in the Cursor class.
E
EXCEPTIONS
f IllegalArgumentException
G И cursorType is not one of the cursor types defined in the Cursor class.
H seealso getPredefi nedCursorO.
I example See the class example for a usage of getPredefi nedCursorO.
K CROSSHAIR-CURSOR
L —
purpose The cursor type specifying a crosshair cursor.
M
syntax public static final int CROSSHAIR_CURSOR
N
description This cursor type is typically displayed when drawing graphics. Its value is 1.
О
example See the class example.
P
Q
R DEFAULT-CURSOR
s PURPOSE The cursor type specifying the default pointer cursor.
T SYNTAX public static final int DEFAULT-CURSOR
L DESCRIPTION This cursor type should be displayed when the cursor is not over a special kind
V of window or if the application is not in any mode. A cursor of this type is returned by getDefaul tCursorO. Its value is 0.
W SEE ALSO getDefaul tCursorQ.
X Y EXAMPLE See the class example.
480
li RESIZE_CURSOR
E RES1ZE, cursor
PURPOSE The cursor type specifying a type of resizing cursor.
SYNTAX public static final int E_RESIZE„CURSOR
description This cursor type is typically displayed while the user is resizing the eastern border of an object. Its value is 11.
example See the class example.
getDefaultCursor()
PURPOSE Retrieves the system’s default cursor.
SYNTAX public static Cursor getDefaul tCursorO
DESCRIPTION This method creates a new instance of Cursor for the cursor type type. This constructor typically should not be called directly. You should use getPre- definedCursorO instead.
PARAMETERS type The cursor type. Must be one of the cursor types defined in the Cursor class.
EXCEPTIONS
IllegalArgumentExcept ion
If type is not one of the cursor types defined in the Cursor class.
SEE ALSO getPredefi nedCursorO.
EXAMPLE See the class example.
getPredefinedCursor()
purpose Retrieves the cursor of a predefined cursor type.
SYNTAX public static Cursor getPredefinedCursorfint cursorType)
PARAMETERS cursorType exceptions The cursor type. Must be one of the cursor types defined in the Cursor class.
Illegal Argumentsxception
If cursorType is not one of the cursor types defined in the Cursor class.
SEE ALSO getDefaultCursorO.
example See the class example.
Cursor
java.awt
getTypet)
getiype()
pcrpose: Retrieves this cursor's cursor type.
swiax public int getTypeO
returns This cursor's cursor type. One of DEFAULT-CURSOR, CROSSHAIR-CURSOR.
TEXT_CURSOR. WAIT_CURSOR. SW_RESIZE.CURSOR, SE^RESIZF.CURSOR.
NW_RESIZE_CURSOR. NE_RESIZE_CURSOR. N_RESIZE_CURSOR. S..RESIZE__
CURSOR. W_RESI7E_CURS0R, E_RESIZE_CURSOR. HAND-CURSOR, or MOVE__
CURSOR.
see also CursorO , getPredefi nedCursor().
example This example creates a thread that alternately sets the frame's cursor between
lhe crosshair cursor and the wait cursor. When the crosshair cursor is dis-
played, clicking the mouse draws a black circle. When lhe wait cursor is dis-
played. mouse clicks are ignored.
import java.awt.-;
import java.awt.event;
class Main extends Frame implements Runnable {
int curX, curY;
Main() {
super("getType Example”);
setSize(200, ?00);
this. addMousel. i stener (new MouseEventl i stenerO);
show();
(new Thread(this)).start();
}
public void update(Graphics g) {
g.fi 1lOval(curX, curY, 20, 20);
}
public int myCursorType() {
return getCursor().getType();
}
class MouseEventlistener extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
if (myCursorType() 1- Cursor.WAIT_CURSOR) {
curX - evt.getX();
curY = evt.getY();
repai nt();
}
}
}
public void run() {
while (true) {
try {
if (myCursorType() Cursor.WAIT_CURSOR) {
482
ju у сисл w i
HAND-CURSOR
setCursor(Си гsoг.getPredefi nedCиrsor(Си г-
sor.CROSSHAIR-CURSOR));
} else {
setCursor(Cursor.qetPredefinedCursor(Cursor.WAIT CURSOR));
}
Thread.sleep(300O);
} catch (InterruptedException e) {};
}
}
static public void main(String[j args) {
new Mai n();
HAND CtRSOR
PURPOSE The cursor type specifying a hand cursor.
SYNTAX public static final int HAND-CURSOR
DESCRIPTION This cursor type is typically displayed if the cursor is over an object that can be dragged. Its value is 12.
EXAMPLE See the class example.
MOVE-CURSOR
PURPOSE The cursor type specifying a moving cursor.
SYNTAX public static final int MOVE-CURSOR
’ DESCRIPTION This cursor type is typically displayed while the user is moving an object. Its value is 13.
EXAMPLE See the class example.
5 N_RESIZE CURSOR
PURPOSE The cursor type specifying a type of resizing cursor.
SYNTAX public static final int N RESIZE CURSOR
DESCRIPTION This cursor type is typically displayed while (he user is resizing the north bor-
r der of an object. Its value is 8.
> example See the class example.
ft
Cursor
java.au I
\E_RESIZE CURSOR
NE_RESIZE_CLRSOR
PVR К >SE The cursor ty pe specifying a type of resizing cursor.
SY VI AX public static final int NE_RESIZE_CURSOR
A DIiSCRIPlION This cursor type is typically displayed while the user is resizing the northeast-
в EXAMPLE ern border of an object, ks value is 7. See the class example.
D
E NW_RESIZE_CLRSOR
P G Pl RHXSL The cursor type specifying a type of resizing cursor.
H SYNTAX public static final int NW_RESIZE CURSOR
1 DESCRIE’TION This cursor type is typically displayed while the user is resizing the nonh- uestern border of an object. Ils \alue is 6.
J К I XAMl’I.f See the class example.
L M S.RESIZE. .CURSOR
n pi rposf: I he cursor ty pe specifying a type of resizing cursor.
() SYNTAX public static final int S RE-SIZb_CURSOR
p DESCRIPTION This cursor type is typically display ed while the user is resizing the southern
Q border of an object, ks value is 9.
R LX AM PI.h See the class example.
S T SE_RES1ZEJ?URSOR
I Pl К POSE’ The cursor type specifying a type of resizing cursor.
V SYNTAX public static final int SE RFSIZE„CURSOR
w inscription This cursor type is typically displayed while the user is resizing the southeast-
X ern border of an object. Its value is 5.
Y EXAMPLE See the class example.
484
SW..RESIZE-CURSOR
SW^RESIZE_CURSOR
PURPOSt I’he cursor type specifying a type of resizing cursor.
SYNTAX public static final int SW.RESIZF.CURSOR
DESCRIPTION This cursor type is typically displayed while the user is resizing the south- western border of an object. Its value is 4.
EXAMPLE See the class example.
TEXT-CURSOR
purpose: The cursor type specifying a carei cursor.
SYNTAX public static final int TEXT.CURSOR
description This cursor type is typically displayed while the cursor is over an object and
text on the object can be selected. Its value is 2.
example See the class example.
W RESIZE CURSOR
purpose The cursor type specifying a type of resizing cursor.
SYNTAX public static final int W RLSIZF.CURSOR
description This cursor type is typically displayed while the user is resizing the western
border of an object. Its value is 10.
example See the class example.
WAIT€URSOR
PURPOSE The cursor type specifying an hourglass cursor.
syntax public static final int WAIT.CURSOR
DESCRIPTION This cursor type is typically displayed while the application is busy and cannot respond to user input. Its value is 3.
example See the class example.
java.beans
Customizer
QCustomixer
Л
В
Syntax
public interface Customizer
D
E
F
G
H
1
J
К
L
M
N
О
Description
A customizer is a specialized user interface for editing the properties of a bean.
When editing a bean, the hean editor presents to the user one property editor for each edit-
able bean property. The set of property editors is called a property sheet. The hean editor pro-
vides default property editors for typical types such as strings and integers (see
Property Editor). If a hean property is of a type that cannot he edited by any of the bean’s
default property editors, the bean must supply a custom property editor (see PropertyEdi-
tor). However, in some eases, a property sheet is not the best way to edit a bean. For example,
in an animation bean, it is very awkward to set the animation rate, frame sequence, motion
path, and so on. through a property sheet. In such cases, a hean can have a customizer that is a
specialized user interface for editing the bean. A hean editor can display either the property
sheet or the customizer or both.
A customizer must be a component (see Component) because the bean editor will add the
customizer to its own container in order to display the customizer. Also, the customizer must
ha\e a public null constructor.
P Beaninfo
To specify a customizer for a bean, you must provide a bean-info (see Beaninfo) for the bean
and associate the customizer class with the bean class. See BeanDescriptor for more details.
R
s Property Change Events
When a bean editor creates a customizer, the bean editor registers itself as a listener to the cus-
1 tomizer for property change events. The customizer must fire a property change event when-
L ever it changes any of the bean's properties. This allows the bean editor to updates its copy of
the bean's properties. The events should include the name of the property that changes, as well
as the property's old and new values.
X
Y
Z
486
BER SUMMARY
Bean Method
setObjectO
Called by the bean editor to set the customizer's bean.
Event Listener Methods
addPropertyChangeLIstenerO
removePropertyChangeL istenerO
Adds a listener tor receiving property change events.
Stops a listener from receiving property change
events.
See Also
java.awt.Contai ner, PropertyEditor.
Example
This is a somewhat elaborate example of a customizer. The bean is an image map that is an
application that can display a background image with “hot" areas. The hot areas display a mes-
sage when you roll the cursor over them (see Figure 114),
The image map bean comes complete with a built-in image map editor (Figure 115) that
allows you to set areas on the image map such that when the user rolls into an area, a message
is displayed. You can change the location of an area by selecting it and dragging it around. You
can change the size of an area by selecting it and the dragging the handle at the lower-right
comer. You can change the message displayed by an area by selecting the area, typing the new
text in the text field, and then pressing Return. You can create a new area by clicking lhe New
button. You can delete an area by selecting the area and then clicking the Delete button. The
customizer does not immediately update lhe bean’s property value with each modification.
You need to manually update lhe bean's property value by clicking the Save button.
This example uses PropertyChangeSupport to implement the property change listener
methods.
The mapping functionality is separated into its own class called Map. The Map class is used
by both the bean and the customizer. A map object has a design-time switch that allows it to be
easily switched between edit mode or normal-use mode. While in the bean, the map object is
in normal-use mode; while in the customizer, it is in edit mode. While in edit mode, the map
object also reads the Beans.isDesignTimeO flag. If the Hag yields false, the map object
switches into normal-use mode. This means that you can switch the map object in the custom-
izer between edit and normal-use modes b\ changing the bean editor s design-time stale.
Note: In the Beanbox in BDK 1.0apr97. the customizer dialog box is modal, so you cannot
actually change the design-time state while the customizer is displayed.
Note: When you start up the customizer for this bean, notice that the window is too nar
row. This is due to a bug in the Beanbox in BDK 1,0apr97. The Beanbox is retrieving the sizes
of the customizer before the peers have been created.
Customizer
ja\ a.beans
№)E3
1)
r:
i
<i
н
,BeanOo*
-ie Eit!
мер
I КД RI 114: Image Map Bean.
I
J
К
I,
M
N
()
P
Q
R
S
I
ЕКД RI 115: Image Map Bean Customi/er.
A
В
c
U
w
Note: 11' \on run the Beanbox in BDK 1,0apr97 in the same director) as the class files tin
Bcanbox will not be able to create the cusiomi/er. The Beanbox must be run from some othe
directory because there is a problem with the Beanbox's class loaders.
Y
Z
Bean.java
import java.awt.’-';
import java.awt.event.‘;
import java.awt.image.*;
import java.beans;
import java.net.
488
public class Bean extends Panel {
Map map - new Map();
// Constructor
public Bean() {
// Initialize the bean with some data for testing purposes.
Area[] as = {
new Area(new Rectangle(0, 0, 40, 40), "Areal"),
new Area(new Rectangle(100, 100, 40, 40), "Area?")};
map.setAreas(as);
map. setlmage(loadlmage(’'world.gif"));
add(map, BorderLayout.CENTER);
}
// The image accessor methods.
public Image getlmageO {
return map.image;
}
public void setlmage(lmage newlmage) {
Image oldimage - map.image:
map.setImage(newlmage);
pceListeners.firePropertyChangeC"image", oldlmage, newlmaqe);
}
// The area accessor methods.
public Area[] getAreasO {
return map.areas;
}
public void setAreas(Area[] newAreas) {
Area[] oldAreas = map.areas;
map.setAreas(newAreas);
pceListeners. fi rePropertyChangeC'areas" , oldAreas, newAreas);
}
// Create the listener list.
PropertyChangeSupport pceListeners =
new PropertyChangeSupport(this);
// The listener list wrapper methods.
public synchronized void addPropertyChangeListener(
PropertyChangeListener 1) {
pceLi steners.addPropertyChangeLi stener (1);
}
public synchronized void removePropertyChangel istener(
Propertychangelistener 1) {
pceLi steners.removePropertyChangel i stener(l);
}
// This method will load an image relative to the location of the
// bean class file. A bean should always use a method like this one
// to load resources that are located relative to itself. Otherwise the
// resource will be looked for relative to the location of the bean
Customizer
java.beans
// container’s current working directory.
public Image 1oadlmage($tring imageName) {
try {
LRL url - getClassO.getResource(imageName);
return get Toolki tОcreatelmage((ImageProducer)url.getCc
} catch (Exception e) {
return null;
}
}
}
/*
manifest.txt *i1e:
Name: Bean.cl ass
Java-Bean: True
jar command:
jar cfm bean.jar manifest-txt * .class
BeanBeanlnfojava
import java.beans.*;
public class BeanBeanlnfo extends SimpleBeaninfo {
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(Bean.cl ass, MapCustomizer.class):
}
public java.awt.Image getlcon(1nt iconKind) {
switch (iconKind) {
case !CON_COLOR_16xl6:
return loadimage("world-color-16x16.gif”);
case ICON_COLOR_32x32:
return loadlmage("world-color-32x32.gif”);
case ICON_MONO_16xl6:
return loadlmage(”world-mono-16xl6.gif");
case ICON MONO_32x32:
return loadlmage(”worId mono-32x32.gif’);
default:
return nul1;
}
}
}
Areajava
import java.awt.-;
import java.io.”;
import java.util.*;
public class Area implements Serializable {
Rectangle bounds;
String label;
Area(Rectangle bounds, String label) {
this.bounds - bounds;
this.label - label;
}
// Utility function for converting an array to a vector
static Vector toVector(Area[] areas) {
490
Vector v = new VectorO;
for (int i=0; i<areas. length; in) {
v.addFlement(areas Г Г):
}
return v;
}
// Utility function for converting a vector to an array.
static Area[J fromVector(Vector v) {
Area[] result new Areafv.size()];
for (int i-0; i<v.size(); i-*-*-) {
result[ij = (Area)v.elementAt(i);
}
return result;
}
}
Map.java
import java.awt.1';
import java.awt.event;
import java.beans.*;
public class Map extends Canvas implements IterrSelectable {
// These fields are used by clients of this class.
public transient Image image;
public Area[] areas;
int curArea = 1;
// Offscreen image used for double-buffering.
transient Image bbuf;
// If true, the map is in a customizer and so the map can be edited,
boolean inCustomizer - false;
// If true, the user is dragging an area,
boolean dragging;
// If true, the user is stretching an area,
boolean stretching;
// Location of cursor when the user pressed the mouse.
// When dragging, it is relative to the origin of the area rather than
// to the component.
// When stretching, it holds distance to the se corner of the area;
// both coordinates are always positive.
Point downPt:
public Map() {
// Listen for mouse and mouse motion events.
addMouseMotionli stener(new MouseMot iontventHandler());
addMousel istener(new MouseEventHandlerO):
}
// Change the background image.
public void setlmagedmage newlmage) {
MediaTracker tracker - new wediaTracker(this);
image -= newlmage;
Customizer
ja\ a.beans
try {
tracker.addImage(image, 0);
tracker.waitForAl1();
} catch (exception e) {
e.printStackT race();
J
setSize(image.getWidth(nul1). image.getHeight(nul1));
repaintO;
}
public void setAreas(Area[] newAreas) {
areas - newAreas;
curArea = -1;
repai ntO ;
}
// This method is need to implement TtemSelectable.
public Object J getSelectedObjects() {
it (curArea >= 0) {
Objectf] result = {areas[curArea]};
return result:
}
return null;
}
// Paint methods.
public void paint(Graphics g) {
update(g);
J
public void update(Craphics g) {
// Copy the value in case it gets changed by the event handle
int ca = curArea;
if (inCustomizer | !Beans.isDesignlime()) {
g.drawlmage(imaget 0, 0, this);
return;
1
// Create the offscreen image if necessary.
if (bbuf == null) {
bbuf ~ createlmage(image.getWidth(nul1), image.getHeight
}
Graphics bbufG = bbuf.getGraphics();
// Draw the background image.
bbufG.drawlmage(image, 0, 0. this);
// Paint all the area rectangles.
for (int i-0; i<areas.length; i*+) {
if (i == ca) {
bbufG.setCol or(Color.red);
// Paint the handle.
bbufG.fi11Rect(handleRect.x, handleRect.у,
handleRect.width-1. handleRect.height 1);
} else {
bbufG.setColor(Color.bl ack);
}
492
bbufG.drawRect (areas; i ; .bounds.x, areas! i] .bounds.у,
areas[i].bounds.width-1, areas[ij.bounds.height 1);
}
bbufG.dispose():
g.drawlmage(bbuf, 0, 0, this);
}
class MouseMotionFventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
if (inCustomizer M Beans. isDesignliте()) {
return;
}
int x - evt.getX();
i nt у - evt. getYO ;
for (int i=0; i<areas.length: i-+) {
if (areas[i1.bounds.contains(x, y)) {
showTip(areasfij.label, x, y) ;
return;
}
}
showIip(null, 0, 0);
}
public void mouseDragged(MouseLvent evt) {
if (dragging) {
areas [curArea] .bounds.x -- evt.getX()-downPt.x;
areas[curArea].bounds.у = evt. getYO down Pt. у;
// Keep the area within the imagemap.
areas[curArea].bounds.x = Math.max(0, Math.min(
areas[curArea].bounds.x, image.getwidth(nuП)
- areas[curArea].bounds.width));
areas[curArea].bounds.у - Math.max(0, Math.min(
areas[curArea].bounds. у, image.getHeight(nul1)
• areas ГсигАгеа].bounds.height));
updateHandleQ ;
repaintO;
} else if (stretching) {
// Keep the box within the image.
int x - Math.min(evt.getX(), image.getWidth(nul1) 1);
int у = Math.min(evt.qetY(), image.getHeight(nul1)-1);
areas[curArea].bounds.width - x+downPt.x
-areas[curArea].bounds.x;
areas[curArea].bounds.height - у-downPt.у
-areas[curArea].bounds.у;
// Don't make the area too small.
areas[curArea].bounds.width - vath.max(20,
areas[curArea].bounds.width);
areas[curArea].bounds.height - Math.max(20.
areas[curArea].bounds.height);
}
}
updateHandleO ;
repai nt();
Customizer
ja\a.bcitns
void updateHandleO {
if (curArea >= 0) {
handleRect = new Rectangle(areasCcurArea].bounds);
handleRect.x - handleRect.xihandleRect.width 5;
handleRect.у = handleRect.y+handleRect.height-5;
handleRect.width - 5;
handleRect.height - 5;
}
}
Rectangle handleRect;
class MouseFventHandler extends MouseAdapter {
public vo-'d mousePressed(MouseEvent evt) {
int x - evt. getXO ;
int у = evt.getYO :
for Ont i-0; i<areas.1ength; i+*) {
if (areas [iL.bounds.contains(x, y)) {
curArea - i;
// Check if on handle
updateHandle();
if (handleRect.contains(x, y)) {
stretching = true;
// The down point is relative to the se corner.
downPt = new Point(areas[i.bounds.x+
areas[i].bounds.width-x,
areas[i].bounds.y+areas[i J.bounds.hei ght-y);
} else {
dragging = true;
// The down point is relative to the nw corner.
downPt = new Point(x-areas[i].bounds.x,
у-areas[i].bounds.y);
}
process!temEvent(new ItemEvent(Map.this,
ItemEvent.ITEM STATE CHANGED, new Integer(i),
ItemEvent.SELECTED));
repai nt();
break;
}
}
}
public void mouseReleased(MouseEvent evt) {
dragging - false;
stretching - false;
}
}
public Dimension getPreferredSizeO {
return new Dimension(image.getWidth(null), image.getHeight(nulIX
}
//Tip methods
TipWindow tip;
public void showTip(String tipLabel, int x, int y) {
if (tip =- null) {
// Find the parent.
Component c = getParentO;
while (!(c instanceof Frame)) {
494
с - с. get Ра rent () ;
}.
tip - new TipWindow((Fname)с);
}
tip.setLabel(tiplabel);
if (tiplabel null) {
if ( ! tip, isShowingO) {
Point pt = getLocationOnScreenO ;
tip,setLocation(pt.x+x, pt.y+y);
tip.show();
}
} else {
tip.hideO ;
}
}
// Item listener support methods.
transient ItemListener itemListener;
public synchronized void addltemListener(Itemlistener 1) {
itemListener ~ AWTEventMulticaster.add(itemListener, 1);
}
public synchronized void removeItemListener(Itemlistener 1) {
itemLi stener д. AWTEventMulticaster. remove(i temListener, 1);
}
protected void processItemEventfltemFvent evt) {
if (itemListener 1- null) {
i temLi stener.i temStateChanged(evt);
}
}
}
MapCustomizer.java
import java.awt.7;
import java, awt .event.
import java.beans.*;
import java.util.*;
public class MapCustomizer extends Panel
implements ActionListener, ItemListener, Customizer {
Bean bean;
// Components
Button newBtn = new ButtonC'New1');
Button deleteBtn = new ButtonC'Del ete”);
TextField labelTf - new TextField(15);
Button saveBtn = new ButtonC'Save");
// Offscreen image for double-buffering.
transient Image bbuf;
Map map;
public MapCustomizer() {
map = new Map();
map,inCustomizer = true;
// Layout buttons.
Panel p =- new Panel (new GridLayout(0, 1));
Customizer
ja\ a. beans
p.add(labelTf);
p.add(newBtn);
p.add(deleteBtn);
p.add(saveBtn);
Panel q - new Panel(new BorderLayout O);
q.add(p, BorderLayout.NORTH);
A
// Layout map and buttons.
В setlayoutCnew Borderl ayoutO);
add(q, BorderLayout.EAST);
addfmap, BorderLayout.CENTER);
D
E
l;
C
// Listen for events.
map.addltemListenerCthi s);
labelTf.addActiont istenerCthis);
newBtn.addActi onLi stener(thi s);
deleteBtn.addAct ionLi stenerCthi s);
saveBtn.addActionLi stenerCthis);
H public void setObjectCObject b) {
bean = (Bean)b;
I map. setAreasCbean. getAreasO);
map.set Image(bean.getImage О);
J 1
К // Action event handler,
public void actionPerformedCActionEvent evt) {
L if Cevt,getSourceO == newBtn) {
// Add a new entry.
M Vector v - Area.toVector(map.areas);
Area a = new Area(new Rectangle(0, 0, 30, 30), "Unknown’');
N v,addElement(a);
map.setAreas(Area.fromVector(v));
() } else if (evt. getSourceO == deleteBtn) {
if (map.curArea >= 0) {
P // Delete the current entry.
Vector v = Area.toVector(map.areas);
Q v.removeElementAt(map.curArea);
map.setAreas(Area.fromVector(v));
R }
} else if (evt. getSourceO — saveBtn) {
S Areafl oldAreas - bean. getAreasO ;
bean. set Areas (map. areas);
T pceListeners,firePropertyChangeC’areas", oldAreas, map.areas);
} else if (evt.getSourceO == labelTf) {
L’ map, areas [map. curArea] . 1 abel = 1abelTf.get Text();
}
V repaintO;
}
W
// Item event handler.
X public void i terrStateChanged(ItemEvent evt) {
labelTf.setText(map.areas[((Integer)evt.getltemO) .i ntValue()J,lat
Y }
Z // Create the listener list.
PropertyChangeSupport pceListeners -
new PropertyChangeSupport(this);
496
// The listener list wrapper methods.
public synchronized void addPropertyChangeListener(
PropertyChangeListener 1) {
peeli steners.addPropertyChangeLi stenerO);
}
public synchronized void removePropertyChangeListener(
PropertyChangeListener 1) {
pceListeners.removePropertyChangeLi stenerO);
}
}
TlpWindow.java
import java.awt.*;
public class Tipwindow extends Window {
String label;
Font f = new FontC'Seri f”, Font. PLAIN, 14);
FontMetrics fm;
public TipWindow(Frame frame) {
super(frame);
setFontff);
fm - getFontMetrics(f);
}
public void setLabel(String label) {
this.label =• 1abel;
if (label ’= null) {
setSize(fm.stringWidth(label), fm.getHeight());
}
}
public void paint(Graphics g) {
g.setColor(Color,yellow);
g.fi1lRect(0, 0, getSize().width, getSize().height);
g.setColor(Color.bl ack);
if (label !- nul1) {
g.drawStringflabel, (getSize().width - fm.stringWidth(labe1))/2,
(getSizeO.height fm.getHeiqht())/2 + fm.getAscentQ) ;
1
}
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
}
Customizer
java.beans
add Property ChangeListenerC)
add Property ChangeListenerO
D
E
F
Ci
H
I
J
К
1.
M
N
()
P
Q
R
S
T
pirpose Adds a listener for receiving property change events.
syntax void addPropertyChangeListener(PropertyChanget istener listener)
di sc ripiiox This method should add listener to the listener list, h is typically called bv
the bean editor just after it creates the customizer.
After this method is called, the property editor should fire a property change
event to the listeners of any changes that the customizer makes to the bean.
'The property name of the event should contain the name of the property that
changed. The old and new values of the event should contain the previous and
new property values, respectively.
This method is typically called by a bean editor so that the editor can be noti-
fied when the user changes the property of a bean. The bean editor uses these
notifications to update its display of any bean properties.
PAR A METERS
1 istener A non-nul 1 property change event listener.
SEE ALSO removePropertychangeLi stener().
example See the class example.
removePropertyChangel Jstener()
V
w
X
Y
z
purpose Slops a listener from receiving property change events.
syntax void removePropertyChangeli stener(PropertyChanqeListener
1i stener)
description This method should remove listener from the listener list. If listener is
not in the listener list, the method call should be ignored. This method is topi-
cally called by the bean editor just after it creates the customizer.
The implementation of this method does not have to stop the deliver} of events
immediately. That is, after this method is called, the listener mav receive a few
more property change events. See PropertyChangeListener for more
details.
PARAMETERS
1 i stener /X non-nul 1 property change event listener.
sf.f. also addPropertyChangeListener().
f xample See the class example.
498
setObjectO
ObjectO___________ ___ ___ _ ___________________________________________
PURPOSE Called by lhe bean editor to set the customizer’s bean.
syntax void setObjectfObject bean)
DESCRIPTIOS Just after a bean editor creates a customizer, the bean editor calls this method once to give the customizer a reference to the bean. The bean editor calls this method before it adds the customizer to a container. Essentially, this means that this method cannot do any work that involves component sizes. See Com- ponent .getPreferredSizeO for more details.
parameters bean The non-null bean to be customized.
EXAMPLE See the class example.
java.awt.datatransfer
DataFlavor
' — ___________j
A • t DataFlavor
В
c Syntax
public class DataFlavor
E
Description
When an application retrieves data from a clipboard» it is given a transferable object (see
Transferable), which holds the actual data. To retrieve the actual data from the transferable
H object, an application must use a data flavor. A data flavor specifies two things: a data type
! (image, text, a bean, and so on) and a delivery method (a byte stream, an Image object, an
array of pixels, and so on). For example, if an application wishes to retrieve an image as an
J array of pixels from the transferable object, it must construct (or use) a data flavor containing
К this information and then present it to the transferable object. The transferable object can
either reject the request (because it either does not have an image or cannot deliver it as an
L array of pixels) or deliver the data.
M When an application places some data on the clipboard, it must also include with the data
all of the data flavors that are supported. All of this information is kept in a transferable object.
Note*. This class is still under development. It currently supports string data flavors but not
° much else. Many of the methods have not been thoroughly designed and implemented. The
P class and method descriptions should improve greatly in the near future as other data types are
allowed on the system clipboard and as drag-and-drop becomes available.
r Using Data Flavors
There are two ways to use data flavors when trying to extract data from a transferable object.
The first is to ask the transferable object for all of' the data flavors that it will recognize. The
I application can then go through each data flavor and use one that it likes.
L The second way is to create a data flavor with the right specifications and then present it to
the transferable object. The transferable object could grant or reject the request. In practice,
v this is the simpler of the two ways. An application typically deals only in a fixed set of data
W flavors, and it can just try each one in a particular order until one or none works.
X The MIME Content Type
Y When an application retrieves the contents of a clipboard, it must interrogate the transferable
7 object to determine if it contains data of a type w ith which it can deal. For example, a text edi-
tor would ignore the contents if it were anything but text, while a paint program would ignore
all but images.
500
The data type of a transferable object is specified using MIME types, rhe MIME type is a
nonlocalized string that serves as a standard way of naming data types. Eor example, lhe
MIME type "image/jpeg" refers to a JPEG image and "text/plai n; charset=us'asci i "
refers to an ASCII string. If an application expects a JPEG image, it needs to create a data fla-
vor using the JPEG MIME type ("image/jpeg ’) and use that to interrogate the transferable
object.
The MIME type specification is described in REC 1341, which can be viewed on the
Internet at http: //ds.i nterni c. net/rfc/rfcl341.txt.
The Representation Class
Although the MIME type can determine what the transferable object contains, it does not say
fttnv the data is to be delivered to the application. For example, a JPEG image could be deliv-
ered as an Image object, a byte stream, or an array of pixels, This delivery information must
also be specified when interrogating a transferable object. This information is called the repre-
sentation class.
The representation class describes how the data in a transferable object is delivered to an
application. If the data is desired in the form of a java.awt. Image object, then the representa-
tion class is the java. awt. Image Cl ass object (see later in this discussion for more informa-
tion). If the data is desired in the form of a byte stream, then the representation class is the
java .io. ByteAr ray InputSt ream Class object.
In summary, a data flavor has two components: the MIME content type, which describes
what data type is desired, and the representation class, which describes how the data type is to
be delivered.
Human-presentable Name
A data flavor contains a localizable, human-presentable name that is meant to help a user iden-
tify a data flavor. The value of this name has no effect on how the data is transferred.
Class Objects
Every object has associated with it a Class object that contains information about the object’s
class, such as its superclass. These Class objects are used as the representation class in a data
flavor. A Class object can be retrieved in one of three ways:
1. By calling the object's getClassC) method
2. By calling Class.forNameO with the object s fully-qualified class name
3. By appending ".class" to the class name.
For example:
Integer 1 a new Integer(42);
// Method 1
Class the_IntegerClassDescriptorl = i.getClassO;
// Method 2
Class the_IntegerClassDescriptor2 •« Class, forNameC’java. lang. Integer’’) ;
DataFlavor
java.awt.datatransfer
//Method 3
Class = Integer.class;
String Data Flavors
The DataFlavor class contains two standard data flavors. These data flavors are for strings
and are used by the StringSelection class. Table 9 shows each data flavor and its MIME
type and representation class.
Data Flavor Representation Class MIME Type
stri ngFlavor java.1ang.Stri ng.cl ass appli cation/x-java-
seri ali zed-object;
class=java.lang.Stri ng
C plainTextFlavor java.io.StringReader.class text/plain; charset=unicode
H
TABLE 9: Data Flavors and Their MIME Types and Representation Classes.
I
J Note: In Java 1.1.2, the representation class for a plain text data flavor is actually null. Also,
K the MIMES type for the string data flavor is "application/x-java-serialized-object".
These arc bugs,
L
M MEMBER SUMMARY
N Constructor
() DataFlavor() Construct a DataFlavor instance.
P j MIME Methods
o getMimeTypeO Retrieves this data flavor's MIME type.
i sMimeTypeFqualО Determines if two MIME types are equal.
R i । normalizeMimeTypeО Called to normalize a MIME type.
S 1 normalizeMimeTypeParameterO Called to normalize a parameter in a MIME type.
T Representation Class Method
[j getRepresentati onClass 0 Retrieves this data flavor’s representation class.
V Human-presentable Name Methods getHumanPresentableNamef) Retrieves this data flavor’s human-presentable name. E
w setHumanPresentableNameO Sets this data flavor’s human-presentable name. •
X ’ Predefined Flavors
у । plainTextFlavor A standard data flavor for a string.
stri ngFlavor A standard data flavor for a string.
7 Data Flavor Equality Method equals() Determines if two data flavors are equal.
5П?
Example
See Transferable.
DataFlavorO _____
. ... r
purpose Construct a DataFlavor instance,
c
syntax public DataHavor(String mimeType, String humanPresentableName) м
public DataFlavor(Class representationclass, String
humanPresentableName)
description A data flavor can be constructed with either a MIME type or a representation
class. There is no way to specify both; it is necessary to subclass DataFlavor
in order to specify both properties.
If a MIME type is used to construct a data Havoc the representation class is set I"
to java.io.Inputstream. If the MIME type is "appl i cat ion/x - java- ।
serialized-object; cl ass=</k/wc of representation class>". the represen-
tation class is set to Cl ass . forName(owwc of representation class>). J
If representationclass is specified, the MIMI: type for lhe data flavor is K
set to ’’application/х-java-serial i zed-object; class=<nawr of rep- I
resentation class>". Eor example, if the representation class is
java.lang.String.class, then the MIME type would he ’’application/
x-java-serialized-object; class=java.lang.String". h
Note: The semantics described here are not entirely implemented in Java 1.1.2. (
In particular, when lhe MIME type is "application/x-java serialized-
object; clas5=<tt«we of representation eluss>\ the representation class is
not set to Cl ass. forName(<7wwe of representation cla\s>) Instead, it is sei
to java. io.TnputStream.class. Also, note that when the data flavor is con- p
strutted with a representation class, lhe inclusion of the class parameter in the
MIME type has not been implemented; if you try this, you'll discover that the
class parameter is missing. I
The humanPresentableName parameter is a localizable string that is meant to t
help a user identify the data flavor. This name is not used by the data transfer
mechanism.
Note: In Java 1.1.2, getMimeTypeO returns mimeType (or the derived MIME V
type). In a future release, the MIME type stored in the data flavor may possibly У
be the normalized version of lhe one supplied to the constructor. .
DataFlavor
java.awt .da la trans let
equals!)
PARAMETERS
mimelype Anon-null string containing a MIME type,
representationclass
/X non-nul 1 Cl ass object.
humanPresentableName
В H SEE ALSO EXAMPLE. Anon null localizable string. java.io.TnputStream, java.lang.Class, normalizeMjmeTypef). ’ See Transferable.
E I equalsO
G PI RPOSE Determines if two data flavors are equal.
H SYNTAX public boolean equalsfDataFlavor dataFlavor)
1 DESCRIPTION Two data flavors dfl and df2 are equal if isMimeTypeEqual (dfl, df2) is
J true and
К PARAMEI ERS dfl.getRepresentationCl assO -= df2.getRepresentationClass().
1. dataFlavor A non-nul 1 data flavor.
M RLILRNS true if dataFlavor is equal to this data flavor: false otherwise.
N OVERRIDES java.lang.Object.equals().
() SEE ALSO getRepresentationClassOT isMimeTypeEqualО. |
P EX AM PI 1 See Transferable. |
Q i
R gctHumanPresentableNameO
s T Pl RPOSE ) Retrieves this data flavor’s human-presentable (localizable) name. 1
i ! ’ SY MAX public String getHumanPresentableNameQ '
DI • SCRIPTIOS This method returns a human-presentable (localizable) name that is meant to ]
V help a user identify a data flavor. T he value of this name has no effect on how |
w the data is transferred. j
X RIH RSS A possibly nul 1 string containing the data flavor's human-presentable (local- i
Y izable) name. ;
z EXAMPLE See StringSelection.getTransferDataFlavorsO- j
504
getMimelVpeO
PURPOSE Retrieves the data flavor's MIME type.
SYNTAX public String getMimeTypeQ
DESCRIPTION The data flavor's MIME type specifies a particular data type such as a JPEG image or a Unicode siring. See the class description for information about a data flavor's MIME type. The MIME type is determined when the data flavor is created. It cannot be changed. Note: In Java 1.1.2, the returned MIME type is identical to the one supplied in the constructor. The returned MIME type may in a future release be the nor- malized version of the one supplied to the constructor.
RETURNS A non-nul 1 string containing the data flavor s MIME type.
SEE ALSO DataFlavorO, normalizeMimeType().
EXAMPLE See Stri ngSe1ection.get!ransferDataFlavors0
getRepresentationClassf)
PURPOSE Retrieves the data flavor’s representation class.
SYNTAX public Class getRepresentationClassO
DESCRIPTION The data flavor's representation class specifies how a transferable object should deliver its encapsulated data such as a byte stream or an array of bytes. See the class description for more information about the data flavor s represen- tation class.
RETURNS A non-nul 1 Class object.
EXAMPLE See StringSelection.getTransferDataFlavors().
isMimeTypeEquaK)
purpose: Determines if two MIME types are equal.
syntax public boolean isMimeTypeFqual(String mimeType) public final boolean isMimeTypetqual(DataFlavor flavor)
description This method normalizes mimeType (using norma 1 izeMimeTypeO) and com- pares it with the normalized version MIME type of this data flavor. If the two strings are equal, this method returns true. Otherwise, false is returned.
DataFlavor
norinalizeMime'f\pe(i
jav a.awt.datatransfer
The second form of this method (where flavor is specified} is equivalent to calling i sMimeTypeEqual (dataFlavor. getMimeType0). Note: In Java 1.1.2. this method simpl\ does a string comparison between mimeType and this data flavor's MIME type. The implementation will be com- pleted in a future release.
PARAMETERS flavor mi meType A non-nul 1 data flax or. A non-nul 1 string containing a MIME type.
SEE Al so getMime!ype().
normalizeMimeTypeO
PURPOSE Called to normalize a MIME type.
SYNTAX protected String normalizeMimeType(String mimeType)
DESCRIPTION This method is called to normalize a MIME type so that it can be compared xx ith another MIME type. This method also lakes each parameter in the MIME type and normalizes them by calling nomalizeMimeTypeParameterO. A subclass of a data flavor should call super. normal i zeMimeTypeQ before applying its own normalizing procedure. Note: In Java 1.1,2, this method simpl} returns mimeType. A normalizing algo- rithm will be implemented in a future version.
PAR.AME'I LRS mimeType A non-nul 1 string containing a MIME type.
normalizeMimeTypeParameterO
PURPOSE Called to normalize a parameter in a MIME type.
SYNTAX protected String normalizeMimelypeParameter(String parameterName, String parametervalue)
1>ES( RIP 1 ION This method is called by normalizeMimeTypeO as it normalizes a MIME type. The normal izeMimeType() method takes each parameter in the MIME type and normalizes it by calling this method. A subclass of a data flavor should call super. normalizeMimeTypeParame- terC) before applying its own normalizing procedure. Note: In Java 1.1.2. this method simply returns parameter Г ype + ’,-’1 + parametervalue
506
p I ainText Flavor
A normalizing algorithm will he implemented in a future version.
PARAMETERS
parameterName
A non-null string containing the name of a MIME type parameter,
parametervalue
A non-null string containing a MIME type parameter value.
plainTextFlavor
purpose: A standard data flavor for a string.
SYNTAX public static DataFlavor plainlextFlavor
DESCRIPTION When string data is being transferred via a clipboard, an application should use either this plain text data flavor or the string data flavor (see stringFlavor). This data flavor is used by the StringSelection class. The MIME type for this data flavor is ”text/plain; charset=uni code’1. The representation class for this data flavor is java. io. Stri ngReader. Note: In Java 1.1.2. the representation class for a plain text data flavor is actu ally nul 1. This is и /wg.
example: See StringSelection.getTransferDataO
setHumanPresentabieName()
pcrposi: Sets this data flavor s human-presentable name.
syntax public void setHumanPresentableName(Strinq humanPresentableName)
description A data flavor's human-presentable name is a localizable string that is meant to
help a user identify a data flavor. The value of this name has no effect on how
lhe data is transferred.
PARAMETERS
humanPresentableName
A possibly nul 1 string containing the data flavor's human presentable name.
example See Transfe rabl e.
DataFlavor
java.awt.datatransfer
stringFlavor
stringFlavor
pi rpose A standard data flavor for a string.
syxtax public static DataFlavor stringFlavor
X description When string data is being transferred via a clipboard, an application should use
В either this string data flavor or the plain text data flavor (see plai nTextTla-
vor). This data flavor is used by the StringSelection class.
The Ml MF type for this data flavor is "appl icat ion/x-java-serial ized-
" object; cl ass=java.1ang.String". The representation class for this data
Ь flavor is java.lang.String.
F Note: In Java 1.1.2. the actual MIME type for this data flavor is "applica
G tion/x-java-serial i zed-object".
„ example See StringSelection.getTransferDataO.
I
J
К
L
M
N
О
P
Q
R
S
T
t:
v
x
Y
z
508
Dialog
Syntax
public class Dialog extends Window
Description
A dialog component is a top-level window with a title bar and a border. A dialog can be modal.
It resembles a frame, but it has fewer properties. It does not have, for example, an icon image
or a cursor.
The Modal Property
A modal dialog, when visible, prevents the user from interacting with any other AWT window.
A modeless dialog does not have this affect; it behaves more like a frame. The modal property
can be changed at any time.
The Title Property
The title bar is a strip across the top of the dialog that displays a short description of the dialog.
The title can be changed at any time.
The Resizable Property
A resizable dialog allows (he user to change the size of the dialog. The resizable property can
be changed at any time. The precise manner in w’hich the user resizes the dialog is platform-
dependent.
Events
The dialog fires the same events as a window does. See lhe Window class for more details.
Dialog
ja\ a.awt
MEMBER SUMMARY
Constructor Di al ogO Constructs a new Dialog instance.
Property Methods getT i tle() Retrieves this dialog's tide.
i sModal() Retrieves this dialog's modal state.
i sResi zable() Retrieves this dialog's resi/able slate.
setModa1() Sets (his dialog's modal property.
setResi zable() Sets this dialog's resi/able propertv.
set Li tle() Sets this dialog's title.
V isibility Method showQ Makes this dialog visible and in front of all other window
Peer Method addNoti fy() Creates this dialog's peer hierarchy.
Debugging Method paramStri ng() Generates a string representation of the dialog's state.
I.
M
N
()
P
Q
R
S
T
Lt
V
w
X
Y
Z
Example
This example demonstrates how to center
a dialog with respect to its parent frame.
1’he dialog is always positioned so that its
bounds is within the screen bounds (Fig-
ure 116). It is defined to show a one-line
message. Also, it is modal and can be
closed b\ clicking either OK or the close
icon on the window title. The dialog is set
up such that it shows itself in the construc-
tor.
A frame w ith a single button is used to
create the message dialog. The message
that is displayed in the message dialog is
the current time in the default locale.
Message
The time is now - 4:22:12 AM PDT
OK
import java
import java
import java
import java
awt. ;
awt. event. *;
text. •;
uti1.*;
FIGI RE Ho: Centering я Dialog.
class Main extends Frame implements
ActionListener {
510
Button b = new ButtonC'See Current Time’1);
Main() {
super(“Dialog Example”);
// Listener for events.
b.addActionLi stener(thi s);
// Layout components.
add(b, BorderLayout.NORTH);
pack();
show();
}
public void actionPerformed(ActionEvent evt) {
// Get the current time in the default locale.
String time = DateFormat.getTime!nstance(
DateFormat.LONG) .format(new DateQ) I
// Create the message dialog.
new MessageDialog(this, “The time is now - “4-time);
}
public static void main(Stringn args) {
new Mai n();
}
}
class MessageDialog extends Dialog implements ActionListener {
MessageDialogfFrame f, String msg) {
super(f, “Message”, true);
// Create the components.
Button b = new Button(“OK");
Label 1 = new Label(msg, Label.CENTER) {
// This adds some space around the text,
public Dimension getPreferredSizeO {
Dimension d = super.getPreferredSizeO ;
return new Dimensioned.width+40, d.height+40);
}
};
// Listen for events.
b.addActionLi stener(thi s);
addWi ndowLi stener(new WindowEventHandlerO) ;
// Layout components.
add(l, BorderLayout.NORTH);
add(b, BorderLayout.SOUTH);
pack();
Dimension myDim = getSize();
Dimension frameDim = f.getSizeO;
Dimension screenSize = getToolkit().getScreenSize();
Point loc = f.getLocation();
// Center the dialog w.r.t. the frame.
loc.trans 1ate((frameDim.width-myDim.width)/2,
(frameDim.height-myDim.height)/?);
java.awt
Dialog
add\otity()
// Ensure that slave is withing screen bounds.
loc.x = Math.max(0, Math. mi n(loc. x, screenSi ze.width-getSizeQ . wi dt h));
loc.y = Math.max(0,
Math.min(loc.y, screenSize.width getSize().height));
A
В
setlocation(loc.x, loc.y);
show();
}
public void actionPerformedCActionEvent evt) {
dijposeO ;
I
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
di spose();
}
}
11
I
addNotify()
К PURPOSE Creates this dialog's peer hierarchy.
L SYNTAX public void addNotifyO
M DESCRIPTION This method creates the dialog's peer hierarchy, if necessary. The hierarchy
is created by calling the Toolkit.createDialog() method. 1'his method
IN should be called before the dialog's minimum or preferred size is calculated.
0 I'he methods Window.pack() and Window.show() automatically call
p addNotifyO.
Q OVERRIDES Component.addNoti fy().
D SEE Al.SO Component, Component.getMinimumSizeO,
К Component.getPreferredSizeO, Toolkit, Window.pack(),
S Window.show().
T EXAMPLE See Component.setVi si bl e ().
и
V DialogO
w „ . ,
purpose C onstructs a new Di al og instance.
X
syntax public Dialog(Frame parent)
Y public Dialog(Frame parent, boolean modal)
public Dialog(Frame parent, String title, boolean modal)
description This constructor creates a new invisible Dialog instance. If title is nul 1, the
dialog's title is blank. If title is not specified, the dialog's title defaults to
512
Lhalogf j
null. If modal is true, the dialog is modal; otherwise, the dialog is modeless.
If modal is not specified, the dialog is modeless. Both the dialog's modal prop-
erty and title can be changed at any time.
The default layout manager for the dialog is BorderLayout,
parameters
modal
parent
title
If true, dialog is modal: otherwise, the dialog is modeless.
I’he non-nul 1 parent of the dialog.
The string specifying the dialog s title. Can be nul 1,
exceptions
ПlegalArgumentException
If parent is null.
I
see also Component. setVi sibleO . setModa I (), setResizableO , setTi tleO.
example This example creates a frame that has two buttons. One creates a modal dialog;
the other creates a modeless dialog. Figure 117 shows the dialog creator as
well as the newly created modal and modeless dialogs.
Dialog Ex.
Ц Modal BFEH
FIGURE 117: Dialog (Teator. Modeless, and Modal Dialogs.
This example also show's how to create the dialog at a particular position on
the screen. This is done by calling the setLocation() method before calling
the showO method on the dialog.
import java.awt.*;
import java.awt.event
class Main extends Frame implements ActionListener {
Mainf) {
super(“Dialog Example”);
Button b;
add(b = new Buttonf‘Modal”), Borderl ayout.WEST);
b.addActionLi stenerCthis);
add(b = new Button(“Modeless“), BorderLayout.EAST);
b.addActionLi stener(this);
packO;
show();
}
public void actionPerformed(ActionFvent evt) {
String what = evt.getActionCommand();
if ("Modal”.equals(what)) {
new MainDialog(this♦ true);
} else if (“Modeless”.equals(what)) {
new MainDialog(this, false);
java.awt
Dialog
getTitle()
J
}
static public void main(String[J args) {
new Чапn();
}
}
class MainDialog extends Dialog implements Actionlistener {
// These two integers hold the location of the last window.
// New windows are created at an offset to the previous one.
static int offsetX, offsetY;
MainDialog(Frame frame, boolean modal) {
super(fname, modal);
setTit1e(isModal() ? “Modal” : “Modeless”):
Button b;
add(b - new Button(“Quit”), BorderLayout.CENTER);
b.addActionListener(thi s);
offsetX +- 20;
offsetY *= 20;
setLocation(offsetX, offsetY);
packQ ;
show();
1
public void actionPerformed(ActionFvent evt) {
di sposeO ;
}
}
getTitleO
РГRPOSE Retrieves the dialog's title.
SYNTAX public String getlitleC)
RlJl'RNS A string containing the dialog's title. The result value may be null.
FX AMPLE- See setTitle().
isModal()
PCRPOSI. Retrieves this dialog's modal state.
SYNTAX public boolean isModal()
DESCRIPTION A visible modal dialog prevents lhe user from interacting with any other AWT window. A modeless dialog does not have this affect: it behaves more like a frame. The modal property cannot be changed after the dialog is created.
Rl- Г1 RNS true if the dialog is modal: fal se if the dialog is modeless.
514
SEE ALSO setModal ().
example. See DialogO.
isResizable()
PURPOSE Retrieves this dialog’s resizable stale.
SYNTAX public boolean isResizable()
RETURNS true if this dialog is currently resizable; fal se otherwise.
EXAMPLE See setResizableO*
PURPOSE Generates a string representation of this dialog's state.
SYNTAX protected String paramStringO
DESCRIPTION The string representation of a dialog consists of its container siring representa tion and its title and whether it is modal. If you subclass Dialog, you should override this method to add your addi- tional state to the dialog's state by concatenating the new information with the results of super.paramStringO. This method is called by the toStringO method and is typically used for debugging.
RETURNS Л non-nul 1 string representing the dialog's state.
OVERRIDES Contai ner .paramStringO.
SEE ALSO Component.toStringO . java. 1 ang.Object.toStringO.
EXAMPLE This example shows how to override the paramStringO method. The over- ride appends an extra piece of state (myData) to the returned string. Figure 118 shows the output of the example. Maiп{0,0,0x0,i rival id, hidden, 1ayout=java.awt.BorderLayout mode- less, title-paramString Example,myData=Testing] FIGURE 118: Dialog.paramStringO Output.
import java.awt,*;
class Main extends Dialog {
String myData = "‘Testing”;
Dialog
setModaK)
java.awt
Main() { super (new FrameO, “paramStri ng Exampie”, false); } protected String paramString() {
A String str = super,paramString О; if (myData !- null) {
R c str -t-= myData-” + myData: } return str;
}
1. static public void mai n(Stri ng[] args) { Main m = new Main(); System.out.pri ntln(m);
h 1 }
H I setModaK)
—.
J pi rpose: Sets this dialog s modal property.
К syntax public void setModal(boolean modal)
L M description This method sets the dialog's modal property as specified by modal. PARAMETERS
N modal If true, dialog becomes modal; if fal se, dialog becomes modeless.
() p sit also i sModal ().
Q setResizahlet)
R — . .— — .. .— .. — . — —
s T pl rpose Sets this dialog's resizable property. syntax public synchronized void setResizablefboolean resizable)
A I desc ripi ion This method sets this dialog box to be resizable or nonresizable. II resizable is true, resizing is enabled: otherwise, it is disabled.
V PARAME 1 ERS ШИЖМЯРМЖ
w resizable If true, the dialog becomes resi/-
X Y able; otherwise, the dialog becomes E* n о n r es i zab 1 e. example This example creates a dialog with а Vя
Z checkbox indicating whether the dia- FIGURE 119; Dialog. setResizableO. log can be resized. Clicking the checkbox changes the resizable property of the dialog. See Figure 119.
516
import java.awt."4;
import java, awt. event.:
class Main extends Dialog implements ItemListener {
MainO {
super(new FrameO, “setResizable Example", false);
Checkbox cb = new Checkbox(“Resizable", null, isResizable());
cb.addltemListener(this);
add(cb, Borderlayout.NORTH);
pack О;
showO I
}
public void itemStateChanged(ItemEvent evt) {
setResizable(evt.getStateChangeO ItemEvent.SELECT ED);
}
static public void main(String[] args) {
new Mai n();
}
}
setTitle()
PURPOSE Sets this dialog's title.
SYNTAX public synchronized void setTitle(String title)
DESCRIPTION This method sets the dialog's title to be the string ti tie.
PARAMETERS title The string specifying the dialog's new title. A value of nul 1 clears the title.
SEE ALSO getTi tle().
EXAMPLE This example creates a text field in а dialog. 1 he text field is initialized with |^авИИИЯЕ!ВИяИИМНйЙ^И the current title of the frame. Pressing 1 setTitle Example | Return while in the text field sets the r , t I** ii FIGURE 120: Dialog.setTitleO frame s title to the text in the text field. See Figure 120.
import java.awt.О
import java.awt.event.♦;
class Main extends Dialog implements ActionListener {
TextField t;
Main() {
super(new FrameO, “setTitie Example", false);
// Initialize the text field with the current title,
t = new TextField(getTitleC), 50);
java.awt
Dialog
sho\v()
t.addAct ionListener(this);
add( t, BorderLayout.NORTH);
pack();
show();
}
Л public void actionPerformed(ActionEvent evt) {
setTitle((Str i ng) evt. get Act ion CommandO) ;
В }
C static public void main(String [] args) {
new Kain();
u
}
PURPOSE
I
SYNTAX
J
DESCRIPTION
К
1.
M
OVERRIDES
\
SEE ALSO
О
EXAMPLE.
show()
Makes this dialog visible and in front of all other windows.
public void show()
This method calls the addNotifyO method. validates the dialog's layout, and
then makes the dialog visible. If the dialog is already \ isible. it is brought to
the front. If the dialog is modal. showO will block until the dialog is no longer
\ isible (via setVi si ble(fal se) or di spose() h
Wi ndow.show().
Component.setVisibleO .
See setResizableO. setTitleO.
У
R
s
г
I’
V
w
X
Y
Z
518
DialogPeer
Syntax
public interface DialogPeer extends WindowPeer
Description
The dialog component (see the Dialog class) in the AWT uses the platform s native imple-
mentation of a dialog box. So that the AWT dialog box behaves the same on all platforms, the
dialog box is assigned a peer, whose task is to translate the behavior of the platform's native
dialog box to the behavior of the AWT dialog box.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
(heir peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently; most peer documentation refers to
java.awt counterparts.
See Component and Toolkit for additional information about component peers.
jjlgMBER SUMMARY
Peer Methods
setResizableO
setTitleQ
Sets the resizable property.
Sets the dialog’s title.
See Also
java.awt.Component< java.awt.Dialog, java.awt.Toolкit.
DialogPeer
setResizablef)
java, awt .peer
setResizable{)
PL* R POS I; Sets the resizable property.
SYMAX PARAMETERS resizable void setResizable(boolean resizeable) If true, the dialog becomes resizable; otherwise, the dialog becomes nonresi able.
SFF Al SO java.awt.Di al og.setResi zable()
setTitleO — —
PURPOSE Sets the dialog's title.
SYNTAX void setTitle(String title)
PARAMETERS title The string specifying the dialog's new title. A value of null clears the title.
SEE ALSO java.awt.Dialog.setfi tle().
520
Syntax
public class Dimension implements Serializable
Description
A dimension is used to represent a size. It holds two values: a width and height. In general,
when returning a dimension instance in a method call, you should either have a copy returned,
if you need to retain the instance, or have the instance discarded after it is returned. If you have
a dimension instance passed in a method call and wish to continue using the instance, note
whether the method will retain the instance or copy the values.
ОНЮИВЕЙ SUMMARY
Constructor DimensionO Constructs a new Dimension instance.
Size Methods getSi zeO setSizeO Retrieves a copy of this dimension. Changes the value of this dimension.
Fields height width Holds the dimension’s height. Holds the dimension's width.
Object Override Methods
equalsO toStri ng() Determines whether an object is equal to this dimension. Generates a string representation of this dimension s values.
See Also
Component.getSize() , Component. setSizeO , java.io.Serializable.
java.awt
Dimension
DimensionC)
Example
This example implements a Circle class, which is an
object that has an origin and radius. This Circle class
implements the getSize() method, which returns the cir-
cle's dimension. The example creates a circle object and
paints it in a frame. See Figure 121.
import java.awt.-;
class Main extends Frame {
Circle c - new Circle(new Point(60T 60), 25);
MainO {
super(“Dimension Example’*);
setSize(100, 100);
show();
}
public void paint(Graphics g) {
c.draw(g);
1
public static void main(StringГ1 args) {
new Mai n();
}
}
class Circle {
Point origin;
int radius;
Dimension Ex...
HGl RE 121: Dimension.
Circle(Point origin, int radius) {
th is.origin = origin;
this.radius - radius;
}
public Dimension getSizeO {
return new Dimension^? * radius, 2 radius);
}
public void draw(Graphics g) {
g.fi1lOval(origin.x radius, origin.y-radius,
getSizeO .width, getSizeO .height);
}
}
Dimension!)
purpose Constructs a new Dimension instance.
sY vi xx public DimensionC)
public Dimension(Dimension dimension)
522
cquaist )
public Dimensionfint width, int height)
DESCRIPTION This constructor creates a new Dimension instance that has the specified ini- tial values. If dimension is specified, the initial values for the newj dimension are taken from dimension. If neither dimension nor width and height are specified, the default is 0.
parameters dimension height width The non-nul 1 dimension containing the initial values. The dimension's height. I’he dimension s width.
EXAMPLE See the class example.
eqiials()
purpose: Determines whether an object is equal to this dimension.
syntax public boolean equals(Object obj)
description An object obj is equal to this dimension if obj is an instance of Dimension
and has the same width and height as this dimension.
PARAMETERS
obj The object to compare.
returns true if obj is equal; fal se otherwise.
overrides java.lang.Component.equals().
example See getSizeO.
getSizet)
PURPOSE Retrieves a copy of this dimension.
SYNTAX public Dimension getSizeO
RETURNS A new instance of Dimension that is a copy of this dimension.
SEE ALSO height, setSizeO, width.
EX AM PI E This example is a variation on the class example. It allows the user to dynamically change the size of the circle. See Figure 122.
FIGI RE 122:
Dimension. getSizeO.
(
1
1
i
X
(
1
(
F
c
1
I
\
V
>
/
java.awt
Dimension
getSize()
import java.awt.'-':
import java.awt.event;
class Main extends Frame implements ActionListener {
Circle c - new Circle(new Point(60, 60), 25);
TextField textfield;
г:
i-
ci
н
i
j
к
I.
M
N
О
p
Q
R
S
T
L
V
w
X
Y
z
Main() {
super(“getSize Example”);
Panel p - new Panel (new GridLayoutQ, 0));
p.add(new Label (“radius1’));
p.add(textfield=new TextField(“25”));
textfield.addActionListener(thi s);
add(p, BorderLayout.SOUTH);
setSize(100, 150);
show();
}
public void paint(Graphics g) {
c,draw(g);
}
public void actionPerformed(ActionEvent evt) {
Dimension orig = c.getSize();
Dimension sz = orig.getSize(); // make copy
int radius = Integer.parselnt(evt.getActionCor
sz.setSize(radius*2, radius*2);
if (sz.equals(orig)) {
System.out.println(”Radius unchanged”);
} else {
c.setSi ze(sz);
}
repaint();
}
public static void main(String[; args) {
new Mai n();
}
}
class Ci rcle {
Point origin;
int radius;
Circle(Point origin, int radius) {
this, о rigin = origin;
this.radi us = radius;
}
public Dimension getSizeO {
return new Dimension(2 * radius, 2 * radius);
}
public void setSize(Dimension d) {
radius = d.width/2;
}
public void draw(Graphics g) {
524
g.fillOvaHorigin.x radius, origin.y-radius,
getSizeO .width, getSizeO .height) ;
}
}
height
PLRPOSI: This field holds this dimension's height.
SYNTAX public int height
SEE ALSO getSizeO, setSizeO, width.
EXAMPLE See the class example.
setSize()
PURPOSE Changes the value of this dimension.
SYNTAX public void setSizefDimension dim) public void setSizefint width, int height)
DESCRIPTION This method changes the value of this dimension. If the dimension dim is sup- plied, the width and height of this dimension are set to dim.width and dim. hei ght, respectively. If width and height are supplied, they are used as the new w idth and height values for this dimension.
PARAMETERS dim height width The dimension to use. The height to use. The width to use.
SEE ALSO getSizeO, height, width.
example See getSizeO.
toString()
purpose Generates a string representation of this dimension.
syntax public String toString()
description This method generates this dimension's siring representation, which consists
of its width and height.
This method is typically used for debugging.
java.awt
Dimension
width
RETl’RNS A non-null string representing this dime
OVERRIDES java. lang.Object.toStringO.
EXAMPLE See java. lang.Object.toStringO.
width
Pl’RlH )Sk This field holds this dimension's width.
SYNTAX public int width
SEE ALSO getSizeO, height, setSizeO.
1АЛМР1.Е See the class example.
526
DirectColorModel
Syntax
public class DirectColorModel extends ColorModei
Image
Pixel
Value
»|~~ARGB~|
KIGl’RE 123: Direct Color Model Pixel Values
Description
A pixel value in an image can be encoded in
either a direct color model or an indexed color
model. In the direct color model encoding, pixel
values actually contain the color information;
the color model is used to extract the color infor-
mation from the pixel value (see Figure 123). The typical encoding used in a direct color
model is to divide the bits in a pixel value among the colors of this dimension’s components.
For example, in one encoding you could allow 2 hits each for red and green, 10 hits for blue,
and 4 bits for alpha.
See the ColorModei class for more information about color models. See IndexColor-
Model for more information about indexed color models.
fMEWBER SUMMARY
Constructor
Di rectColorModelQ
Constructs a Di rectColorModel from the given masks.
Color Component Retrieval Methods
getAlpha()
getBlueO
getGreenQ
getRedQ
getRGBQ
Retrieves the alpha component of a pixel value.
Retrieves the blue component of a pixel value.
Retrieves the green component of a pixel value.
Retrieves the red component of a pixel value.
Converts a pixel value to a pixel value in the default color model.
Color Component Mask Retrieval Methods j
getAl phaMaskQ Retrieves the bit mask for the alpha transparency component. |
getBlueMaskQ Retrieves the bit mask for the blue color component.
getGreenMaskQ Retrieves the bit mask for the green color component.
getRedMaskQ Retrieves the bit mask for the red color component.
DircctColorModel
jav a.awt. image
Direct Color Model Ex ДНЕЗ
1
1КЛ RE 124: DirectColorModel .
E
F
G
H
I
J
К
L
M
N
()
P
Q
R
s
1
U
V
w
X
Y
Z
Example
This example creates a low-resolution color filter
that reduces the number of hits of a color. Sec Figure
124. A frame is created that displays an image plus a
text field for entering the number of bits per color
component. When you change the value in the text
field, the image is passed through the filter and then
redisplayed. For example, if you enter the value 1 in
the text field, each of the four color components—
red. green, blue, and alpha—of even pixel value in
the image will be reduced to 1 bit.
The filter is derived from RGBImageFi 1 ter. this makes it convenient for modifying
image colors bv flowing all pixel values through a single method called filterRGBf) (see
RGBImageFi 1 ter for details). Whenever the bit si/e for the color components is changed, a
new direct color model is created to represent the new encoding. As pixels flow through the
filter, the colors of the pixel values are reduced and the filter's direct color model is substituted
for the image producer's color model.
import java.awt.';
import java.awt.image.л;
import java. awt. event . ;
import java.net.-’;
import java . uti 1 . ••;
class Main extends Frame implements Actionlistener (
TextField textField = new TextFieldO;
ImageCanvas icv;
Main(String filename) {
super(“Di rectColorModel Example');
try {
// Retrieve the image.
Image image = getToolkit().getlmage(fi1 ename);
addficv - new ImageCanvas(image), BorderLayout.CENTER);
add(textField, BorderLayout.SOUTH);
} catch (Exception e) {
e.pri ntStackT race();
}
// Add listener for text field
textField.addActionLi stener(thi s);
setSize(50, 100);
show();
}
public void actionPerformed(ActionEvent evt) {
i cv.setColorBi ts(Integer.parselnt(textFi eld.getText()));
}
static public void main(String[] args) {
if (args.length == 1) {
52Я
new Main(args[0]);
} else {
System.err,println("usage: java Main <image file>”);
}
}
}
class ImageCanvas extends Component {
Image newlmage;
Image image;
LowResFilter imgf - new LowResFi1ter();
ImageCanvas(Image image) {
this.image = image;
processimage();
}
void setColorBits(int bits) {
imgf.setColorBi ts(bits);
processImageO;
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
g.drawlmage(newlmage, 0, 0, this);
}
void processImageO {
ImageProducer ip = image.getSourceO;
ip new FilteredImageSource(ip, imgf);
newlmage getToolkit() .createlmage(ip);
repai nt();
}
}
class LowResFilter extends RGBImageTi1 ter {
int bits; // bits for each color.
DirectColorModel lowResColorModel -
(Di rectColor^odeI)ColorModel.getRGBdefault();
void setColorBits(int bits) {
int mask ~ 0;
this.bits - bits;
for (int i=0; i<bits; i++) {
mask (masked) + 1;
}
lowResColorModel = new DirectColorModel(bits v 3,
mask<<(2 * bits), mask<<bitsr mask);
System.out.println(
Integer. toString(lowResColorMode 1 .getAlphaMaskQ , 16)) ;
System.out.println(
Integer. toStri ng(lowResColorModel . getRedMaskO , 16)) ;
System.out.println(
Integer.toString(lowResColorModel.getGreenMask(), 16));
System.out.println(
1)
DirectColorModel
DirectColorModel)
jav a. awt. image
Integer.toStri ng(lowResColorModel.getBlueMask()। 16));
public void setColorModel(ColorModei model) {
consumer.setColorModel(lowResColorModel);
public int fi1terRGB(int x, int y, int rgb) {
int
i nt
int
i nt
i nt
res - 1 << bits;
a = ColorModel.getRGBdefault().getAlpha(rgb);
r = ColorModei.getRGBdefau1t().getRed(rgb);
g = ColorModei.getRGBdefault(),getGreen(rgb);
b - ColorModei.getRGBdefault().getBlue(rgb);
return ((a res / 256) << 3vbits)
res / 256) « ?-fbits)
res / 256) « bits)
I ((r *
I (<q *
I (Cb * res / 256));
public void fi 1 terRGBPixels(int x, int y,
int pixels[] ,
int
for
i ndex - off;
(int cy - 0; cy < h; cy*+) {
for (int ex = 0; ex < w; cx++) {
pixels[indexJ - filterRGB(x +
i ndex++;
i nt
int
w, int h,
off, int scansize) {
у + су, pixelsLindexl);
A
В
c
E
H
К
}
1
ex,
index +- scansize - w;
M
consumer.setPixels(x, yT w, h, lowResColorModel, pixels, off, scansize);
}
()
P
Q
DirectColorModel ()
R
Pt RPOSE:
SYNTAX
DESCRIPTION
PARAMETERS
amask
Constructs a Di rectColorModel instance.
Г
public DirectColorModel(int bits, int rmask, int gmask, int
bmask)
public DirectColorModel(int bits, int rmask, int gmask, int bmask,
int amask)
V
W
X
V
These constructors construct a new DirectColorModel object based on the
specified masks. A mask for a color component specifies which bit positions in
the pixel values are occupied by the color component. For example, the value 3
specifies the bit positions О and 1 (small endian). The bit positions in a mask
must be contiguous, and the masks must not overlap. The sum of all of the
masks must be no more than the number of hits specified by bits.
The mask for the alpha color component.
530
bits bmask gmask rmask The total number of bits used by the pixel values. The mask for lhe blue color component The mask for the green color component. The mask for the red color component.
example See the class example.
getAlpha() . —
PURPOSE Retrieves the alpha component of a pixel value.
SYNTAX final public int getAlpha(int pixelValue)
DESCRIPTION This method retrieves the alpha component of the pixel value pixelValue. The return value must be in the range 0-255. where lhe value 0 means com- pletely transparent and the value 2 5 5 means completely opaque.
PARAMETERS pixelValue The pixel value specifying a color in the color model.
RETURNS The alpha transparency component in the range 0 255.
EXAMPLE See the class example.
getAlphaMaskf)
PURPOSE Retrieves the bit mask for the alpha transparency component.
SYNTAX final public int getAlphaMask()
DESCRIPTION The return value is identical to the one supplied to the constructor.
RETURNS The mask for the alpha component.
EXAMPLE See the class example.
getBluef)
PURPOSE Retrieves the blue component of a pixel value.
SYNTAX final public int getBluefint pixelValue)
DESCRIИ ION This method retrieves the blue component of the pixel value pixelValue. The return value must be in the range 0-255. where lhe value 0 means no blue and the value 25 5 means maximum blue.
DirectCoiorModel
getBlueMaskf)
java.awt.image
PARAMETERS pi xelValue The pixel value specifying a color in the color model.
REH RNS The blue color component in the range 0 255.
example See the class example.
getBlueMask()
l-
E
G
H
I
J
К
I.
M
X
О
p
Q
R
S
T
u
V
w
X
Y
Z
PURPOSE Retrieves the bit mask for the blue color component.
SYNIAX final public int getBlueMask()
DESCRIPTION The return value is identical to the one supplied to the constructor.
RETURNS The mask for the blue component.
EXAMPLE See the class example.
getGreen()
purpose Retrieves the green component of a pixel value.
syntax final public int getGreen(int pixelValue)
description This method retrieves the green component of the pixel value pixelValue.
fhe return value must he in the range 0-255» where the value 0 means no
green and the value 255 means maximum green.
PARAMETERS
pi xelValue The pixel value specifying a color in the color model.
returns I hc green color component in the range 0-25 5.
example See the class example.
getGreenMask()
purpose Retrieves the bit mask for the green color component.
syntax final public int getGreenMaskQ
description The return value is identical to the one supplied to the constructor.
returns The mask for the green component.
example See the class example.
532
getRedQ
PURPOSE Retrieves (he red component of a pixel value.
SYNTAX final public int getRedfint pixelValue)
DESCRIPTION This method retrieves the red component of the pixel value pixelValue. The return value must be in the range 0 255» where the value 0 means no red and the value 25 5 means maximum red.
PARAMETERS pixelValue The pixel value specifying a color in the color model.
RETURNS The red color component in the range 0 255.
EXAMPLE See the class example.
getRedMaskQ
PURPOSE Retrieves the mask that specifies which bits in the pixel value contain the red color component.
SYNTAX final public int getRedMaskQ
DESCRIPTION The return value is identical to the one supplied to the constructor.
RETURNS The mask for the red component.
example: See the class example.
getRGBQ ______________
PURPOSE Converts a pixel value to a pixel value in the default color model.
SYNTAX final public int getRGB(int pixelValue)
DESCRIPTION The pixel value pixelValue is converted Io an equivalent pixel value that must be interpreted using the default color model. The color of the new pixel value might not be identical to the color of pi xel Value, so there may be some loss of color information.
PARAMETERS pi xelValue The pixel value specifying a color in the direct color model.
returns Л pixel value that specifies a color in lhe default color model.
OVERRIDES ColorModel.getRCBC).
SEE ALSO ColorModel.getRGBdefault().
example See the ColorModel class example.
Note: Use of the Event class is deprecated. Use AWTEvent and its hierarchy of event sub-
classes instead.
Syntax
public class Event
Description
In Java 1.0. events that flow between the /XWT components are represented by objects of the
Event class. When an event such as a mouse click or a keyboard press occurs, a new platform-
independent Event object is created to hold data about the event. All events use the Event
class and so have the same fields, but not all fields are used for all events. The event type
determines which fields are to be used.
In Java LE event types are organized into a class hierarchy rooted at AWTEvent. For
example, there is a MouseEvent for describing mouse-related events and a KeyEvent for
describing keyboard input related events. Each of these classes might have event subtypes. For
example, a focus event has two event subtypes: gaining the focus and losing the focus. Each
AWTEvent subclass contains methods for retrieving properties specific to its event type.
In Java LE the old event model is still supported, but the usage of it is deprecated. You
should migrate your program to use the new event model, which is described in detail in
AWTEvent.
Firing Events
Events can be fired by a component as the user interacts with the component. In Java 1,0. not
all components fire events such as mouse and keyboard events. Instead, the component max
hide all mouse and keyboard events and fire only a single action event. In Java I.L all AWT
components can fire mouse and keyboard events, as well as focus and component events. To
determine what additional events a component fires, check the component's class description.
Events can also be fired other than in response to user interaction. For example, you may
want a component to become enabled when some asynchronous activ ity completes. The thread
doing the asynchronous activity could either disable the component directly or send it a special
event to perform that task itself. The latter method would be more appropriate if disabling the
component also involved other activities known only to the component.
In Java 1.0, special events can be created either by subclassing Event or by creating an
action event and filling in the arg and target fields. The event handler can then identify the
special event by testing the arg and/or target fields using the instanceof operator. In Java
1.1, special events can be created by subclassing the appropriate subclass of AWTEvent (see
See Also later in this discussion) and defining additional properties for the new event. You can
get a feel for how to do this by examining the existing subclasses of AW7 Event.
Event Elow
In Java 1.0, events flow up the com
ponent hierarchy. For example, a
button that fires an action event can
either handle the event itself or not.
If it doesn’t, the AWT framework
automatically forwards the event
onto the button’s parent. The parent
can either handle the event or not. If
it doesn't, the AWT framework
again forwards the event, this time to
the next parent. If no one handles the
event, the event is simply discarded.
See Figure 125(a).
In Java 1.1, the event flow does
not flow up the component hierar-
chy. In the new event model, event
listeners are registered with a com-
ponent for receiving events fired by
the component. There are different
types of event listeners registered for
the corresponding types of events.
When the component fires an event,
event listeners of that event type are
notified to handle the event. The
event does not flow up the compo-
nent hierarchy unless one of the
event listeners explicitly redis-
patches the event to the component’s
parent. If there are no event listeners
for the event type registered with the
component that fired the event, the
event is simply discarded. See Figure
125(b).
<bi New Java 1.1 Event Model
FIGI RE 125: Event Flow in C omponent Hierarchy.
Event
java.awt
Event Handlers
In Java 1.0, events are handled by overriding a component's handleEventO method. In
Java 1.1, events are handled by event listeners registered with lhe event's source. Typically,
a component controls how its different types of events are processed by adding or removing
Л event listeners of the corresponding type. If the component requires special processing to be
performed prior to the dispatching of the event to its listeners, it overrides Component .pro-
cessEventO.
Mouse Events
In Java 1.0. the AWT assumes that the mouse has only one button. This means that on a mouse
with more than one button, pressing any of the buttons fires the same event type. A specific hit
set in the event's modifiers field indicates which button was pressed. In particular, if the
ALT_MASK bit is set, the middle mouse button w as pressed; if the META_MASK bit is set. the right
mouse button was pressed. On platforms with mice that have fewer than three buttons, (he
extra buttons can be simulated by holding down the appropriate modifier key (Shift. Control,
or Alt) while pressing the mouse button.
1'his design does not allow you to determine, for example, on a platform with a three-but-
ton mouse, whether the right button was pressed or whether the left button w'as pressed while
the META_MASK was held down.
In Java 1.1. the mouse event's modifiers contain different bit masks for the mouse button
keys and the Alt, Meta, and Control keys. This means that you can always determine which
mouse button was pushed, as well as the modifier key (if any) held while pressing the mouse
button. See MouseEvent for details.
()
P
Q
R
S
T
U
V
w
X
Y
z
Cursor Coordinates
In Java 1.0, the coordinates of the cursor are captured in the x and у fields for mouse-related
events. As an event travels up the component hierarchy, the cursor coordinates are automati-
cally translated to be relative to the bounds of the component currently holding the event. This
means the cursor coordinates are alwrays relative to the bounds of the component that handles
the event, not to the bounds of the component that fires the event, I’or example, if an event was
fired by a button in a panel and the event wzas handled by the panel, the cursor coordinates in x
and у would be relative to the bounds of the panel, not to the bounds of the button.
Another important fact about cursor coordinates in an event is that if the component han-
dling the event is a container with nonzero insets, the cursor coordinates are relative to the
container's inset area rather than to the container's bounds; see the Container class for more
details.
In Java 1.1. the coordinates of the cursor are captured in the MouseEvent instance and are
obtained using its getXO and getYQ methods. These coordinates are not translated relative
to the listeners handling the event because a listener need not even be a component. The coor-
dinates in a mouse event are always relative to the bounds of the source component that tired
the event.
536
Compatibility of Event Models
The Java LI AWT can handle both components that use the Java 1.1 event model and compo-
nents that use the Java LO event model. However, mixing components that use both models in
a single application or applet or mixing Java 1.1 and Java 1.0 events within a single component
is not recommended.
When an event is fired, the AWT must determine whether to use the Java 1.1 model or the
Java LO model to process it. An event is classified as a Java 1.1 event if the event s source has
any registered listeners (regardless of event type) or if Component .enableEventsO has been
called on it (regardless of event type). Otherwise, the event will be treated as a Java 1.0 event
and processed using the target component's handl eEvent О method as described previously.
Because the event flows of the two event models are different, a Java LO event will be
propagated up its component hierarchy, while a Java LI event will not be propagated further
than the event’s source. This is true independent of the model used by the object’s containers
in its component hierarchy. In other words, a Java LI event will never propagate up its
source’s container hierarchy, even if the source’s parent is using the Java 1.0 event model,
while a Java 1.0 event will always be propagate up its component hierarchy.
Event
ja\ a.awi
Г MEMBER SUMMARY i I
| Constructor 1
Fvent() Use constructors for one of AWTEventN subclasses instead.
A I Event Types 1
В ACTION-EVEN I Replaced b\ ActionEvent .ACTION-PERFORMED.
I G01_r0CUS Replaced by TocusEvent. FOCUS.GAINED. (
C I KEY ACTION Replaced by KeyEvent. KEY. PRESSED.
I? KEY .ACTION-RELEASE Replaced by KeyEvent. KEY.RELLASED.
j KEY_PRESS Replaced by KeyEvent. KEY.PRESSED. 1
KFY.RELFASt Replaced by KeyEvent. KtY.RELEASED.
г | 1 TSI.DESbLFCT Replaced by ItemEvent.ITEM.STATE.CHANGED.
I LISI.SELECT Replaced by ItemEvent. ITEM_STATE_CHANGED. •
G LOAD FT LF Not used. 1
II 1 LOSl.FOCUS Replaced by Focus Event. FOCUS-1 OST
MOUSE. DOWN Replaced by MouseEvent.MOUSE.PRESSFD.
! | MOUSF. DRAG Replaced by MouseEvent. MOUSE-DRAGGED. |
J MOUSE-ENTER Replaced by MouseEvent.MOUSF_ENTERED.
I MOUSE-EXIT Replaced by MouseEvent.MOUSF_EXITED.
К । MOUSF,MOVE- Replaced by MouseEvent. MOUSE-MOVED. |
I. MOUSF.UP Replaced by MouseEvent. MOUSE-RELEASED.
1 SAVE.L1LF Not used.
M SCROLL.ABSOLUTE Replaced by AdjustmentEvent.TRACK. ।
N I SCROLL.LINE,DOWN Replaced by AdjustmentEvent. UNIT_INCREMFNT. 1
1 SCROLL.LINF.UP Replaced by Adjustmenttvent.UNIT-DECREMENT.
() SCROLL PAGE.DOWN Replaced by AdjustmentEvent. BLOCK-INCREMENT
P | SCROLL .PAGE.UP Replaced by AdjustmentEvent. BLOCK-DECREMENT. |
WINDOW.DEICONIFY Replaced by Wi ndowEvent.WINDOW_DEICONIF [ED.
Q I WINDOW.DESTROY Replaced by Wi ndowEvent .WINDOW-CLOSING.
R | WINDOW.EXPOSE Replaced by WindowEvent.WINDOW.ACTIVATED. »
WINDOW.1CONTFY Replaced by Wi ndowEvent. WINDOWLICONI FI ED. |
S | WINDOW-MOVED Replaced by ComponentEvent.MOVED.
T Event Fields
и I arg Replaced by event-specific properly. |
v I clickCount Replaced by MouseEvent.getClickCountO
V evt Replaced by EventQueue.
W 1 id Replaced by AWTEvent. getIDO. |
Y key Replaced by KeyEvent.getKeyCode().
A. I modifiers Replaced by InputEvent.getModifiers().
Y | target Replaced by Eventobject. get Sou reef).
у when Replaced by InputEvent .getWhenQ. I
1 X Replaced by MouseEvent .getX().
1 У Replaced by MouseEvent. getY().
538
fffiMBER SUMMARY J— Keyboard Modifier Masks ALT-MASK CTRL-MASK META_MASK SHIFT-MASK Replaced by InputEvent. AL I .MASK. Replaced by InputEvent.CTRL.MASK. Replaced by InputEvent.MEIA-MASK. Replaced by InputEvent.SHIFT-MASK.
Keyboard Modifier Methods
control Down 0 metaDown() shiftDownO Replaced by InputEvent. isControlDownO. Replaced b\ InputEvent. i sMetaDownQ. Replaced by InputEvent. i sShi ftDownQ.
Non-ASCII Key Constants
DOWN Replaced by KeyEvent. VK_DOWN.
END Replaced by KeyEvent. VK_END.
Fl Replaced by KeyEvent.VK_F1,
F10 Replaced by KeyEvent.VK_F10.
Fll Replaced by Key Event. VK_F11.
F12 Replaced by KeyEvent,VK.F12.
F2 Replaced by KeyFvent.VK_F2.
F3 Replaced by KeyEvent.VK_F3.
F4 Replaced by KeyEvent. VK_F4.
F5 Replaced by KeyEvent .VK_F5.
F6 Replaced by KeyEvent. VK_F6.
F7 Replaced by KeyEvent .VK_F7.
F8 Replaced by KeyEvent. VK_F8.
F9 Replaced by KeyEvent. VK_F9.
HOME Replaced by KeyEvent.VK_HOME.
LEFT Replaced by KeyEvent. VK_L EFT.
PGDN Replaced by KeyEvent.VK_PAGE_DOWN.
PGUP Replaced by KeyEvent. VK_PAGE_UP.
RIGHT Replaced by KeyEvent, VK RIGHT.
UP Replaced by KeyEvent. VK_UP.
Translate Method
translateO Replaced by MouseEvent. translatePoi nt()
Debugging Methods
paramStri ngO Replaced by AWTEvent. paramString().
toStri ngO Replaced by AWTEvent. toStri ng().
Event
java.awt
Г
G
H
I
J
К
L
M
N
()
P
Q
R
S
T
u
V
w
X
Y
Z
See Also
AWTEvent, AWTEventMulticaster, Component.di spatchEventO,
Component.processEventO, java.awt.event.ActionEvent,
java.awt.event.ActionLi stener, java.awt.event.AdjustmentEvent,
java.awt.event.AdjustmentLi stener, java.awt.event.ComponentEvent,
java.awt.event.ComponentLi stener, java.awt.event.Contai nerEvent,
java.awt.event.ContainerListener, java.awt.event.FocusEvent,
java.awt.event.FocusListener, java.awt.event.InputEvent,
java.awt.event.ItemEvent, java.awt.event.ItemLi stener,
java.awt.event.KeyEvent, java.awt.event.KeyEventLi stener,
java.awt.event.MouseEvent, java.awt.event.MouseLi stener,
java.awt.event.MouseMotionListener, java.awt.event.TextEvent,
java.awt.event.TextLi stener, java.awt.event.WindowEvent,
java. awt. event .Wi ndowLi stener.
Example
As mentioned previously in this section, the events that are fired by the AWT components in
Java 1.0 are not consistent. To cope with this, you can use (he following example to experi-
ment with each component to determine exactly what events it fires and in what situations.
The program handles every event that is fired by any of the components and prints the details
of the event to standard output.
An example written using the Java 1.1 event model proxiding the same functionaliw is
shown as well.
See Figure 126 for a screen shot of this example.
FIGURE 126: A Container of All AWT Components.
540
Java 1.0
import java.awt.*;
class Main extends Frame {
Main() {
super(“Fvent example’’);
// Menu bar with a menu and menu item.
MenuBar mb = new MenuBarO;
Menu m - new Menu(“Menu”);
m.add(“MenuItem”);
m.add(new CheckboxMenuItemC'CheckboxMenuItem”));
mb.add(m);
setMenuBar(mb);
setLayout(new GridLayout(0, 3));
// checkbox, grouped checkbox, label, text field, scrollbar, button
add(new Checkbox(“Checkbox”));
add(new Checkbox(“Checkbox”, new CheckboxGroupO, true));
add(new Label(“label”));
add(new TextField(“TextField”));
add(new Button(“Button”));
add (new MyCanvasO);
// scrollbar
Scrollbar sb new Scrollbar(Scrol1 bar.HORIZONTAL);
sb.setValues(50, 50, 0, 100);
add(sb);
// choice
Choice choice = new ChoiceO;
choice.add!tem(“Choice”);
choice.addltem(“a choice item”);
add(choice);
// list
List list = new List() ;
list.add!tem(“List”);
1ist.addltem(“a list item1’);
add(li st);
// text area
TextArea textArea = new TextArea(“TextArea”);
textArea.resize(100, 50);
add(textArea);
pack();
show();
public boolean handleEvent(Event evt) {
if (evt.target instanceof Button) {
System.out.pri nt(“Button”);
} else if (evt.target instanceof Choice) {
System.out.pri nt(“Choi ce”);
} else if (evt.target instanceof Checkbox) {
System.out. pri nt(“Checkbox’’);
} else if (evt.target instanceof CheckboxGroup) {
System.out.pri nt(“CheckboxGroup”);
} else if (evt.target instanceof Label) {
Event
java.awt
b
U
H
1
J
к
L
M
N
()
P
Q
R
S
Г
U
V
w
X
У
z
System.out.print(“Label”);
} else if (evt.target instanceof TextField) {
Sy st err. out . print(“ TextField”) ;
} else if (evt.target instanceof Scrollbar) {
System.out.pri nt(“Scrol1 bar”);
} else if (evt-target instanceof Canvas) {
System.out.print(“Canvas”);
} else if (evt.target instanceof List) {
Syst em.out.pri nt(“Ii st”);
} else if (evt.target instanceof TextField) {
Sy st err. out .pri nt (“TextField”) ;
} else if (evt.target instanceof TextArea) {
System.out.pri nt(“TextArea”);
} else if (evt.target instanceof Menuitem) {
System.out.print(“wenultem”);
} else if (evt.target instanceof Container) {
System.out -pri nt(“Contai ner”);
}
System.out.print(“ “);
switch (evt.id) {
case Fvent.AC IION_EVENT:
System.out.pri nt(“ACTION.EVENT”); break;
case Event.GOT_FOCUS:
System.out.pri nt(“GO!.FOCUS”); break;
case Event.KEY^ACTION:
System.out,pri nt(“KEY.AC I ION”); break;
case Event.KLY_ACTION_RELEASE:
System.out.print(“KEY_ACriON. RELEASE”); break:
case Event.KEY_PRESS:
System.out,pri nt(“KEY_PRESS”); break;
case Event.KEY-RELEASE:
System.out,pri nt(“KEY_RELEASE”); break;
case Event.LIST_DESEI EC Г:
System.out.print(“LISTJDESELECl”); break;
case Event.LIST-SELECT:
System.out.print(“LIST_SElECT’') ; break;
case Fvent.LOAD-FILE:
System.out.print(“LOAD.FILF”); break;
case I vent.LOST_FOCUS:
System.out.pri nt(“LOS1_FOCUS”); break;
case Event.MOUSF_DOWN:
System.out.print(“MOUSE_DOWN”); break;
case Event.MOUSF_DRAG:
System.out.pri nt(“MOUSF_DRAG”); break;
case Event.MOUSE_ENTER:
System.out.print(“MOUSE-ENTER”); break;
case Event.MOUSE-EXIT:
System.out.pri nt(“MOUSE .FXIT”); break;
case Event.MOUSE-MOVE:
System.out.print(“MOUSE-MOVE”); break;
case Event.MOUSE„UP:
System.out.print(“MOUSE .UP”); break;
case Event.SAVE .FILE:
System.out.print(“SAVE.FILF”); break;
case Event.SCROLL-ABSOLUTE:
System.out.pri nt(“SCROLL-ABSOLUTE”); break;
case Event.SCROLL_LINE_DOWN:
System.out.print(“SCROLL _LINF_DOWN”); break;
case Fvent.SCROIL LINE_UP:
542
System.out.pri nt(“SCROLL-LINE-UP"); break;
case Event.SCROLL_PAGE_DOWN:
System.out.pri nt(“SCROLL..PAGE.DOWN”); break;
case Event. SCROLL,_PAGE_UP:
System.out.print(“SCROLI-PAGE UP"); break;
case Event. WINDOW..DE1CONIFY:
System.out.print(“WINDOW_DElCONIFY"); break;
case Fvent.WINDOW_DESTROY:
System.out.print(”WINDOW_DESTROY”); break;
case Event.WINDOW-EXPOSE:
System.out.pri nt(“WINDOW_EXPOSE"); break;
case Event.WINDOW.ICON1FY:
System.out.print(“WTNDOW ICONIFY”); break;
case Event.WINDOW-MOVED:
Systern.out.print(”WINDOW_MOVED"); break;
}
System.out.print(“ (“+evt.x+" “+evt.y+”) *(“*evt.when-F”)");
System.out.print(“ k(“*(char)evt.key+") m(“*evt.modifiers+")”);
System.out.print(“ cC'+evt.clickCount*”) a(“+?vt .arg*”)’’) ;
System.out.pri ntln();
return false;
}
static public void main(String[J args) {
new Main();
}
}
class MyCanvas extends Canvas { L
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetrics();
g.drawString(“Canvas”,
(sizeO . width-fm. stringWidth(“Canvas''))/2, 4
(size() .height-fm.getAscent())/2);
1
}
F
Jutput
Canvas KEY-RELEASE (540 183) *(827558080120) k(_) m(0) c(0) a(null)
Canvas LOST FOCUS (540 183) w(0) k(-) m(0) c(0) a(null)
Canvas MOUSE.ENTER (347 454) *(827558089680) k(_) m(0) c(0) a(null)
Canvas MOUSE-MOVE (347 454) w(827558089680) k( ) m(0) c(0) a(null)
Canvas GOT_FOCUS (302 452) w(0) k(„) m(0) c (0) a(null)
Canvas MOUSE-MOVE (343 465) w(827558090010) k(_) m(0) c(0) a(null)
Canvas MOUSE-DOWN (343 464) w(827558090010) k(_) m(0) c(l) a(null)
Canvas MOUSE. DRAG (331 480) w(827558092040) k(_) m(0) c(0) a(null)
Canvas MOUSE.UP (331 480) w(827558092040) k(_) m(0) c(0) a(null)
Canvas MOUSE-MOVE (331 480) w(827558092040) k(_) m(0) c(0) a(null) 4
Canvas MOUSE-MOVE (309 477) w(827558092150) k(_) m(0) c(0) a(null)
Canvas MOUSE-EXIT (251 467) w(827558092260) k(_) m(0) c(0) a(null)
Canvas LOST-FOCUS (302 452) w(0) k(-) m(0) c(0) a(null)
Button ACTION-EVENT (153 93) w(0) k(. ) m(0) c(0) a(Button)
TextField KEY_PRESS (4 93) *(827558094240) k(k) m(0) c(0) a(null)
TextField KEY-RELEASE (4 93) *(827558094340) k(k) m(0) c(0) a(null)
TextField KEY-PRESS (4 93) *(827558094450) k(l) m(0) c(0) a(null)
Checkbox ACTTON.FVFNT (4 42) w(0) k(„) m(0) c(0) a(true)
Checkbox ACTION.FVFNT (4 42) w(0) k(_) m(0) c(0) a(false)
Scrollbar SCROLL-PACE. UP (4 144) w(0) k(„) m(0) c(0) a(40)
Scrollbar SCROLL-ABSOLUTE (4 144) *(0) k(_) m(0) c(0) a(20)
Scrollbar SCROLl_LINE-UP (4 144) w(0) k(_) m(0) c(0) a(17)
Event
java.awt
Sc го II bar SCROLL-ABSOLUTE (4 144) w(0) k(_) m(0) c(0) a (22)
Scrollbar SCROLL-LINE-DOWN (4 144) w(0) k(_) m(0) c(0) a(23)
List LIST .SELECT (302 144) w(0) k(_) m(0) c(0) a(0)
List ACTION-FVFNT (302 144) w(0) k(_) m(0) c(0) a(List)
TextArea KEY-PRESS (4 195) w(827558105110) k(k) m(0) c(0) a(null)
TextArea KEY-RELEASE (4 195) «(827558105490) k(j) m(0) c(0) a(null)
A Container MOUSE_MOVE (799 10) «(827558114500) k(_) m(0) c(0) a(null)
Container MOUSE-MOVE (799 2) «(827558114670) k(_) m(0) c(0) a(null)
В Container WINDOW-DESTROY (0 0) w(0) k(_) m(0) c(0) a(null)
C
Java 1.1
F
G
H
I
J
К
import java.awt.*;
import java. awt. event . ;
class Mai nil extends Frame {
Mai nil О {
super(“Event example using lava 1.1“);
// Create listeners for all components
MouseListener ml = new MousetventHandler();
MouseMotionListener mml - new MouseMotionEventHandlerO ;
FocusListener fl = new FocusEventHandlerQ ;
ComponentListener cpl new ComponentEventHandlerQ;
KeyListener kl = new KeyEventHandlerQ;
Container! istener ctl = new ContainerFventHandlerQ ;
WindowListener wl = new WindowEventHandlerQ;
// Handles Action, Text, Item and Adjustement events
SemanticEventHandler si = new SemanticEventHandlerO;
// Add listeners for frame, this will catch
// events as components are added
addMouseListener(ml);
addMouseMotionLi stener(mml);
addFocusListener(fl);
addComponentLi stener(cpl);
addKeyListener(kl);
addContainerLi stener(ctl);
addwi ndowLi stener(wl);
// Menu bar with a menu and menu item.
MenuBar mb - new MenuBarO;
Menu m new Menu(“Menu”) ;
CheckboxMenuItem cbm = new CheckboxMenuItem(“CheckboxMenultem”);
m.add(“MenuItem”);
m.add(cbm);
mb.add(m);
setMenuBar(mb);
setLayout(new GridLayout(0, 3));
// checkbox, grouped checkbox, label, text field, scrollbar, buti
Checkbox cbl, cb2;
Label label;
Text Field text Field; 1
544
Button button;
MyCanvas canvas;
add(cbl = new Checkbox("Checkbox”));
add(cb2 new Checkbox("Checkbox", new CheckboxGroupO, true));
add(label = new Label("1abel”));
add(textField = new TextFie ld(”IextF ield”)) ;
add(button = new Button(“Button”)) ;
add(canvas = new MyCanvasO);
// scrollbar
Scrollbar sb = new Scrollbar(Scrol1 bar.HORIZONTAL);
sb.setValues(50, 50, 0, 100);
add(sb);
// choice
Choice choice =. new ChoiceO;
choice.add!tem("Choice”);
choice.addltem("a choice item”);
add(choi ce);
// list
Li st list - new L i stQ ;
list.add!tem("Li st”);
list.addltem("a list item”);
add(li st);
// text area
TextArea textArea = new TextArea("lextArea”);
textArea.setSize(100, 50);
add(textArea);
// Add listeners to components
// Checkboxes
cbl.addMouseListener(ml);
cbl.addMouseMotionLi stener(mml);
cbl.addFocusListener(fl);
cbl.addComponentlistener(cpl);
cbl.addKeyListener(kl);
cbl.addltemli stener(si);
cb2.addMouseLi stener(ml);
cb2.addMouseMotiont istener(mrrfl) ;
cb2.addFocusListener(fl);
cb2.addComponentListener(cpl);
cb2.addKeyListener(kl);
cb2.addltemLi stener(si);
// Choice
choice.addMouseListener(ml);
choi ce.addMouseMotionL i stener(mml);
choice,addFocusListener(fl);
choi ce.addComponentLi stener(cpl);
choice.addKeyl istener(k1) ;
choice.addItemListener(si);
// Label
label.addMouseListener(ml);
Event
java.aw i
1 abel , addMouseMot ionLi stener(mml) ;
label.addFocusLi stener(fl);
label.addComponentListener(cpl);
label.addKeyListener(kl);
// Button
button.addMousetistener(ml);
button.addMouseMotionListener(mml);
button.addFocusListener(fI);
button.addComponentListener(cpl);
button.addKeyl istener(kl) ;
butt on.addActionLi stener(si);
// Scrollbar
sb.addMouseli stener(ml);
sb.addMouseMotionl istener(mml);
sb.addFocusListener(fl);
sb.addComponentListener(cpl);
sb.addKeyListener(kl);
sb.addAdjustmentL istener(sl);
// List
list.addMouseii stener(ml);
li st.addMouseMotionLi stener(mml);
1i st.addFocusListener(fl);
1ist.addComponent 1 istener(cpl);
list.addKeyLi stener(kl);
list.addltemListener(si);
list.addActionLi stener(s1);
// Text Field
textf ield.addMouseLi stener(ml);
textFi eld.addMouseMotionLi stener(mml);
textField.addFocusLi stener(t1);
textFi eld.addComponentLi stener(cpl);
textField.addKeyListener(kl);
textField.addActionLi stener(si);
textField.add!extli stener(si);
// Text Area
textArea.addMouseL istener(ml);
textArea.addMouseMotionLi stener(mml);
textArea.addFocusListener(fl);
textArea.addComponentl istener(cpl);
textArea.addKeyListener(kl);
textArea.addTextListener(sl);
// canvas
canvas.addMouseListener(ml);
canvas.addMouseMotionLi stener(mml);
canvas.addFocusListener(fl);
canvas.addComponentLi stener(cpl);
canvas.addKeyl istener(kl);
// Checkbox Menu
cbm.addltemLi stener(si);
cbm.addActionLi stener(si);
// Menu
m.addAct i onLi stener(si) *,
546
pack();
show();
class MouseEventHandler implements MouseListener {
void printEvent(MouseEvent evt) {
System.out.print(“ (“+evt.getX()+” “+evt.getY()+”) w(“);
System.out.println(evt.getWhen()+”)”);
System.out.print('‘m(“ + evt.getModif iers()+’,)', + ” c(”);
Sy stem, out. pri ntl n (evt .getClickCount () + '') ”) ;
}
public void mousedicked(MouseEvent evt) {
System.out.print(“ (“+evt.getXQ +” “+evt .getY()4n) w(“);
System.out.pri nt(“MOUSE-CLICKED”);
pri ntEvent(evt);
}
public void mousePressed(MouseEvent evt) {
System.out.print(“ (“+evt.getX() + ” "+evt.getY()+”) w(“);
System.out.print("MOUSE DOWN”);
pri ntEvent(evt);
}
public void mouseReleased(MouseEvent evt) {
System.out.print(“ (“+evt.getX()+” “+evt.getY()+”) w(“);
System.out.pri nt(“MOUSE-UP”);
printEvent(evt);
}
public void mouseEntered(MouseEvent evt) {
System.out.print(‘J ("+evt.getXO+" “+evt .getY() + '') w(“);
System.out.pri nt(“MOUSE-ENTER");
printEvent(evt);
}
public void mouseFxited(MouseEvent evt) {
System.out.print(“ ("+evt.getX()+ ” "+evt.getY()>”) w(“);
System.out.print(“MOUSE EXIT”);
printEvent(evt);
}
}
class MouseMotionEventHandler implements MouseMotionL istener {
void printEvent(MouseEvent evt) {
System.out.print(" (“+evt .getX()f ” "+evt. getYO-f-”) w(“);
System.out.print In(evt.getWhen()+”)”);
System.out.print(“m(“+evt.getModitiers()+”)”+“ c(“);
System.out.pri ntln(evt.getClickCount()+”)”);
}
public void mouseDragged(MouseEvent evt) {
System.out.print(evt .getSourceO .getClassO + ” “);
System.out.print(“MOUSF_DRAC”);
pri ntEvent(evt);
}
public void mouseMoved(MouseEvent evt) {
System.out.pn’nt(evt.getSourceO .getClass() + “ ") ;
System.out.pri nt(“MOUSE-MOVE”);
pri ntEvent(evt);
1
f
Event
java.awt
}
// Implements methods for Action, Text, Item, Adjustment
class SemanticEventHandler implements ActionListener, ItemListener,
Textlistener, AdjustmentListener {
public void actionPerformed(Actionhvent evt) {
A System.out.print(evt.getSourceQ .getClassO * “
System.out.print(“ACTION .EVENT");
В System.out.printTn(“ cmd(“ < evt.getActionCommandO + “)’’);
}
C
public void itemStateChanged(ItemEvent evt) {
I) System.out.print(evt.getSourceQ .getClassO + “ “);
switch (evt .getStateChangeQ) {
case ItemEvent.SELECTED:
System.out.print(“JTFM_SFLLCT”);
F break;
Ci case ItemEvent.DESELECTED:
System.out.pri nt(“1TFM_DESELECT”);
H }
System.out.println(“ item( *’ r evt,getltem() i-
I }
J public void adjustmentValueChanged(AdjustmentEvent evt) {
System.out.print(evt. getSourceQ .getClassO + “ “);
К switch (evt.getlDQ) {
case AdjustmentEvent.TRACK:
L System.out-print("SCROLL-ABSOLUTE”);
break;
M case AdjustmentEvent.UNIT-INCREMENT:
System.out.print(“SCROLL-LINE .DOWN”);
X break;
case AdjustmentEvent.UNIT_DECREMENT:
О System.out.print(“SCROLL-L1NE_UP“);
break;
P case Adjustment Event.BLOCK.DECREMENT:
System.out.pri nt(“SCROLL-PACE „DOWN");
Q break;
case AdjustmentEvent.BLOCK-INCREMENT:
R System.out.print(“SCROl L-PACE_UP”);
break;
S }
System.out.printC’ value (“ + evt .getValueO + “)");
T System.out.printing adjustable (“ evt.getAdjustable() +
}
U
public void textValueChanged(TextFvent evt) {
V System.out.print(evt.getSourceQ .getClassO + “ ");
System.out.p ri ntln(“TEXT.VAL UE-CHANCED");
W }
}
X
class WindowEventHandler implements Windowlistener {
Y public void windowDeiconified(WindowEvent evt) {
System.out.print(evt.getSourceQ .getClassO + “ “);
Z System.out.pri nt(“WINDOW-DFICONIFY");
System.out.println(“ window (“ * evt.getWindowO + “)"):
}
public void windowClosing(WindowEvent evt) {
System, out .print (evt .getSourceO .getClassO + “ “);
Sy stem, out .pri nt("WINDOW_DESTROY") ;
System.out.print 1n(“ window (" + evt.getWindow() + “)");
}
public void windowClosed(WindowEvent evt) {
System.out.print(evt .getSourceO .getClassO * " ") ;
System.out.print(“WINDOW..CLOSED") ;
System.out.println(” window (“ + evt .getW’indow() + ")”);
}
public void windowActivated(WindowEvent evt) {
System.out. print(evt.getSourceO .getClassO + " “);
System.out.pri nt C‘WINDOW_FXPOSE”);
System.out.println(" window (“ 4 evt.getWindow() t “)”);
}
public void windowDeactivated(WindowEvent evt) {
System.out.print(evt.getSourceO .getClassO + “ “) ;
System.out.print("WINDOW-DEACTIVATED");
System.out. printing window (" 4- evt.getWindow() + “)");
}
public void windowIconified(WindowFvent evt) {
System.out.print(evt. getSourceO .getClassO + “ “);
System.out.pri nt(“WlNDOW_ICONIFY");
System.out.println(" window (“ * evt.getWindowO * ")”);
}
public void windowOpened(WindowEvent evt) {
System.out.print(evt.getSourceO .getClassO + “ “) ;
System.out.print("WINDOW OPENED”);
System.out.println(“ window (" 4- evt.getWindow() + ”)");
}
}
class ComponentEventHandler implements Component!, istener {
public void componentMoved(ComponentFvent evt) {
System.out.print(evt.getSourceO .getClassO > “ “);
Sys tern.out.p ri nt(“COMPONENI.MOVED”);
System.out.println(" component(“ + evt .getComponentO + ")”);
}
public void componentResized(ComponentEvent evt) {
System.out.print(evt.getSourceO .getClassO + “ H) :
System.out.print(“C0MR0NENT_REST7FD’') ;
System.out.println(" components + evt.getComponentO + “)");
}
public void componentShown(ComponentEvent evt) {
System,out.print(evt.getSourceO .getClassO + “ “);
Systern.out.printC‘COMPONENT_SHOWN”);
System,out.println(" components 4 evt.getComponentO * ")”);
}
public void componentHidden(ComponentEvent evt) {
System.out.print(evt.getSourceO .getClassO + " ") ;
System.out.print(“COMPONENT_HIDOFN");
System.out.printing component(" + evt .getComponentO * ")");
}
class ContainerEventHandler implements ContainerListener {
public void componentAdded(ContainerFvent evt) {
System.out.print(evt.getSourceO .getClass() 4 “ “);
System.out.pri nt("CONTAINER_ADDFD");
System.out.print In(“ container(“+evt.getContainer()+") child(" +
evt.getChild() +")");
Event
java.awt
}
public void componentRemoved(ContainerEvent evt) {
System.out .pri nt(evt.getSourceO .getClass() 4 “ “);
System.out .print(“CONTAINER_RtMOVED'’);
System»out.pri ntln(“ contai ner(‘*+evt.getContai ner()*”) child(
evt. getChi 1 d() -►’’)”):
}
}
class FocusEventHandler implements FocusListener {
public void focusGained(FocusEvent evt) {
System.out .print(evt .getSourceO .getClassO + “ “) ;
System.out .print(“FOCUS_GAINED") ;
System.out.println(evt.isTemporary() ? “ temporary." ; “.’’);
}
public void focusLost(FocusEvent evt) {
System.out.print(evt.getSourceO.getClass() 4- “ ;
System.out.pri nt(“FOCUS_LOST”);
System.out. pri ntln(evt. i slemporaryO ? “ temporary." : ".");
1
}
class KeyEventHandler implements KeyListener {
public void keyPressed(KeyEvent evt) {
System.out.print(evt .getSourceO ,getClass() 4 “ “);
if (evt. i sActionKeyO) {
System.out.pri nt(“Kt Y_ACTION");
} else {
System.out.pri nt("KFY_PRESS");
}
System.out.print(“ k(“4-(char)evt .getKeyCode()+’’) m(“);
System.out.pri ntln(
KeyEvent.getKeyModi fiersText(evt.getModi fiers())*")");
}
public void keyReleased(KeyEvent evt) {
System.out. print(evt .getSourceO .getClassO 4- “ “) ;
if (evt.i sActionKeyO) {
System.out.print(“KLY_ACTION .RELEASE");
} else {
System, out .pri nt (,lKEY_RELEASE;
}
System.out.print(“ k(“+(char)evt.getKeyCode()4-") m("):
System.out.pri nt In(
KeyEvent.getKeyModifiersText(evt.getModifiers())+")”):
}
public void keyTyped(KeyEvent evt) {
System.out. print(evt.getSourceO ,getClass() + “ ");
System.out.pri nt(“KEY-TYPED");
System.out.print(“ k(“-(char)evt.getKeyCode() + ’’) m(“);
System.out.pri ntln(
KeyEvent.getKeyModifiersText(evt.get Modifiers())-")");
}
}
static public void main(String[] args) {
new Mai nil();
}
}
550
AV IIUr\_r.V|-.IM
class MyCanvas extends Canvas {
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetrics();
g.drawStri ng(“Canvas”,
(getSizeO .width - fm. st ringWidth(“Canvas"))/2 ,
(getSizeO.height-fm.getAscent())/2);
ACTION-EVENT
DEPRECATED
PURPOSE
Replaced by ActionEvent.ACTION-PERFORMED,
SYNTAX
public static final int ACTION .EVENT
DEPRECATION
Replace the usage of this deprecated constant, as in
Event evt;
switch(evt.id) {
case Event.ACTION_FVENT:
either by using ActionListener.actionPerformedO or
subtypes as follows:
AWTEvent evt;
if (evt instanceof ActionEvent) {
if (evt.getIDO -- ActionEvent .ACTION. PERFORMED) {
iy using event
ALT_MASK
DEPRECATED
PURPOSE
Replaced by InputEvent,ALT_MASK.
SYNTAX
public static final int ALT_MASK
deprecation
Replace the usage of this deprecated constant, as in
public static boolean isAltDown(Event evt) {
return (evt.modifiers & Event.ALT_MASK) != 0;
1
with
public static boolean isAltDown(InputEvent evt) {
return (evt.getModifiers() & InputEvent-ALT_MASK);
}
arg
DEPRECATED
}
PURPOSE
syntax
Replaced by event-specific fields and methods,
public Object arg
java.awt
Event
clickCount
I
Cl
[I
I
J
К
I,
M
N
О
P
Q
R
S
T
i;
v
w
x
Y
z
deprecation Instead of using the arg field to represent an argument to be passed along with
the event, the Java 1.1 event model has a more flexible way of passing argu-
ments with an event. Each event subclass defines the properties relevant for an
event type to be passed along with that event. For example, an action event has
an action command associated with it that takes the place of the arg field for
events of type ACTION.FVENT. See individual event subclasses for details.
Replace usage of this deprecated field, as in
Fvent evt;
if (evt.target instanceof Button) {
String cmd = (String)evt.arg;
with
AW1Event evt;
if (evt.getSourceO instanceof Button) {
String cmd - ((ActionEvent)evt).getActionCommandQ;
clickCount
[DEPRECATED
purpose Replaced by MouseEvent. getC 1 i ckCount ().
syntax public int clickCount
deprecation Replace the usage of this deprecated field, as in
Event evt;
if (evt.clickCount > 1) ...
with
MouseEvent evt;
if (evt.getClickCount() >1) ...
COntrolDOWn() DEPRECATED
PLRPost: Replaced by InputEvent.isControlDownO.
syntax public boolean control Down()
description In Java 1.1, MouseEvent and KeyEvent are subclasses of InputEvent.
Replace the usage of this deprecated method, as in
Event evt;
if (evt.control Down()) ...
with
MouseEvent evt; // or KeyEvent
if (evt. isControlDownO) ...
552
CTRL MASK DEPRECATED
PURPOSE Replaced by InputEvent.CTRL_MASK.
SYNTAX public static final int CTRL.MASK
deprecation Replace the usage of this deprecated method, as in public static boolean isControlDown(Event evt) { return (evt.modifiers & Event.CTRL_MASK) != 0; } with public static boolean isControlDown(InputEvent evt) { return (evt.getModifiers() & InputEvent.CTRL_MASK) != 0; }
DOWN DEPRECATED
PURPOSE Replaced by KeyEvent.VK.DOWN.
SYNTAX public static final int DOWN
DEPRECATION Replace the usage of this deprecated constant, as in Event evt; if (evt.key == Event.DOWN) ... with KeyEvent evt; if (evt.getKeyCodeO == KeyEvent.VK.DOWN) ...
END DEPRECATED
PURPOSE Replaced by KeyEvent. VK_END.
SYNTAX public static final int END
DEPRECATION Replace the usage of this deprecated constant, as in Event evt; if (evt.key == Event.ENO) ... with KeyEvent evt; if (evt.getKeyCodeO == KeyEvent.VK_END) ...
Event() DEPRECATED
purpose L'se the constructor for one of AWTEvent’s subclasses instead.
SYNTAX public Event(Object target, long when, int id, int x, int y, int key, int modifiers, Object arg)
Event
java.awl
evt
public Event(Object target, long when, int id, int x, int y, int key, int modifiers) public Lvent(Object target, int id, Object arg)
PARAMETERS
arg id key modi fiers target when The object to be associated with this event. The event type. The key that tired the event. Used b) ke\board related event t v pcs. The state of the modifier keys at the time of the event. I'he non nul 1 component that fired the event. The event's time stamp at the time of lhe event.
X The л-coordinate of the cursor at the time of the event.
У The y-coordinate of the cursor at the time of the event.
DE PRI CATION Event has been replaced by a class hierarchs of event subclasses rooted at AWTEvent. See the individual event subclasses for details on their constructors. For example, instead of creating an ACTION .EVENT event for a button as fol- lows: Event evt ~ new Lvent(button,Event.ACTION EVENT,but ton.getLabel()); use the subclass's constructor: ActionEvent evt - new ActionEvent(button, Ac ti onEvent.ACT 10N_PERF0RMED, button. getActionCommandO);
evt
DEPKECATED
PURPOSE Replaced by EventQueue.
STM AX public Event evt
Dt PR EC A HON In Java 1.0. this field is used when the event needs to be inserted into a linked list. In Java 1.1, events are chained together using EventQueue. See the postEventO, getNextEventQ, and peekEventQ in the EventQueue class for details. Replace the usage of this deprecated field, as in E'vent list; void queueFvent(Event event) { event.evt = list; list = event; } with EventQueue queue; AWTEvent evt; queue.postEvent(evt);
554
Fl DEPRECATED
purpose Replaced by KeyEvent.VK Fl.
syntax public static final int Fl
deprecation Replace the usage of this deprecated constant, as in
Fvent evt;
if (evt.key == Event.Fl) ...
with
KeyEvent evt;
if (evt.getKeyCodeO == KeyEvent.VK_F1) ...
F10 DEPRECATED
PUR POSt: Replaced by KeyEvent.VK_F10.
SYNTAX public static final int F10
DEPRECATION Replace the usage of this deprecated constant, as in Event evt; if (evt.key -= Event.F10) ... with KeyEvent evt; if (evt.getKeyCodeO KeyEvent.VK_T10) ...
DEPRECATED
purpose Replaced by KeyEvent.VK_F11.
syntax public static final int Fll
deprecation Replace the usage of this deprecated constant, as in
Event evt;
if (evt.key == Event.Fll) ...
with
Keytvent evt;
if (evt. getKeyCodeO == KeyFvent.VK_F11) ...
F12
purpose Replaced by KeyEvent .VK_F12.
Syntax public static final int F12
deprecation Replace the usage of this deprecated constant, as in
Event evt;
if (evt. key Event.F12) ...
DEPRECATED
java.awt
Event
кГ
with
KeyEvent evt;
if (evt.getKeyCodeO === KeyEvent.VK_F12) ...
Л
В
C
F2 DEPRECATED
F
G
H
I
J
К
L
M
N
О
P
Q
R
S
T
U
V
purpose Replaced by KeyEvent .VK_F2.
syntax public static final int F2
deprecation Replace the usage of this deprecated constant, as in
Event evt;
if (evt.key == Event.F2) ...
with
KeyEvent evt;
if (evt.getKeyCodeO == KeyEvent.VK_F2) ...
F3 DEPRECATED
purpose Replaced by KeyEvent. VK_F3.
syntax public static final int F3
deprecation Replace the usage of this deprecated constant, as in
Event evt;
if (evt.key == Event.F3) ...
with
KeyEvent evt;
if (evt.getKeyCodeO -= KeyEvent.VK_F3) ...
F4
DEPRECATED
W
X
Y
Z
purpose: Replaced by KeyEvent. VK_F4.
syntax public static final int F4
deprecation Replace the usage of this deprecated constant, as in
Event evt;
if (evt.key == Event.F4) ...
with
KeyEvent evt;
if (evt.getKeyCodeO == KeyEvent.VK_F4) ...
DEPRECATED
purpose: Replaced by KeyEvent. VK_F5.
556
SYNTAX public static final int Г5
DEPRIVATION Replace the usage of this deprecated constant, as in Event evt; if (evt.key -- Event.F5) ... with KeyEvent evt; if (evt.getKeyCodeO -= KeyEvent.VK_F5) ...
F6 DEPRECATED
PURPOSE Replaced by KeyEvent. VK. F6.
SYNTAX public static final int F6
deprecation Replace the usage of this deprecated constant, as in Fvent evt; if (evt.key == Event.Г6) ... with KeyEvent evt; if (evt.getKeyCodeO -= KeyEvent.VK_F6) ...
F7 DEPRECATED
PURPOSE Replaced by KeyEvent .VK_F7.
SYNTAX public static final int F7
DEPRECATION Replace the usage of this deprecated constant, as in Event evt; if (evt.key =.^ Event.F7) ... with KeyEvent evt; if (evt.getKeyCodeO == KeyEvent.VK_F7) ...
F8 DEPRECATED
PURPOSE Replaced by KeyEvent.VK_F8.
SYNTAX public static final int F8
DEPRECATION Replace the usage of this deprecated constant, as in Fvent evt; if (evt.key == Fvent.F8) ... with KeyEvent evt; if (evt.getKeyCodeO — KeyEvent.VK_F8) ...
java.awt
Event
но
F9
DEPRECATED
A
в
с:
D
PCRPOSi: Replaced by KeyEvent .VK Г9.
syntax public static final int F9
dbprfx ation Replace the usage of this deprecated constant, as in
Event evt;
if (evt.key == Event.F9) ...
with
KeyFvent evt;
if (evt .getKeyCodeQ —« KeyEvent.VK_F9) ...
F
G
H
1
J
к
L
M
N
О
P
Q
R
S
T
и
GOT.FOCUS DEPRECATED
pcrposi- Replaced by FocusEvent. FOCUS-GAINED.
syniax public static final int GOT.FOCUS
deprecation Replace the usage of this deprecated constant, as in
Event evt;
switch(evt.id) {
case Event.GOT—FOCUS:
case Event.LOST_FOCUS:
by using a FocusListener.focusGainedО or by using event subtypes as
follows:
AWTEvent evt;
if (evt instanceof FocusFvent) {
switch (evt.getlDQ) {
case FocusEvent.FOCUS_GAINED:
case FocusEvent.FOCUS.LOST:
HOME
DEPRECATED
w
X
Y
Z
purpose Replaced by KeyEvent. VK-HOME.
syntax public static final int HOME
deprecation Replace the usage of this deprecated constant, as in
Event evt;
if (evt.key == Event.HOME) ...
with
KeyEvent evt;
if (evt.getKeyCodeO == KeyEvent.VK.HOME) ...
558
jd DEPRECATED
purpose Replaced by AWTEvent. getTD().
SYNTAX public int id
DEPRECATION Replace the usage of this deprecated Пек!, as in Event evt; switch (evt.id) { with the usage of the appropriate event subclass, or AWTEvent.getID(). as follows: AWTEvent evt; switch (evt.getlDQ) {
key DEPRECATED
PURPOSE Replaced by KeyEvent.getKeyCodeO.
SYNTAX public int key
DEPRECATION Replace the usage of this deprecated field, as in Event evt; switch (evt.key) { case ‘a’: case ‘b’: with KeyEvent evt; switch (evt.getKeyCodeO) { case KeyEvent .VK_^A: case KeyEvent.VK B:
KEY ACTION deprecated
PURPOSE. Replaced by KeyEvent. KEY-PRESSED.
SYNTAX public static final int KEY-ACTION
deprlcai ion In the Java 1.1 event model, all key presses fire a KEY-PRESSFD event, regard- less of whether the key is an action key. You use isActionKeyQ on the key event to determine whether the key pressed was an action key. Replace the usage of this deprecated constant, as in Event evt; switch (evt.id) { case Event.KEY-ACTION: ... case Event.KEY_ACTION_RELEASE: ...
java.awt
Event
m:y_actio>Frei .ease
z\
в
c
D
by using KeyLi stener. keyPressedO with KeyEvent.isActionKeyO or
by using event subtypes as follows:
KeyFvent evt;
switch (evt.getTDQ) {
case KFY PRESSED:
if (evt. isActionKeyO) ...
case KEY.RELEASED:
if (evt. i sAct ionKeyO ) ...
F
G
H
J
J
К
I.
M
N
О
P
Q
R
S
T
и
KEY ACTION RELEASE deprec med
purpose Replaced by KeyEvent. KEY-RELEASED.
syntax public static final int KEY_ACI1ON_RLLEASF
deprecation In the Java 1.1 event model, all key releases fire a KEY.RtLEASED event,
regardless of whether the key is an action key. Use i sActionKeyO on the key
event to determine whether the key released was an action key.
Replace the usage oi this deprecated constant by using KeyLi stener. keyRe-
1 eased О with KeyEvent. i sActionKeyO or by using event subtypes, as
shown in KEY-ACTION.
KEY -PRESS
DEPRECATED
w
X
Y
Z
pi rposf Replaced by KeyEvent. KEY-PRESSED.
syntax public static final int KEY PRESS
deprecation In the Java 1.1 event model all key presses fire a KEY-PRESSED event, regard-
less of whether the key is an action key. You use i sActionKeyO on the key
event to determine whether the key pressed was an action key.
Replace the usage of this deprecated constant, as in
Event evt;
switch (evt.id) {
case Event.KEY_PRESS: ...
case Event.KEY_RELEASF: ...
by using KeyListener.keyPressedO with KeyEvent.isActionKeyO or
by using event subtypes as follows:
KeyEvent evt;
switch (evt.getlDQ) {
case KEY PRESSED:
if ('evt.isActionKeyO) ...
case KtY_RELLASED:
if (’evt.isActionKeyO) ...
560
KEY_RELEASE DEPRECATED
PURPOSED Replaced by KeyEvent.KEY_RELEASED.
SYNTAX public static final int KFY_ACTION_RF1 FASL
DEPRECATION In the Java 1.1 event model, all key releases fire a KEY_RELEASED event, regardless of whether the key is an action key. You use isActionKeyO on the key event to determine whether the key released was an action key. Replace the usage of this deprecated constant by using KeyLi stener, keyRe- leasedO with KeyEvent.isActionKeyO or by using event subtypes, as shown in KEY_PRESS.
LEFT DEPRECATED
purpose; Replaced by KeyEvent .VK_LEFT,
SYNTAX public static final int LEFT
DEPRECATION Replace the usage of this deprecated constant, as in Event evt; if (evt.key -- Event.LEFT) ... with KeyEvent evt; if (evt.getKeyCodeO == KeyEvent .VK_L FFT) ...
LIST DESELECT DEPRECATED
PURPOSE Replaced by ItemEvent .DESELECT.
SYNTAX public static final int 1TST_DFSFLECT
DEPRECATION The Java l.l event model contains a generic event subclass ItemEvent for representing selection/deselection of items in a component. Checkbox. CheckboxMenuItem. Choice, and Li st are .AWTclasses that fire ItemEvent. Replace the usage of this deprecated constant, as in Event evt; switch (evt.id) { case Event.LIST_DESELECT: ... case Event.LIST_SELECT: ... by using ItemListener.itemStateChanged() and using ItemEvent.get- StateChangeQ as follows: public void itemStateChanged(IterrEvent evt) { switch (evt. getStateChangeO) { case ItemEvent.SELECT: ... case ItemEvent.DFSFLECT: ... T
Event
java.awt
LIST-SELECT
LIST-SELECT
DEPRECATED
м rpose Replaced by ItemEvent.DESELECT.
syntax public static final int LIST-SELECT
DEPRECATION See LIST.DESELECT.
LOAD_FILE
DEPRECATED
Pl RPOSE Not used.
SYNTAX public static final int LOAD-FILE
DESCRIPTION This constant was not used in Java 1.0. There is no corresponding constant for it in Java 1.1.
LOST FOCUS
DEPRECATED
F’l RPOSF Replaced by FocusEvent. FOCUS_LOST.
S Y N 1 A X public static final int IOST_FOCUS
DI:PREC A1FON See GOT. FOCUS.
META_MASK DEPRECATED
PURPOSE Replaced by InputEvent.METAJ4ASK.
SYNTAX public static final int META-MASK
DEPRECATION Replace the usage of this deprecated constant, as in public static boolean isMetaDown(Event evt) { return (evt.modifiers & Event.META_MASK) 0; } with public static boolean isMetaDown(InputEvent evt) { return (evt.getModifiers() & InputEvent,MFTA_MASK); }
DEPRECATED
metaDown()
purpose Replaced by InputEvent. i sMetaDownQ,
syntax public boolean metaDown()
562
DESCRIPTION In Java LI. MouseEvent and KeyEvent are subclasses of InputEvent. Replace the usage of this deprecated method, as in Event evt; if (evt.metaDownO) ... with MouseEvent evt; // or KeyEvent if (evt. i sMetaDownO) ...
modifiers DEPRECATED
PURPOSE Replaced by InputEvent.getModifiersO.
SYNTAX public int modifiers
DESCRIPTION In Java LL MouseEvent and KeyFvent are subclasses of InputEvent. Replace the usage of this deprecated Geld, as in Event evt; if ((evt.modifiers & Event.META_MASK) !- 0) ... with MouseEvent evt; // or KeyEvent if ((evt.getModifiers() & InputEvent .META MASK) ...
MOUSE IX)WN DEPRECATED
PURPOSE Replaced by MouseEvent. MOUSE^PRESSED.
SYNTAX public static final int MOUSE-DOWN
DEPRECATION Replace the usage of this deprecated constant, as in Event evt; switch(evt.id) { case Event.MOUSE DOWN: case Event.MOUSE_UP: case Fvent.MOUSE_FNTER: case Event.MOUSE EXIT: by using MouseLi stener .mousePressedf) or by using event subtypes as follows: AWTEvent evt; if (evt instanceof MouseEvent) { switch (evt.getIDO) { case MouseEvent.MOUSE-PRESSED: case MouseEvent.MOUSE RFlEASED: case MouseEvent.MOUSE ENTERED: case MouseEvent.MOUSF_EXITED:
Event
java.awt
MOUSE DRAG DRAG DEPRECATED
MOUSE.
A В C D F G H 1 J К L M PURPOSE SYNT/XX DEPRECATION MOUSE. Replaced by MouseEvent.MOUSE„DRAGGED. public static final int MOUSE„DRAG Replace the usage of this deprecated constant, as in Event evt; switch(evt.id) { case Fvent.MOUSF.DRAC: case Event.MOUSE-MOVE: by using MouseMotionLi stener .mouseDraggedO or by using event sub- types as follows: AWTEvent evt; if (evt instanceof MouseEvent) { switch (evt.getID()) { case MouseEvent.MOUSE DRAGGED: case MouseEvent.MOUSE_MOVED: .ENTER DEPREt .1 TED
PURPOSE Replaced by MouseEvent,MOUSE_ENTFRFD.
X SY N LAX public static final int MOUSE.ENTER
0 DEPRECATION Replace the usage of this deprecated constant by using a MouseLis-
P Q R MOUSE tener.mouseEnteredO or by using event subtypes, as shown in MOUSE-DOWN. EXIT DEPRE( A TED
S T purpose: Replaced by MouseEvent.MOUSE-EXITED.
и SYNTAX public static final int MOUSE-EXIT
V DEPRECAI ION Replace the usage of this deprecated constant by using a MouseLis-
w X MOUSE_ tener .mouseExi tedQ or by using event subtypes, as shown in MOUSE-DOWN. MOVE DEPRECA TED
Y z PURPOSE Replaced by MouseEvent.MOUSE_MOVED.
SYNTAX public static final int MOUSF_MOVF
564
DEPRECATION Replace the usage of this deprecated constant by using a MouseLis- tener.mouseMovedO or by using event subtypes, as shown in MOUSE-DRAG.
MOUSE-UP DEPRECATED
PURPOSE Replaced by MouseEvent.MOUSE-RELEASED.
syntax public static final int MOUSE.UP
DEPRECATION Replace the usage of this deprecated constant by using a Mouselis- tener .mouseReleasedO or by using event subtypes, as shown in MOUSE-DOWN.
paramString() deprecated
PURPOSE Replaced by AWTEvent.paramString().
SYNTAX protected String paramString()
DEPRECATION The Event class is deprecated. Use AWTEvent instead.
PGDN DEPRECATED
PURPOSE Replaced by KFYEvent. VK_.PACE_DOWN.
SYNTAX public static final int PGDN
DEPRECATION Replace the usage of this deprecated constant, as in Event evt; if (evt.key =- Fvent.PGDN) ... with KeyFvent evt; if (evt .getKeyCodeO — KeyEvent_VK. PAGF_DOWN) ...
PGUP DEPRECATED
PURPOSE Replaced by KeyEvent .VK-PAGE_UP.
SYNTAX public static final int PGUP
deprecation Replace the usage of this deprecated constant, as in Event, evt; if (evt.key == Event.PGUP) ... with KeyEvent evt; if (evt. getKeyCodeO ==> KeyEvent.VK„PAGF-UP) ...
java.awt
Event
RIGHT
RIGHT DEPRECATED pi rposf Replaced by KeyEvent. VK_RICHT.
A syntax public static final int RIGHT deprecation Replace the usage of this deprecated constant, as in
1} C Event evt; if (evt.key == Event.RIGHT) ... with
D KeyEvent evt; if (evt.getKeyCodeO KeyEvent-VK.RIGHT) ...
F SAVE_FILE DEPRECATED
G
H purpose Not used.
I syntax public static final int SAVE_FILE
J descript ion This constant was not used in Java 1.0. There is no corresponding constant for it in Java I.L
К
L SCROLL.ABSOLUTE deprecated
M .. .
N purpose. Replaced by AdjustmentEvent.TRACK.
О syntax public static final int SCROLL-ABSOLUTE
P deprecation Replace the usage of this deprecated constant, as in Fvent evt;
Q switch(evt.id) {
R S case Fvent.SCROLL-ABSOLUTE: case Event.SCROLL_LINE_DOWN: case Event.SCROLL_LINE_UP:
T case Event.SCROLL_PAGE_DOWN:
и v case FvebtrSCROLL_PAGE_UP:
V W by using Adjustment!-!stener.adjustmentValueChangedO and adjust- ment types as follows:
X public void adjustmentValueChanged(AdjustmentEvent evt) { switch (evt.getAdjustmentlype) {
Y case AdjustmentEvent-TRACK:
Z case AdjustmentEvent.UNIT-INCREMENT: case AdjustmentEvent-UNIT-DECREMENT:
566
case AdjustmentEvent.BL OCK_INCREMENT:
case AdjustmentEvent.BLOCK-DECREMENT:
SCROLL,_LINE_DOWN
purpose Replaced by AdjustmentEvent.UNIT_INCREMENT.
syntax public static final int SCROLL_LINL DOWN
deprecation See SCRQLL_ABSOLUTE.
DEPRECATED
SCROLL LINE UP
purpose Replaced by AdjustmentEvent ,UNIT_DECRFMENT.
SYNTAX public static final int SCROLL .LTNEJJP
deprecation See SCROLL_ABSOLUTE.
SCROLL PAGE_DOWN
purpose Replaced by AdjustmentEvent. BLOCK_DECREMENT.
syntax public static final int SCROLL PAGE_DOWN
DEPRECATION See SCROLL_ABSOLl)TE.
DEPRECATED
DEPRECATED
SCROLL PAGE_LP
purpose Replaced by Adj ustmentEvent. BLOCK_DECREMFNT.
syntax public Static final int SCROLL_PAGE UP
depri CA I к )N See SCROLL_ABSOLUTE.
DEPRECATED
SHIFT_MASK
purpose Replaced by InputEvent. SHI FT .MASK.
syntax public static final int SHIF1_MASK
DLPRHReplace the usage ot this deprecated method, as in
public static boolean isShiftDown(Event evt) {
DEPRECATED
java.awt
Event
shiftDowni)
return (evt.modifiers A Event.SHIFT MASK) !- 0; } with public static boolean isShiftDowndnputEvent evt) { return (evt .getModifiersO & InputEvent. SHIRT..MASK) !- 0;
A В C } shiftDownC) deprecated
D F pcrpose Replaced by InputEvent.isShiftDown(). syntax public boolean shiftDownC) descrihion In Jaxa 1.1. MouseEvent and KeyEvent are subclasses of InputEvent.
G Replace the usage of this deprecated method, as in Event evt;
H if (evt.shiftDown())
J with Mouselvent evt; // or KeyFvent
J if (evt.isShiftDown()) ...
К 1. target DEPRECA IED
M pi reuse Replaced by AWTEvent.getSource().
N syntax public Object target
0 deprecation Replace the usage of this deprecated field, as in
P Event evt; if (evt.target instanceof Button) ...
Q with AWTEvent evt;
R if (evt.getSourceQ instanceof Button) ...
s T t: toStringO DEPRECATED purpose Replaced by AWTEvent.toString().
V syntax public String toStringO
w X deprecation Hie usage of the Event class is deprecated. Use AWTEvent instead.
Y translate) deprecated
7. perpose Replaced by MouseEvent.translatePoint(). syntax public void translate(int x, int y)
568
PARAMETERS X The value to add to the event’s x-coordinate.
У The value to add to the event’s y-coordinate.
DEPRECATION In Java 1.0, the AWT adjusts the event’s coordinates so that they are relative to the component that is receiving the event. In Java 1.1, (he coordinates are not translated automatically and are, by default, relative to the bounds of the com- ponent that fired the event. See the MouseMotionLi stener class example for the usage of MouseEvent.translatePoint(). Replace the usage of this deprecated method, as in Event evt; Component comp; evt. translate (comp. getBoundsO x, comp. getBoundsO. y); with MouseEvent evt; Component comp; evt.translatePoint(comp,getBoundsO-x, comp.getBoundsO-y);
UP DEPRECATED
PURPOSE Replaced by KeyEvent .VICUP.
SYNTAX public static final int UP
DEPRECATION Replace the usage of this deprecated constant, as in Event evt; if (evt.key «= Event.UP) ... with KeyEvent evt; if (evt.getKeyCodeO — KeyEvent.VKJJP) ...
when DEPRECATED
PURPOSE Replaced by InputEvent .getWhenQ.
SYNTAX public long when
deprecation Replace the usage of this deprecated field, as in Event evt; System.out.println(“time: “ + evt.when); with KeyEvent evt; // or MouseEvent System.out.println( ‘time; “ + evt .getWhenO) ;
Event
WIN DOW_DEICON 11; Y
WINDOW-DEICONIFY
jaxa.au l
DEPRECATED
Pl RPOM-
SY \TA.X
DEPREt Al l()X
Replaced by Wi ndowEvent.WINDOW_DEICONTFIED.
public static final int WINDOW.DETCONIFY
Replace the usage of this deprecated constant, as in
Event evt;
switch(evt.id) {
case Fvent.WTNDOW_DE1CONIFY:
case Event.WINDOW ICOMFY:
case Event.WINDOW DESTROY:
case Event.WINDOW_EXPOSE:
b> using WindowListener.windowDeiconified() Dr by using event sub-
types as follows:
AWTEvent evt;
if (evt instanceof MouseEvent) {
switch (evt .qetIDO) {
case Wi ndowEvent. WINDOW_DEJCOMFTFD:
case Wi ndowEvent .WINDOW ICONIHFD:
case WindowFvent.WINDOW CIOSING:
case Window-Fvent.WINDOW_ACTIVATFD:
()
WINDOW.DESTROY DEPRECATED
P -- _—-------- --- ------- -------------------------- ------
q pi rpose Replaced by Wi ndowEvent.WINDOW-CLOSING.
К syntax public static final int WINDOW_DESTROY
S deprecation Replace the usage of this deprecated constant by using a Window.window-
Closi ng() or by using event subtypes, as shown in WINDOW_.DE I CON IFY.
J WINDOW_EXPOSE DEPRECATED
\ ____________, _ ____________ ________ ___, _____ ___ _____ „ _______
W pi RPOM-. Replaced by Wi ndowEvent .WINDOW-ACTIVATED.
X syntax public static final int WINDOW..EXPOSE
Y deprecation Replace the usage of this deprecated constant b\ using a Wi ndow.wi ndowAc-
y ti vatedf) or by using event subtypes, as shown in WINDOW_DFICONIFY,
570
wjrsuow HUMPY
WINDOW-ICONIFY DEPRECATED
PURPOSE Replaced by WindowEvent.WINDOW-ICONIFIED.
SYNTAX public static final int WINDOW ICONIFY
DEPRECATION Replace the usage of this deprecated constant by using a Window.window- lconi fi ed() or by using event subtypes, us shown in WINDOW_DEICONTFY.
WINDOW-MOVED DEPRECATED
PURPOSE Replaced by ComponentEvent .COMPONFNT..MOVED,
SYNTAX public static final int W1NDOW_MOVFD
DEPRECATION In Java 1.1. any component can fire “move*' events, not just windows. Replace the usage of this deprecated constant, as in Event evt; switch(evt.id) { case Event.WINDOW MOVED: by using Component! i stener.componentMovedO or by using event sub- types as follows: AWTEvent evt; if (evt instanceof ComponentEvent) { switch (evt.getIDO) { case ComponentEvent.COMPONE4T_VOVED:
X DEPRECATED
PURPOSE Replaced by MouseEvent .getXQ.
SYNTAX public int x
deprecation In Java 1.0, the AWT adjusts the event's coordinates so that they are relative io the component that is receiving the event. In Java LI. the coordinates are. by default, relative to the bounds of the component that fired the event. This dif- ference means that other calculations might be required when lhe usage of this deprecated field is replaced, as in Event evt; int x - evt.x * offset; with MouseEvent evt: int x - evt.getXO ♦ offset;
Event
java.awt
У
У DEPRECATED
purpose Replaced by MouseEvent.getY().
syntax public int у
deprecation In Java LO, the AWT adjusts the event’s coordinates so that they are relative to
the component that is receiving the event. In Java 1.1, the coordinates are, by
default, relative to the bounds of the component that fired the event. This dif-
ference means other calculations might be required when the usage of this dep-
recated field is replaced, as in
Event evt;
int у = evt.у + offset;
with
MouseEvent evt;
int у - evt.getYO + offset;
572
EventQueue
" J __
Syntax
public class EventQueue
Description
When an event source fires an event, that source may not be the one that created the event: the
event may have been created by some other object. In particular, for components that have
peers, the event is actually created by the peer and then delivered to the component. When the
event source is not the creator of the event, the event should be delivered to the event source
via an event queue. The event queue is a first-in/first-out queue. When an event is added
(posted) to the event queue, it is delivered to the event source only when the event reaches the
front of the queue.
Each queue has a separate event-dispatching thread that sequentially removes a queue
item from the head of the queue and dispatches it to its event source. If the event source is a
Component or MenuComponent, its di spatchEventО method is invoked to dispatch the
event. Otherwise, if the event is an ActiveEvent, the event's dispatchO method is called
(see ActiveEvent). After the event-dispatching thread has completed dispatching the event to
its event source and any registered listeners, it removes the next event from the event queue
and performs (he same process on it. If there are no more events on the event queue, the event-
dispatching thread blocks until one is available.
The event queue enables two features not possible with direct delivery of events (Le.. by
calling di spatchEventO directly):
1. Il allows for asynchronous delivery of events. As soon as the peer posts the event, it is
free to do other things. If the peer delivered the event directly to the event source, it
would be blocked while (he event source and all of its listeners completed the processing
of the event.
2. It serializes the events. For example, if you click button A and then button button A
will gel the click event before button
System Event Queue
The AWT system uses a single system event queue for posting events (see Toolkit.qetSys-
temEventQueueO). The system event queue can include not only events generated by the
AWT, but also system events that are added programmatically, if allowed by the security man
ager that is installed.
java.awt
EventQueue
EvcntQueueO
MEMBER SUMMARY
Constructor EventQueueO Constructs a new instance of EventQueue.
1 Event Queue Methods I getNextEventO | peekFvent!) postEvent() Removes the next event from this queue and returns it. Retrieves an event from this queue without removing it. Adds an event to the end of this queue.
F
G
H
1
J
К
L
M
N
()
P
Q
R
S
T
See Also
AWTEvent, Component.dispatchEventO » java.awt.peer.ActiveEvent,
java.1ang.Securi tyManager.checkAwtEventQueueAccessO »
MenuComponent.di spatchEventO, Tool kit.getSystemEventQueue().
EventQueue!)
purpose Constructs a new instance of EventQueue.
syniax public EventQueue!)
description This method creates a new event queue and creates a new event-dispatching
thread responsible for dispatching events that are added to the new event
queue.
getNextEventO
PCRPost: Removes the next event from this queue and returns it.
syntax public synchronized AWTEvent getNextEventO throws
InterruptedException
df.scripiion If the event queue is empty, this method blocks until an event is available. This
method is usually invoked only by the event-dispatching thread.
returns The next event from this queue.
INCEPTIONS
InterruptedException
If another thread has interrupted this thread.
see also peekEventQ, postEvent().
574
. yeekEventQ
PURPOSE Retrieves an event from this queue without removing it.
syntax public synchronized AWTEvent peekEventQ public synchronized AWTEvent peekEvent(int id)
DESCRIPTION If an event id id is specified, this method searches from (he beginning of the queue to find the first occurrence of an event that has event id id. If no such event is found, this method returns nul 1. If i d has not been specified, the first event in the queue is returned. If the queue is empty, nul 1 is returned.
PARAMETERS id The event id of the event to retrieve.
returns The first event that has event id id. or the first event if id has not been speci- fied. null if the queue is empty or id is not found.
SEE ALSO getNextEventQ.
postEvent()
PURPOSE Adds an event to the end of this queue.
SYNTAX public synchronized void postEvent(AWTEvent evt)
DESCRIPTION This event will eventually be dispatched by the event-dispatching thread asso- ciated with (his event queue when it reaches the front of the queue.
PARAMETERS evt The event to add.
SEE ALSO getNextEventQ.
EXAMPLE See the AWTEvent class example.
java, beans
EventSetDescriptor
A
В
C
L>
F
Ci
н Syntax
г public class EventSetDescriptor extends FeatureDescriptor
Description
К For each event that a bean can fire, there is an associated event set. The event set refers to the
L supporting methods and interfaces of that ex ent and basically consists of three things:
M I I be listener methods, a group of callback methods that are associated with an ex ent. In
particular, when an object fires the event, one of the listener methods will be called. All
the listener methods must take a single parameter: the Class object of the event itself.
° 2. The listener interface, an interface (or possibly a class) that defines all of the listener
p methods. A listener that wants to listen for the ex ent must implement the listener inter-
face.
3. The two listener suppart methods, w hich are proxided by the bean and are used by listen-
R ers to register for the event. The listener support methods take a single parameter: an
s object of the same ty pe as the listener interface.
.p For example, the event set of the focus event (see FocusEvent) comprises the following:
У I. Two listener methods: focusGained() and focusLostO
2. A listener interface: FocusLi stener
v 3. Two listener support methods: addFocusLi stener О and removeFocusLi stener()
w An event set descriptor contains information about an event set. The event set descriptor also
X contains other attributes about the event set. such as its localized name and whether it is a uni-
cast event. There is one event set descriptor for each event (hat a bean can fire. The list of
event set descriptors can be retrieved through (he introspector by calling Introspector .get-
Z BeanlnfoO .getEventSetDescriptorsO.
For Bean Editors Only
The information contained in an event set descriptor
is meant for programs such as bean editors (programs
that help connect together beans into an application)
and is not used by the bean itself. These and other
descriptors essentially help a bean editor to construct
a meaningful user interface for editing the bean.
When the bean is actually running in an application»
the event set descriptors are not used.
Implicit and Explicit Event Set Descriptors
The introspector first looks for explicit event set
descriptors in the bean's bean-info, if present (see
Beaninfo). If explicit event set descriptors are not
found, the introspector creates implicit event set
descriptors with some default values for each event
set attribute. See Figure 127. Table 10 shows the
attributes of event set descriptors and what they con-
tain. Also shown are the default values for implicit
event set descriptors.
Introspector
Explicit
Descriptors
Implicit
Descriptors
Bean
0
Bean Descriptor
Event Set Descriptors
Method Descriptors
Parameter Descriptors
Property Descriptors
Bean-Info
FIGURE 127: Event Set Descriptor.
Attribute Contents Implicit Default Value
Source The Class object that fires the event. The Class object that fires the event.
Listener type The Class object of the listener interface. The Class object of the lis- tener interface.
Add listener The Method object of the add listener The Method object of the
method support method. add listener support method.
Remove listener Fhe Method object of the remove lis- I'hc Method object of the
method tener support method. remove listener support method.
Listenermethods The Method objects for the collection of callback methods. The Method objects for the collection of callback methods.
In default set true if the event sei is in the default set. true.
Unicast true if the event set is unicast. false? Continued
TABLE 10: Event Set Descriptor Attributes.
EventSetDeseriptor
java.beans
A
В
Attribute Contents Implicit Default Value
Name The event set’s non loculi zed name. The event set’s nonlocalized name.
Display name The event set's localized name The event set's localized name.
Short description A localized description of the event set. ’Hie event set's nonlocalized name.
Expert true if the event set is considered tor use by experts only. false.
Hidden true if the event set is meant to be false.
used by a tool: fal se if it is meant
to be use by a person.
F
G
H
I
J
К
L
M
N
О
P
Q
R
S
T
E
V
TABLE 10: Event Set Descriptor Attributes.
a. It The mirospector discovers that an event set's add listener meihcxl throus
looManyl i stenersFxception. unicast is set ю true.
w
X
Y
Z
Conventions Regarding the Listener Support Method Signature
The bean specification defines conventions for the signature of a listener support method.
These conventions sene two purposes:
1. They make the bean's API easier for a programmer to read. That is. it's easy to see v\ hich
methods arc listener support methods and which are not.
2. They make it possible for the introspector to discover a bean's event sets and create
implicit event set descriptors. In other words, the introspector looks at the entire list of a
bean's public methods. When a method is found that matches the listener support method
signature convention, the introspector assumes that it must be a listener support method.
The names of lhe listener support methods are based on the name of the listener interface. For
example, if the name of the listener interface (without the package name) is EventNameLis-
tener. then rhe add listener method signature convention.
public void addEventNamel istener(EventA/ameListener 1)
where EventNa/neListener must be a subclass of java.util.EventListener and 1 is any
arbitrary parameter name. The remove listener method signature convention is
public void remove F ven r/VameListener (Even t/VameListener 1)
For example, if the listener interface name is FocusListener. the listener support methods
w ould be
public void addFocusListener(FocusListener listener)
public void removeFocustistener(FocusListener listener)
578
Unicast Event Sets
Most event sets are multicast. This means that an object firing a multicast event will support
many listeners. However, some events are unicast, that is, an object firing a unicast event will
support only one listener. An event set is unicast if its add listener method throws
java.util.TooManyListenersException. For example, if the event name is ’ jump", the
signature of the add listener method will be
public void addlumpListenerOumpListener listener)
throws TooManyListenersException
ДЫСВЕИ SUMMARY "
Constructor
EventSetDescri ptorQ Constructs an EventSetDescriptor instance. I
Listener Methods
getAddLi stenerMethodO
getListenerMethodDescriptorsO
getLi stenerMethodsQ
getLi stene rType ()
getRemoveLi stenerMethodO
Default Set Methods
i slnDefaul tEventSetO
setlnDefaultFventSetО
Unicast Methods
isUnicastO
setUnicastO
Retrieves the event set’s add listener support method.
Retrieves the method descriptors for the event >et\
listener methods.
Retrieves the event set's listener methods.
Retrieves the event set’s listener interface.
Retrieves the event set's remove listener support
method.
Retrieves the state of the event set’s "default set”
attribute.
Sets the event set's "default set” attribute.
Determines if the event set is unicast.
Specifies whether the event set is unicast.
______________________________________________________j
See Ako
Beaninfo.getEventSetDescri ptors О, java.awt.AWT Event, java.1ang.СI ass,
java.uti1.Eventobject, java.uti1.TooManyListenersException.
Example
This example demonstrates how to use the four different event set descriptor constructors. See
Figure 128. A new ’ jump" event is defined to demonstrate all of the pieces needed to define an
event. An event first needs a class to represent the event, which, in general, should be a sub-
EventSetDescriptor
java, beans
class of EventObject (see java, util .Eventobject). An event also needs a listener inter-
face that defines all of the callback methods that can be invoked when the event is fired. The
jump event has only a single callback method: beanJumpedQ. (The listener interface could be
a class, but making it an interface allows any object to listen for the event.)
The other three constructors are
demonstrated using events that are
already defined in the
j ava. awt. event package.
A bean-info is necessary to hold
the four event set descriptors. It
must be defined in a class with the
bean's name appended with "Bean-
Info"—in this case, BeanBean-
Info.
Note: The Beanbo.x in BDK.
1.0apr97 requires that the listener
interface be in a named package.
When it is in an unnamed package,
the Beanbox will not hook up the
bean listener to the bean.
FIGURE 12X: Using Event Set Descriptors,
classexample/Beanjava
package classexample;
import java.awt.event.*;
import java.beans.*;
public class Bean {
// Jump events.
public void addlumpListener(lumpListener listener)
throws java.uti1.TooManyListenersFxception {}
public void removeJumpListenerCJump! istener listener) {}
// Focus events.
public void addFocusListener(FocusListener listener) {}
public void removeFocuslistener(FocusListener listener) {}
// MouseMotion events.
public void addMouseMotionListener(ActionListener listener) {}
public void removeMouseMotionListener(ActionListener listener) {}
// Mouse events.
public void addMouseListener(ActionListener listener) {}
public void removeMouseListener(ActionListener listener) {}
public static void mai n(St ri ng[] args) {
try {
Beaninfo beaninfo = Introspector.getBean!nfo(Bean.class);
EventSetDescriptor[] eds - beaninfo.getEventSetDescriptorsO ;
} catch (IntrospectionException e) {
e.printStackTraceO ;
580
cfassexample/BeanBeanl nfo.java
package classexample;
import java.beans.*;
import java.lang.reflect
public class BeanBeanlnfo extends SimpleBeanlnfo {
public EventSetDescriptor[] getEventSetDescriptorsQ {
try {
EventSetDescriptor[] esd = new EventSetDescriptorГ4];
// First form of the constructor.
esd[01 = new FventSetDescriptor(Bean.cl ass,
"jump",
JumpLi stener,class,
"beanJumped");
esd[0]. setUnicast(true);
esd[0].setlnDefaultEventSet(true);
// Second form of the constructor.
Stringf] 1 istenerNamesl - {"focusGained" t "focusl ost"};
esd[l] = new EventSetDescriptorfBean.class,
"focus11,
java.awt.event.FocusListener.class,
listenerNamesl,
"addFocusListener", "removeFocusListener");
// Third form of the constructor.
Method[] listeners? - {
getMethod(java.awt.event.MouseMotionListener.class,
"mouseMoved", 1),
getMethod(java.awt.event.MouseMotionLi stener.class,
"mouseDragged11, 1), };
esd[2] - new EventSetDescriptor(
'’mousemotion'’,
java.awt.event.MouseMoti onLi stener.class,
1i steners2,
getMethodCBean.class, "addMouseMotionListener", 1),
getMethod(Bean.class, "removeMouseMotionListener", 1));
// Fourth form of the constructor.
MethodDescriptorLJ listeners^ = {
getMethodDesc(java.awt.event.Mouse! istener.class,
"mouseClicked", 1),
getMethodDesc(java.awt.event.MouseListener.cl ass,
"mousePressed11, 1),
getMethodDesc(java.awt.event.Mouse! istener.class.
"mouseReleased", 1),
getMethodDesc(java.awt.event.MouseLi stener.cl ass,
"mouseEntered", 1),
getMethodDesc(java.awt.event.MouseLi stener.class,
"mouseExited”, 1), };
esd[3J = new EventSetDescriptor(
"mouse",
java.awt.event.MouseLi stener.class,
1i steners3,
EventSetDescriptor java.beans
EventSetDcscriptort)
getMethod(Bean.class, "addMousel istener1'. 1) ,
getMethod(Bean.class, "removeMouseLi stener” , 1));
return esd;
} catch (Introspect!onException e) {
e. pri ntStackTraceO ;
1
return nul1;
}
Method getMethod(Class cis, String methodName, int argCount)
throws IntrospectionException {
Method methods[] ® с 1s.getMethodsO;
for (int i = 0; i < methods.length; i+i) {
Method method = methodsfij;
i f (method.getName().equals(methodName)
&& method.getParameterTypesO.1ength ==- argCount) {
return method;
}
throw new IntrospectionException(”No method \”" * methodName
i- "V with 11 4- argCount + " argument1’);
MethodDescriptor getMethodDesc(Class cis, String methodName, int argCc
throws IntrospectionException {
return new MethodDescriptor(getMethod(cl s, methodName, argCount))
}
}
classexample/JumpEvent.java
package classexample;
import java.util.";
public class lumpEvent extends Eventobject {
public JumpEvent(Object source) {
super(source);
}
}
classexam pie/Jump Listener, java
package classexample;
public interface lumpListener {
// this method is called whenever the bean “jumps”.
public void beanlumped(JumpFvent evt);
}
EventSetDescriptorO
in rposf. Constructs an EventSetDescri ptor instance.
582
SYNTAX public EventSetDescriptor(Class sourceClass, String
eventSetName, Class listenerType, String 1istenerMethodName)
throws Introspect iontxception
public EventSetDescriptor(Class sourceClass, String eventSetName,
Class listenerType, String 1istenerMethodNames[], String
addListenerMethodName, String removeListenerMethodName) throws
IntrospectionException
public LventSetDescriptor(String eventSetName, Class
listenerType, Method 1istener^ethods[1, Method
addListenerMethod, Method removeListenerMethod) throws
IntrospectionException
public FventSetDescriptor(String eventSetName, Class
listenerType, MethodDescriptor 1istenerMethodDescriptorsf],
Method addListenerMethod, Method removeListenerMethod) throws
IntrospectionFxception
description Event set descriptors are either implicitly created by the introspector or explic
itly created by a bean. See the class description for more information.
When an event set descriptor is created, five attributes are initialized:
• The event set name
• The listener type
• The listener methods
• The add listener method
• The remove listener method
All other attributes are given default values that can be changed by methods in
this class and in the FeatureDescriptor class. The default values for an
event set descriptor are shown in Table 10.
eventSetName is arbitrary and is not used during introspection. It is mainly
used for presentation purposes.
The class name of listenerType must end with "Listener." If the listener
support methods are not supplied, they are determined using the name of 11 s-
tenerlype. For example, if listenerType is java.awt.event, FocusLis-
tener. class, the listener support methods are
public void addFocusListener(Focust istener listener)
public void removeTocusListener(TocusListener listener)
The listener support methods must take a single parameter and not return any
values. The parameter must be an object of the same type as the listener inter-
face. For example, the listener support methods of the action event are
public void addActionListener(ActionListener listener)
public void removeActionListener(ActionListener listener)
When either 1 i stenerMethodNames or 1 i stenerMethods is specified
(instead of 11 stenerMethodDescrl ptors). a method descriptor is implicitly
EventSetDescriptor java.beans
E ve n t Se i De sc r i ptor ()
created for each of the listener support methods. See MethodDescriptor for
more information on the default values for the method descriptor attributes.
When only one listener method exists (e.g., actionPerformedO in Action-
Event). the constructor that takes the 1 i stenerMethodName parameter can he
used. If this constructor is used, the listener support methods arc automatically
determined as described prev iously.
However, in most cases, there is more than one listener method, so one ofli s-
tenerMethodNames, 1istenerMethods. or 1 istenerMethodDescriptors
must be specified. If the listener methods or the listener support methods are
specified as strings, the Class object of the bean (sourceCiass) must also be
specified so that the string names can be converted into Method objects.
The listener methods must take a single parameter and not return an> values.
The parameter must be the event. For example, the action event (see Action-
Event) has only one listener method. It has the following signature:
public void actionPerformed(ActionEvent evt)
PARAML П RS
addLi stenerMethod
The non-nul 1 Method object of the add listener support method.
addLi stenerMethodName
The non-nul 1 name of the add listener support method.
eventSetName
The nonlocalized name of the event.
1i stenerMethodDescriptors
A non-nul 1 array of method descriptors for the listener methods.
1i stenerMethodName
The non-nul 1 name of the listener method. Used only if the listener interface
defines one listener method.
1i stenerMethodNames
A non-nul 1 array of listener method names.
listenerMethods
A non-nul 1 array of Method objects for the listener methods.
li stenerType
fhe non-nul 1 Class object of the listener interface.
removeLi stene rMethod
The non-nul 1 Method object of the remove listener support method,
removet istenerMethodName
I’he non-nul 1 name of the remove listener support method.
sourceClass
The non-nul 1 Class object of the bean that fires the event.
fxci-ptions
IntrospectionException
584
getAddl л stener Met liod()
If the signature of any method is not compatible with the signature conventions
described in lhe class description.
see also java. lang, reflect .Method.
example See the class example.
getAddListenerMethodf)
purpose Retrieves the event set's add listener support method.
syntax public Method getAddListenerMethodQ
description If an object fires an event, it must provide an add listener method so that other
objects can listen for those events. The add listener method must be invoked
with a single parameter: the listener object. The listener object must implement
or extend from the event set's listener type (see getListenerTypeO к other-
wise Il legal ArgumentException is thrown.
returns The non-nul 1 Method object of the add listener method.
EXCEPTIONS
Il1 egalArgumentExcepti on
The listener does not implement or extend from the event set’s listener type.
see also java.lang.reflect.Method, getListenerTypeO,
getRemoveLi stenerMethodQ-
EXAMPLE
This example demonstrates how to invoke a
bean's listener support methods. It loads a bean
from a class file and then examines all of its
event set descriptors, looking for one that fires
action events. When it finds one, it instantiates
the bean and displays it in a frame. The frame
registers itself with lhe bean, listening for action
events. When the frame is closed, it invokes the
remove listener method on the bean to unregis-
ter itself for action events.
FIGURE 129:
Invoking a Bean’s Listener
Support Methods.
Figure 129 shows the example program executed on the OurButton example
bean in BDK 1.0apr97.
•import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.lang.ref Iect;
import java.uti1.*;
A
В
C
D
D
F
G
H
I
J
К
L
M
N
О
P
Q
R
S
I
i;
v
w
X
Y
Z
EventSetDescriptor
getAddLislenerMethodC)
java, beans
class Main extends Frame {
public static void main(String[] args) {
if (args.length 1- 1) {
System.err.pri ntln(
"Usage: java Main «name of component bean class file>”);
System.exit(l);
}
try {
// Load the bean class.
// (See the Introspector class example for FileClassloader sou
Class beanClass = Fi1eClassLoader.1oad(args[0]);
Beaninfo beaninfo - Introspector.getBeanInfo(beanClass);
// Get the event set descriptors, looking for one that fires
// action events.
EventSetDescriptor edsf] = beaninfo.getEventSetDescriptorsO :
for (int i-0; i<eds.1ength; i++) {
if (eds [i j .getListenerTypeO
java.awt.event.ActionListener.class) {
// Instantiate the bean.
Object bean = beanClass.newlnstance();
// Put the bean in a frame.
new TestFrame((Component)bean, eds[i]);
break;
}
} catch (InstantiationException e) {
e.pri ntStackTraceO ;
} catch (Il 1egalAccessException e) {
e.pri ntStacklrace();
} catch (IntrospectionException e) {
e.pri ntStacklrace();
}
}
}
class TestFrame extends Frame implements Action! istener {
Component bean;
EventSetDescriptor esd;
TestFrame(Component bean, EventSetDescriptor esd) {
super(“getAddLi stenerMethod Example");
Method adder = esd. getAddLi stenerMethodO ;
this.bean - bean;
this.esd - esd;
// Register with the bean for action events.
ObjectLJ adderArgs - {this};
try {
adder.1nvoke(bean, adderArgs);
} catch (InvocationTargetException e) {
e.printStackTraceO ;
} catch (Il 1egalAccessException e) {
e.printStackTraceO ;
}
// Watch for window closing events.
addWindowListener(new WindowLventHandlerO);
586
// Layout and show bean.
add((Component)bean, Border!ayout.CENTER);
setSize(100, 100);
show();
}
// Window events.
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
// Get remove listener method.
Method remover = esd.getRemoveListener^ethodO;
// Remove frame from listening for action events.
Object[] removerArgs = {TestFrame.this};
try {
remover.invoke(bean, removerArgs);
} catch (InvocationTarqetException e) {
e.pri ntStackTrace О;
} catch (IllegalAccessException e) {
e.printStackTraceO;
}
// Destroy the frame.
di sposeO;
1
}
// Action events.
public void actionPerformed(ActionFvent evt) {
System.out.pri ntln(evt);
}
}
getListenerMethod Descriptors!)
PURPOSE Retrieves the method descriptors for the event set’s listener methods.
SYNTAX public MethodDescriptor[] getListenerMethodDescriptors()
DESCRIPTION The listener methods are a group of callback methods that are associated with an event. In particular, when a bean fires the event, one of the listener methods will be called. For example, the focus event (see FocusEvent) has two listener methods: focusGained() and focusLostO. When a bean component loses the focus, the focusLostO listener method is called. The number of elements returned by this method should be identical to the number of elements returned by getLi stenerMethods().
RETURNS A non-null array of MethodDescriptor objects, one for each listener method.
SEE: ALSO java.1ang.reflect.Method, getLi stenerMethods().
example See lhe MethodDescri ptor class example.
EventSetDescriptor
getLi stenerMet he >ds()
java, beans
F
U
I
J
К
I.
M
N
О
P
Q
R
S
T
I!
V
W
X
Y
7
getListenerMet hods()
pi’RPo.se: Retrieves the event set's listener methods.
svniax public Method [] getListenerMethodsО
description The listener methods are a group of callback methods that are associated with
an event. In particular, when a bean fires the event, one of the listener methods
will be called. For example, the focus event (see FocusEvent) has two listener
methods: focusGainedO and focusLostO, When a bean component loses
the focus, the focusLostO listener method is called.
The number of elements returned by this method should be identical to the
number of elements returned by getLi stenerMethodDescri ptorsO-
rlti rns A non-nul 1 array of Method objects, one for each listener method.
see. also java.awt.event.FocusEvent, java.awt.event.FocusLi stener,
java.1ang.reflect.Method, getListenerMet hodDescriptors().
e:x ample See the Introspector class example.
getListenerTypeO
elkposi: Retrieves the event set's listener interface.
syntax public Class getListenerTypeO
descrip!ion The listener interface defines all the callback methods that can be invoked
when the source object fires an event. For example, in the case of the focus
event (see FocusEvent), this method returns FocusListener.class.
The event set's two listener support methods must take a single parameter of
the same type as returned by this method. For example, if the listener interface
is FocusLi stener, the two listener support methods have the signatures
public void addFocusListener(FocusListener listener)
public void removeFocusListener(FocusListener listener)
When the listener support methods are not explicitly specified, the listener
interface is used to determine them through introspection. See the class
description for more information.
retl rns The non-nul 1 listener interface Class object.
seealso getAddLi StenerMethodO, getLi stenerMethodsO »
getRemoveLi stenerMethodO , java, awt. event. FocusEvent,
java.awt.event.FocusLi stener.
example: See getAddListenerMethodO.
588
getRemoveListenerMethod()
purpose Retrieves the event set's remove listener support method.
SYNTAX public Method getRemoveListenerMethodO
A
description A listener that is registered with an event source can be unregistered by invok-
ing the remove listener method. The remove listener method must be invoked B
with a single parameter: the listener object. The listener object must implement C
or extend from the event set’s listener type (see getLi stenerTypeO ): other-
wise, Il legal Argument Except! on is thrown.
returns The non-nul 1 Method object of (he remove listener method. H
F
EXCEPTIONS
IllegalArgumentException G
If the listener object and its parents do not implement the event set's listener H
type.
I
SEE ALSO java.lang.reflect.Method t getAddLi stenerMethodO,
getLi stenerTypeO. J
example See getAddLi stenerMethodO. К
L
isInDefaultEventSet()
purpose: Retrieves the state of the event set's '“default set" attribute. 0
SYNTAX public boolean i slnDefaul tEventSetO P
DESCRIPFION Note: We can't elaborate on the “default set" attribute because it's not yet defined in the JavaBeans specifical ion.
RETURNS true if the event set is in the “default set"; fal se otherwise. R
SEE ALSO setlnDefaultEventSetО. $ T
is Unicast() и
v
PURPOSE Determines if the event set is unicast.
SYNTAX public boolean isUnicastO x
description An object firing a unicast event will support only one listener for that event. Y See the class description for more details of unicast events.
KventSetDescriptor
sctlnDefaultEveniSeK)
java.beans
The introspector can discover implicit!} that an cxent set is unicast if its add listener method throws TooManyLi stenersException. You can also explic-
Rl.ll RNs illy specify that an event set is unicast by using setUni castО true if the event set is unicast; fal se if the evenl set is multicast.
Л SLL Al.SO java.uti 1 .TooManyListenersException, set Unicast().
В EXAMPI 1 See the Introspector class example.
c D setlnDefaultEventSetO
F plrposi: Sets the event set s "default sei” attribute.
G SYNTAX public void setInDefaultEventSet(boolean inDefaultEventSet)
H DESCRIPTION Nate: We can't elaborate on the "default set" attribute because it's not \et
1 defined in the JavaBeans™ specification.
J PARAMETERS i nDefaultEventSet
К true if the event set should be in the "default self*
L SI-л: ALSO i slnDefau1tEventSet().
M N set Unicast ()
0 p pi rpose: Specifies whether the event set is unicast.
o S'! max public void setUnicast(boolean unicast)
DI SC RIEM ION An object firing a unicast event will support only one listener for that excnt.
R S See the class description for more details of unicast events. The introspector can discover implicitly that an event set is unicast if its add
T listener method throws TooManyListenersException. You can also explic-
1 itly specify that an exent set is unicast by using this method.
V PARAML IliRS unicast true if this event set is unicast; false if this event set is multicast.
w SEE ALSO i sUni cast().
X Y EXAMPLE See the class example.
Z
590
FeatureDescriptor
Syntax
public class FeatureDescriptor
Description
A feature descriptor is an object used to hold information about some part -a feature of a
bean. For example, the feature descriptor of a bean property specifies whether it is hound or
constrained, while the feature descriptor of a bean method specifies whether the method
should be used only by experts. Table 11 shows all of the bean parts that are features.
Feature FeatureDescriptor Subclass
Bean Event set Property Indexed property Method Method parameter BeanDescri ptor EventSetDescriptor PropertyDescri ptor IndexedPropertyDescri ptor MethodDescriptor ParameterDescri ptor
TABLE II: Features and Their Feature Descriptor Classes.
Attributes
The pans of a feature descriptor are called attributes. For example, the feature descriptor for a
bean property includes attribute information on the property's accessor methods, while the fea-
ture descriptor for a bean event set includes attribute information on whether the event is mul-
ticast. Since each bean feature contains attributes that are specific to the feature, each feature is
F eat u re Descri pto r
java.beans
represented by different classes, where each class contains those special attributes needed by
the feature. Table 11 shows the associated bean descriptor classes for each of the bean features.
Although there is a class for each bean feature, all bean feature descriptors share a set of
common attributes. This common set is contained in the class FeatureDescriptor. All other
A feature descriptors extend from this class and add their own special attributes. Table 12 shows
all of the attributes in the FeatureDescr iptor class.
Attribute
Contents
Default Value
Name The feature’s nonlocalized name. null
H
1
J
К
I.
Display name The feature's localized name. null
Short description A localized description of the feature. nul I
Expert t rue if the feature is considered for use b\ fal se
experts only.
Hidden true if the feature is meant to be used by a false
tool; false if it is meant to be use b\ a per-
son.
TABLE 12: Feature Descriptor Attributes and Their Default Values,
* In general, a bean does not typically define new bean features. But in the event that it
\i does, the hean should not use FeatureDescriptor to describe the new bean feature. Instead.
the bean should define a new subclass of FeatureDescriptor and use the subclass, c\en if
the subclass does not add any extra attributes. For example. ParameterDescriptor is a fea-
p ture descriptor that does not add any extra attributes. This allows a bean editor to distinguish
q between different types of feature descriptors.
R Extension Attributes
S A feature descriptor supports the ability to specify extra attributes called extension attributes.
An extension attribute has a name, which is a string, and a value, which is any non-nul 1
object. Extension attributes are used when a bean editor may treat a bean differently if it
U detects a particular extension attribute. For example, a bean editor may refuse to edit a bean
v unless it contains a "serial-number" attribute with an appropriate value.
w For Bean Editors Only
X The information contained in a feature descriptor is meant for programs such as bean editors
(programs that help connect together beans into an application) and is not used by the bean
Y itself. These and other descriptors essentially help a bean editor to construct a meaningful user
Z interface for editing the bean. When the bean is actually running in an application, the feature
descriptors are never used.
592
Biber summary
Constructor FeatureDescri ptor() Constructs a FeatureDescriptor instance.
Get Attribute Methods getDisplayNameO Retrieves the feature's display name.
getNameO Retrieves the feature's name.
getShortDescri pti on() Retrieves a short description of the feature.
isExpertf) Retrieves the feature's expert attribute.
isHiddenO Retrieves the feature's hidden attribute.
Set Attribute Methods setDisplayNameQ Sets the feature's display name.
setExpertO Retrieves the feature's expert attribute.
setHiddenO Sets the feature's hidden attribute.
setNameO Sets the feature's name.
setShortDescri ptionO Sets a short description of the feature.
Attribute Extension Methods
attributeNamesQ
getValue()
setValueQ
Retrieves the feature descriptor's extension attribute names.
Retrieves the value of an extension attribute.
Defines an extension attribute.
See ALso
BeanDescriptor, EventSetDescriptor, IndexedPropertyDescriptor,
MethodDescriptor, ParameterDescriptor, PropertyDescriptor.
Example
This example demonstrates how to
add extension attributes to a feature
descriptor. The example implements
a bean-info that returns a bean
descriptor with two extension
attributes: author and created. The
author attribute is a simple string
and the created attribute is a calen-
dar object.
The main program invokes the
introspector to retrieve the bean
descriptor and print its contents into
a text area. See Figure 130.
I .. FeatureDescriptoi Example
Name CheapBean Display name. CheapBean© Short Description A bean of no consequence Expert' true Hidden: true
author = Patrick Chan and Rosanna Lee created = 22-May-97 jflj:
FIGURE 130: Adding Extension Attributes to
FeatureDescriptor.
F eat u reDesc ri p tor
java, beans
The empty bean class is needed in order for the introspector to find the bean info.
Main, java
import java.awt.*;
import java.awt.event.*;
import java.beans;
import java.uti1 , *;
import java.text.*;
class Main extends Frame {
Main(BeanDescriptor beanDesc) {
super("FeatureDescriptor Example'1);
TextArea ta - new TextArea(’"’, 10, 40,
TextArea.SCROLLBARS_VERTICAl _0NLY);
// Make the text area readonly,
ta.setEditable(false);
// Print the attributes that are in FeatureDescriptor
ta.append("Name: 11 * beanDesc.getNameO + ,r\n");
ta.appendC'Display name: " + beanDesc.getDisplayName() * "\n");
ta.append(MShort Description: " +
beanDesc.getShortDescription() * "\nM);
ta. appendC’Expert: " + beanDesc . i sExpert() * “Xn”);
ta. appendC'Hidden: " + beanDesc. isHiddenO * "\n\n"):
// Print all the extension attributes.
Enumeration enum = beanDesc. attri buteNamesO :
for (Enumeration e=enum; e.hasMoreElementsO ; ) {
String name = (String)e.nextElement();
Object value = beanDesc.getValue(name);
// Look for Calendar objects.
if (value instanceof Calendar) {
value - DateFormat.getDatelnstanceO.format(
((Calendar)value) .getTimeO) ;
}
ta.append(name + " = ’' + value * ’’Xn");
}
// Layout and show.
add(ta, BorderLayout.CENTER);
setSize(200f 100);
show();
}
public static void main(String[] args) {
try {
// Retrieve the bean-info and then the bean descriptor.
Beaninfo beaninfo = Introspector.getBeanlnfofBean.cl ass);
BeanDescriptor beanDesc -= beaninfo.getBeanDescriptorQ;
// Display the bean descriptor information,
new Main(beanDesc);
} catch (IntrospectionException e) {
e.printStackTraceO ;
}
}
}
594
BeanBeanlnfo.java
import java.beans.*;
import java.util
public class BeanBeanlnfo extends SimpleBeaninfo {
public BeanDescriptor getBeanDescriptorO {
BeanDescriptor bd =- nev\< BeanDescriptor(Bean . class) ;
// Initialize FeatureDescriptor attributes.
bd. setNameC'CheapBean");
bd.setDisplayNaпle(,,CheapBean\u00a9,’) ; // Copyright symbol
bd.setExpert(true);
bd.setHidden(true);
bd. setShortDescr i ptionC’A bean of no consequence");
// Add an "author" attribute.
bd. setValueCauthor", ’’Patrick Chan and Rosanna Lee");
// Add a "created" attribute.
Calendar calendar = Calendar.getlnstanceO;
calendar.set(1997, 4, 22, 10, 49);
bd. setValue(’’created", cal endar) ;
bd.setValue("created", null);
return bd;
}
}
Bean, java
public class Bean {
// An empty bean.
}
attributeNamesf)
PURPOSE Retrieves the feature descriptor’s extension attribute names.
SYNTAX public Enumeration attributeNatnesQ
DESCRIPTION This method retrieves all of the feature descriptor’s extension attribute names, if any.
RETURNS A non-null enumeration containing the attribute names.
SEEALSO getValueO, java.uti1.Enumerationt setValueC).
example See the class example.
595
F eat u re Descri pto r java.beans
FeatureDescriptoi()
FeatureDescriptorO
PURPOSE Constructs a FeatureDescriptor instance.
S\ ЯАХ public FeatureDescriptorO
DESCRIPTION EXAM Pl E In general, a bean does not typically define new bean features. But if it does, the bean should not use FeatureDescriptor to describe the new bean fea- ture. Instead, the bean should define a new subclass of FeatureDescriptor and use that instead, even if the subclass does not have any extra aiiributes. For example. ParameterDescri ptor is a feature descriptor that does not add any extra attributes. This allows a bean editor to distinguish between different types of feature descriptors. The default values for a feature descriptor are shown in Table 12. See the class example.
getDisplayNameO
PCR POM- Retrieves the feature's display name.
SYNTAX public String getDisplayNameO
DESCRIP HON The feature's display name is a localized string that a bean editor displays to identify the feature. For example, a bean could have a property called 'color" but whose display name is “colour." If the display name has not been explicitl\ set or if it is set to nul 1 by setDis- playNameQ. this method returns getNameO.
RETURNS Л possibly null localized string containing the feature's display name.
SET: ALSO getNameO, setDi splayNameO.
EXAMPLE See the class example.
getNameO
PURPOSE Retrieves the feature's name.
SYNTAX public String getNameO
DESCRIPTION The feature's name is a nonlocali/ed string used by a program when referring to the feature.
RETURNS A possibly null string containing the feature's name.
SEE ALSO getDisplayNameO . setNameO.
596
getShortDescriptionO
PURPOSE Retrieves a short description of the feature.
syntax public String getShortDescriptionO
DESCRIPTION The feature's short description contains a string that a bean editor can present to users to provide a little more detail about (he feature. The string should be around 40 characters or fewer. If the short description has not been explicitly set or if it is set to nul 1 by set- ShortDescription(). this method returns getDisplayNameO.
RETURNS A possibly nul 1 localized string containing a short description of the feature.
SEE ALSO getDisplayNameO, setShortDescr!ption().
EXAMPLE See the class example.
getValueO
PURPOSE Retrieves the value of an extension attribute.
SYNTAX public Object getValue(String attributeName)
PARAMETERS
attributeName
The non-null nonlocalized attribute name.
RETURNS The attribute's non-nul 1 value; nul 1 if the attribute is not defined.
SEE At.SO attributeNamesO, setValue().
EXAMPLE See the class example for a longer example.
void printSerialNumber(BeanDescriptor beanDesc) {
Object value = beanDesc.getValue(“serial-number”);
if (value == null) {
System.out.prinltn(“7he extension attribute is not defined1');
} else {
System.out.prinltn(value);
1
Feat u re Desc rip tor isExperU) java, beans
isExpertO _ — - _ —
Pl'RPOSL Retrieves the feature's expert attribute.
SYNTAX public boolean isExpertO
A DESCRIPTION If this method returns true, the feature is meant to be used by experts only. A
В bean editor could use this information to hide expert-only features and display
C those features only if rhe user asks to see them.
D RFTl’RNS true if the feature is intended for use by experts only; false otherwise.
I- SIT ALSO setExpertQ.
EXAMPLE See the class example.
G
H isHiddent)
1 PLRPOSE Retrieves the feature's hidden attribute.
J SYMAX public boolean isHiddenO
К 1)1 ASCRIPTION If this method returns true, the feature should not be modified by users. Hid-
L den features are maintained by programs. A bean editor could use this infor-
M mation to hide the feature from the user.
N RETLRN’S true if the feature is meant to be used by a tool; fal se if it is meant to be used
О SEE ALSO by a person. setHiddenf).
P EXAMPLE See the class example.
Q R V setDisplaylNameO
Л ' — — — .—_ -
1 И’RPOSE Sets the feature's display name.
и SYNTAX public void setDisplayName(String displayName)
V DESCRIPTION The feature's display name is a localized string that a bean editor displays to
w X PARAMEIERS identify the feature. For example, a bean could have a property called "color" but whose display name is "colour."
Y displayName A possibly-null localized string containing the feature's display name.
Z SEE ALSO getDi spl ayNameO.
See the class example.
EXAMPLE
50Я
setExpertO
pCRPOSfi Retrieves the feature's expert attribute.
SYNTAX public void setExpert(boolean expert)
DESCRIPTION This attribute lets you designate a feature to be for experts only. A bean editor A
could use this information to hide expert-only features and display those tea- В
ture only if the user asks to see them. C
parameters D
expert true if the feature is intended for use by experts only; false otherwise. E
SEE ALSO isExpertO.
EXAMPLE; See the class example. G
tl
setHiddenO E
PURPOSE: Sets the feature s hidden attribute. J
SYNTAX public void setHidden(boolean hidden) К
DESCRIPTION This attribute lets you to designate a feature to be for program use only. Hid- 1.
den features should not be modified by users. /X bean editor could use this M
information to hide the feature from the user.
N
PARAMETERS
hidden true if the feature is meant to be used by a tool; f al se otherwise. G
SEE ALSO isHiddenO. P
example See the class example. Q
R
setNamef) S
...— • . — •— — —• —- — — — — — — — — — — -— —• — — — T
PURPOSE- Sets the feature's name. L
SYNTAX public void setNameCString name) V
DESCRIPTION The features name is a non localized string that is used by a program when w
referring to the feature.
X
PARAMETERS
name A possibly-nul 1 localized string containing the feature's display name. У
SEE ALSO getName(). 7
EXAMPLE-. See the class example.
F eat u reDescriptor
set Short Description)
java.beans
setShortDescription()
PURPOSE; Seis a short description of the feature.
SYNTAX public void setShortDescriptionfString text)
A DESCRIPTION The feature’s short description contains a string that a bean editor can present
В io users to provide a little more detail about the feature. The string should be
C around 40 characters or fewer.
I) parameters
Г7 text Л non-nul 1 localized string containing a short description of the feature.
I . see: also getShortDescri pti on().
G EXAMPLE See the class example.
H I setValue()
J PURPOSE Defines an extension attribute.
К SYNTAX public void setValue(String attributeName, Object value)
L DESCRIPTION Defines an attribute that has a non-nul 1 value. If the attribute is already
M v PARAMETERS defined, the old value of the attribute is replaced with value.
л attributeName
0 The non-nul 1 nonlocalized attribute name.
P value A non-nul 1 value.
Q sue also attributeNames(), getValueO.
R example: See the class example.
1'
U
V
w
X
Y
Z
600
FileDialog
Syntax
public class FileDialog extends Dialog
Description
The FileDialog component displays a dialog for selecting a tile in the tile system. The file
dialog can be used to either load or save a tile. It is a modal dialog and blacks the calling
thread until the user has chosen a file.
The Mode Property
There are two tile dialog modes: load and save. A load file dialog is used to select an existing
file in the file system. Л save file dialog is used either to select an existing file or to select an
existing directory and then to allow the user to name a new file. The mode is set al the time a
file dialog instance is created and can be changed at any time.
The Directory and File Property
The directory property of a file dialog indicates the directory that the file dialog is currently
displaying. The file property indicates either the file that is currently selected in the file dialog
or the text in the filename entry text field.
These properties can be set before the file dialog is displayed and queried after the dialog
is closed.
The Filter Property
The filer property controls which files are displayed in the file dialog. The filter is a class that
implements the Fi lenameFi Iter interface that defines the accept() method. The accept()
method is passed a directory and a filename. It returns true if the file should be displayed and
fa*l se otherwise.
See Also
Fi lenameFi Iter
File Dialog
java.awt
Л
В
c
D
Г
G
II
I
J
К
L
M
N
О
P
Q
R
S
T
i;
v
w
x
Y
Z
MEMBER SUMMARY
Constructor Fi 1 eDi alogO Constructs a new Fi 1 eDialog instance.
File Dialog Types LOAD SAVE The file dialog mode that specifies a load file dialog. The file dialog mode that specifies a save file dialog.
Property Methods getDi rectoryO getFi1e() getFilenameFi1ter() getModeQ setDi rectoryO setFileO setFilenamerilter() setModeO Retrieves this file dialog's directory property. Retrieves this file dialog's file property. Retrieves this filename filter object. Retrieves this file dialog's mode. Sets this file dialog's directory property. Sets this file dialog's file property. Sets this file dialog's filename filter. Sets this file dialog's mode.
Peer Method addNoti fyO Creates the file dialog's peer hierarchy.
Debugging Method paramStringO Generates a string representing lhe file dialog's state.
Example
This example creates a frame with two buttons
(Figure 131). One button creates a load file dialog
(Figure 132), while the other creates a save file
dialog (Figure 133). In addition, the frame con-
tains three text Helds directory, file, and filter—
for showing and changing the current values of
the file dialog's properties. Just before lhe file is
displayed, lhe directory and file properties are ini-
tialized to the values in the respective text fields.
After a file has been selected and the file dialog is
closed, the two text fields are updated with lhe
values in the dialog.
The file filter is implemented by the accept О
^FileDialog Example
1 г-
diiectoiyd
fib:| NewClass|
java”
FIG Г RE 131: FileDialog: Control Panel
mode is LOAD and the filename suffix matches the contents of the filler text field. If the file <
log taode is SAVE, accept О always returns true.
602
Note: In Java 1.1.2. filename filtering does not work. Nor does setting the director} and
the filename. The file dialog always displays the entire contents of the current working direc-
tory.
Open ____________________________________ВЕЗ
Look in: | lang
!* *] Object iava
W| OutOfMemoryError iava
[й] Process java
l-зй] Runnable.java
lai] Runtime, java
|ай] RuntimeE xception iava
Security Exception iava
ai] Security Manager iava
ai] S tackO vertlowE rror iava
_л] String.java
a] StringB utter |ava
ai] S tringlndexOutLlfB oundsE xception |.
Open
File name:
Files of type.
Cancel
FIGURE 132: A Load File Dialog.
Save
ИВ
Save in: M lang
ЗЙй! 1йв®1
,ai] A b s tract b '1 e t h о d E г г о r । a a
raj] ArithmeticE xception iava
af] Ar rayl ndexO utO tB oundsE xc cphon । ava
|ai] A г r ay S t о r e E x c e p t i о n । a v a
;=*] Boolean, iava
*0 Lharacter java
ai] Class |ava
^i] L-1 a s s L- a s t E x c e p 11 о n । a v a
ей! Llac ?Circ ulantvE rr,jr iava
* i] LlassEorrriatError iava
* i] LlassLoader iava
* i] LlassNotFoundE xception iava
4
File name: [New'L.lass|
Save as type: I
Save |
Cancel
FIGURE 133: \ Save File Dialog.
FileDialog
java.awt
Л
В
С
D
E
G
II
I
J
К
L
M
N
О
P
Q
R
S
T
i;
v
w
x
Y
z
import java.awt.*;
import java.awt.event;
import java.io.*;
class Main extends Frame implements FilenameFi1 ter, ActionListener {
FileDialog fd;
TextField tfDirectory = new TextFieldO;
TextField tfFile - new TextFieldO;
TextField tfFilter = new TextFieldO;
Main О {
super(“Fi leDi alog Example");
Button lb = new Button(“Load") ;
lb.addActionListener(this) ;
Button sb = new ButtonCSave”) ;
sb.addActionli stener(thi s);
add(lb, BorderLayout.WEST);
add(sb, BorderLayout.EAST);
Panel p = new Panel(new GridBagLayoutO);
addRow(p, new Label(“di rectoryt Label.RIGHT), tfDirectory);
addRow(p, new Label("file:", Label.RIGHT), tfFile);
addRow(p, new Label(“fiIter, Label.RIGHT), tfFilter);
add(p, BorderLayout.SOUTH);
packO;
show();
1
// Adds a row in a gridbag layout where the c2 is stretchy
// and cl is not.
void addRow(Container cont, Component cl, Component c2) {
GridBagLayout gbl = (GridBagLayout)cont.getLayoutO ;
GridBagConstraints c - new GridBagConstraints();
Component comp;
c.fill = GridBagConstraints.BOTH;
cont.add(cl);
gbl.setConstraints(cl. c);
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1.0;
cont.add(c2);
gbl.setConstraints(c2, c);
}
public boolean accept(File dir, String name) {
if (fd.getModeO »= FileDialog.LOAD) {
reteurn name.lastlndexOf(tfFiIter.getTextO) > 0;
}
return true;
}
public void actionPerformed(ActionEvent evt) {
String what = evt.getActionCommandO;
boolean load = “Load".equals(what);
FileDialog fd;
if ("Load".equals(what)) {
fd - new Fi leDialog(thi s, null, FileDialog.LOAD);
604
} else if (“Save”.equals(what)) {
fd - new FileDialog(this, null, FileDialog.SAVt);
} else {
return;
}
fd.setDirectory(tfDi rectory. getTextO) ; A
fd.setFile(tfFile.getTextO);
fd.setFilenameFiIter(Main.thi s); В
fd.showO; (
// Update text fields with input from dialogs I)
tfDi rectory. setText(fd.getDi rectoryO) ;
tfFile.setText(fd.getFileO); В
и
static public void main(String[] args) {
new MainQ; G
}
H
}
1
J
. addNotify() K
purpose Creates this file dialog's peer hierarchy.
M
syntax public void addNotifyO
N
description This method creates this file dialog’s peer hierarchy, if necessary, l he file dia-
log’s peer is created by calling the Tool kit.createFi1eDialog() method. °
Overrides Dialog. addNotifyO. p
see also Component, Toolkit. Q
example See Component. setVi si Ы e (). К
s
FileDialogO
................................ " --------- и
purpose Constructs a new Fi 1 eDi al og instance.
syntax public Fi1 eDialog(Frame parent)
public FileDialog(Frame parent, String title)
public FileDialog(Frame parent, String title, int mode) X
description This constructor creates a new invisible Fi 1 eDialog instance with the parent Y
parent, title title, and file dialog mode mode. If mode is not specified, it
defaults to LOAD. The title can be null or not specified, in which case it
defaults to "Open” for a load file dialog and "Save” for a save file dialog.
FileDialog java.awt
getDirecroryc) By default, all of (he properties of the file dialog—directory, file, and filter are set to null.
PARAMETERS mode parent title An integer specifying the file dialog mode. The file dialog's non-null parent. The string specifying the title of the file dialog. If null, it defaults to eithei “Open” or “Save”, depending on the mode.
EXCEPTIONS
111 egal ArgumentExcepti on
It parent is null.
SEE: ALSO LOAD, SAVE.
exam pi E See the class example.
getDi rectory ()
PIRPOS1 Retrieves the file dialog's directory property.
SYNIAX public String getDi rectoryO
DESCRIPTION This method should not be called while the dialog is visible.
REIT RNS The non-null directory of the file dialog.
SEI- ALM) setDi rectoryO.
EXAMPLE Sec (he class example.
getFile()
Pl RPOSE SYNTAX Retrieves the file dialog's file property, public String getHleO
DESCRIPTION This method should not be called while the dialog is visible.
RET CRN’S The Hie property. A return value of null indicates that no file was selected.
SEE Al SO setFile().
LX AM Pl I; See the class example.
getFilenameFilter()
PURPOSE Retrieves the filename filter object.
SYNTAX public FilenameFiIter getFi1enameFilter()
RETURNS The object that is implementing the filename filter May he nul 1.
SEE ALSO FilenameFiIter, setFi 1 enameFi 1 ter().
example See the class example.
getModef)
PURPOSE Retrieves this file dialog’s mode.
SYNTAX public int getModeO
RETURNS An integer indicating the file dialog’s mode, which can be either LOAD or SAVE.
SEE ALSO LOAD, SAVE, setModeQ.
example: See the class example.
LOAD
PURPOSE: The file dialog mode that specifies a load file dialog.
SYNTAX public static final int LOAD
description This integer constant is used to specify a load file dialog when a file dialog is created.
example See the class example.
paramString()
PURPOSE Generates a siring representing this file dialog's state.
SYNTAX protected String paramStringO
DESCRIPTION This method returns a string representing the file dialog, including the selected item. A subclass of this class should override this method and return a concat- enation of its state with the results of super. paramStri ng(). This method is called by the Component.toStri ngO method and is typically used for debug- ging.
RETURNS A non-null string representing the file dialog's state.
FileDiaiog
SAVE
java.awt
overrides Di al og. paramSt r i ng О.
see also Component. toStringO, java .lang.Object. toStringO.
example See Component.paramStringO.
SAVE
purpose The file dialog mode that specifies a save file dialog.
syntax public static final int SAVF
description This integer constant is used to specify a save file dialog when a file dialog is
created.
example See the class example.
J к setDirectory()
PURPOSE Sets this file dialog's directory property.
I. SY .VI AX public synchronized void setDirectory(String dir)
M DESCRIPTION If dir is null or specifies an invalid directory, no exception is raised. The behavior of the file dialog in this case depends on the platform, but typically
N some default directory is displayed.
() This method should be called before the file dialog is made visible. It should
P not be called when the file dialog is visible.
Q PARAMETERS
R di Г fhe string specifying the directory to display in the file dialog. May be null.
S SEE ALSO getDi rectoryO.
T u EXAMPLE See the class example.
V setFile()
w PURPOSE Sets this file dialog’s file property.
X SYNTAX public synchronized void setFile(String file)
Y DESCRIPTION When the file dialog is displayed, its filename text field contains the string
z file. If the file dialog’s current directory has a file with the name file, that
file will be selected. If file is null, the filename defaults to
608
This method should be called before the file dialog is made visible. It should not be called when the file dialog is visible.
PARAMETERS file I’he string specifying the initial value of the f ilename text field in the file dia- log. May be null.
SEE ALSO getFileO-
example See the class example.
setFilenameFilter()
purpose Sets the file dialog's filename filter.
SYNTAX public synchronized void setFilenameFi1ter(Filenamel iIter filter)
DESCRIPTION This method installs filter as the file dialog's filename filter. The file dialog will display only Hies whose names are accepted by the filename filter. If fi 1 - ter is nul 1, the file dialog displays all files.
PARAMEI ERS filter The possibly nul 1 filename filter for the file dialog.
SEE ALSO FilenameFiIter, getFi1enameFiIter().
EXAMPLE See the class example.
setMode()
purpose Sets this file dialog's mode.
syntax public void setMode(int mode)
PARAMETERS
«node An integer indicating the file dialog s mode, which must be either LOAD or
SAVE.
EXCEPTIONS
Illegal ArgumentException
If mode is neither I OAD nor SAVE.
SEEALSO getModeO, LOAD, SAVE.
example The class example could have been written to use setModeO instead of creat-
ing a new instance of Fi 1 eDi alog each time the Load button or Save button is
clicked. This example is a simplified version of the class example that uses
FileDialog
sctMode()
java.awt
only a single instance of Fil eDialog. The Load and Save buttons control the
mode of the file dialog and display the file dialog. Because file dialog win-
dows are modal, you must exit the file dialog before making another button
selection.
import java.awt.-;
import j ava. awt. event .•*;
class Main extends Frame implements ActionListener {
FileDialog fd;
Main О {
super(“setMode example’’):
Panel p = new Panel(new Gri dl ayout (1, 0));
Button b;
b т new ButtonC'Load ’);
p.add(b);
b.addAct ionLi stener(thi s);
b - new ButtonC'Save”);
p.add(b);
b.addActi onLi stener(thi s);
add(p, BorderLayout.SOUTH);
packO;
showO:
// Create file dialog
fd = new FileDialogCthi s);
}
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommandQ;
if (cmd.equalsCToad")) {
fd.setMode(FileDi a log.LOAD) ;
fd. showO ;
} else {
fd.setModefFileDialog.SAVE);
fd.show();
}
}
static public void main(String[] args) {
new wai nt);
}
}
610
FileDialogPeer
Syntax
public interface FileDialogPeer extends DialogPeer
Description
The file dialog component (see the FileDiaiog class) in the AWT uses the platform’s native
implementation of a file dialog box. So that the AWT file dialog box behaves the same on all
platforms, the file dialog box is assigned a peer, whose task is to translate the behavior of the
platform's native file dialog box to the behavior of the AWT file dialog box.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java. awt counterparts.
See Component and Tool ki t for additional information about component peers.
^member summary
Peer Methods setDi rectoryO setFileO setFilenameFilter О Sets the file dialog’s directory property. Sets the file dialog’s file property. Sets the file dialog's filename filter.
See Also
java.awt.Component, java.awt.Fi1eDialog, java.awt.Toolkit.
FileDialogPeer
setDi rectory ()
java.aw (.peer
setDi rectory ()
pr rpose- Sets the file dialog's directory property.
syntax void setDirectory(String dir)
PARAMETERS
di r The string specifying the directory to display in the file dialog.
see also java.awt.Fi1eDialog,setDi rectoryf).
setFile()
purpose- Sets the file dialog's file property.
symax void setFi leCStri ng file)
PARAMEIERS
file The string specifying the initial value of the filename text field in the file dia
log.
Sfili also java. awt. Hl eDi al og. setFI 1 e().
setFilenameFilter()
pi. rpose Sets the file dialog's filename filter.
syntax void setFilenameFiIter(FilenameFiIter filter)
PARAMEl ERS
fi Iter The possibly null filename filter for the file dialog.
see: also java.awt.FileDialog,setFi lenameFilterO.
T
t;
V
w
X
Y
Z
612
FilteredlmageSource
. j xv i 1 u.g • J
* ......ulw
"I e<3Teaagc^urce — j ’’ 71 lq 1; Л
в
Syntax c
public class FilteredlmageSource implements ImageProducer D
E
Description щ
This class is used to build a stream of image filters. This class takes an image producer and an HI
image filter (see ImageFiIter) and creates a new image producer. This new image producer (j
can be combined with yet another image filter to create yet another image producer. Image
consumers that get pixels from the new image producer will get pixels that have been modified
by the associated image filter. I
J
{member summary К
Constructor L
FilteredlmageSourceO Constructs a new FilteredlmageSource M
object. N
Image Producer Methods i о
addConsumerO Registers an image consumer with this image I °
producer. P
isConsumer () Determines if an image consumer is registered with this image producer. Q
removeconsumer() Removes a registered image consumer from this R
image producer. c
requestTopDownLeftRightResendO Request by an image consumer to retransmit pix-
els in top-down, left-to-right order. T
startproduction О Adds an image consumer to the list of consumers interested in pixels. U
L— _ , : : V
See Also
Imageconsumert ImageFiIter, ImageProducer.
w
X
Y
r ilteredlmageSource
java.awt.image
Example
This example creates a filter stream with two
image filters. See Figure 134. The first image fil-
ter closest to the source image is a crop filter that
A extracts a portion of the source image. In this
B example, the bottom quarter of the image is
removed. The next filter down the pixel stream
< is an RGB filler that swaps the red and blue
D components of all of the colors in the image.
FIGI RE 134: Fil teredlmageSource.
E
G
H
1
J
К
I,
M
N
О
P
Q
R
S
T
t:
v
x
Y
import java.awt."';
import java.awt.image.-;
import java.awt.event;
import java.net.*;
import java.util .
class Main extends Frame {
Main(String filename) {
super(“Fi1teredlmageSource Example”);
try {
Image image - getToolkit().getlmage(filename);
// Use a media tracker object to wait until all the pixels
// have been retrieved.
MediaTracker tracker - new MediaTracker(this):
tracker.addTmage(image. 0);
tracker.waitForID(0);
add(new ImaqeCanvas(image), Borderlayout.CENTER);
} catch (Exception e) {
e.printStackTraceO ;
}
setSize(50, 100);
showO ;
}
static public void mai n(Stri ng [] arqs) {
if (args.length -= 1) {
new Mai n(args[0]);
} else {
System.err.println(“usage: java Main <image files”);
}
}
}
class ImageCanvas extends Component {
Image newlmage;
ImageCanvasClmage image) {
ImageProducer ip =- image .getSourceO;
ip = new Ti1teredImageSource(ip, new CropImageFi1ter(0, 0,
image.getWidth(this), image.get Height(thi s)v3/4));
ip = new Fi1teredImageSource(ip, new RedBlueSwapFi1ter());
newlmage - get Toolkit().createTmage(ip);
}
614
public void paint(Graphics g) {
g.drawlmage(newlmage, 0, 0, this);
}
}
class RedBlueSwapFilter extends RGBInageFi1 ter {
public RedBlueSwapFi1ter() {
canFi1terlndexColorModel - true;
}
public int fi1terRGB(int x, int y, int rgb) {
return ((rgb & 0xff00ff00)
| ((rgb & 0xff0000) » 16)
| ((rgb & 0xff) « 16));
}
}
PURPOSE Registers an image consumer with this image producer.
SYNTAX public synchronized void addConsumer(TmageConsumer ic)
DESCRIPTION See ImageProducer .addConsumerO for details on how an image consumer should use this method.
PARAMETERS ic The non-nul 1 image consumer to register.
SEE ALSO ImageConsumer.
EXAMPLE See ImageProducer.addConsumerО.
FilteredImageSource()
PURPOSE Constructs a new Fi 1 teredlmageSource object.
SYNTAX public FilteredImageSource(ImageProducer ip, ImageFilter filter)
DESCRIPTION This constructor constructs a new filtered image source that combines an image producer with an image filter. The new filtered image source becomes a new image producer, which takes pixels from ip. converts them using fi Iter, and then passes them on to its registered image consumers.
PARAMETERS filter ip The non-null image filler The non-null image producer.
SEE ALSO ImageFilter, ImageProducer.
EXAMPLE See the class example.
Filtered I mageSou rce
isConsunier()
ja va, aw t. image
pirpose: Determines if an image consumer is registered with this image producer
S\NE AX public synchronized boolean isConsumer(ImageConsumer ic)
DESCRIPTION See ImageProducer.isConsumerQ for details on how an image consumer should use this method.
PARAMETERS i C The possibly nul 1 image consumer to check if registered.
KETER VS true if ic has been registered: false otherwise.
SEE ALSO ImageConsume r.
EXAMPLE- See ImageProducer.i sConsumer Q.
removeConsumer()
PLRPOSE Removes a registered image consumer from this image producer.
SYNTAX public synchronized void removeConsumer(lmageConsumer ic)
DESCRIP HON Sec ImageProducer.removeConsumerO for details on how an image con- sumer should use this method.
PARAMETERS ic I'hc non-nul 1 image consumer to be removed.
EXAMPLE See ImageProducer.removeConsumerO-
requestTopDownLeftRightResendO
PURPOSE Request by an image consumer to retransmit pixels in top down, left-to right order.
SYNTAX public void requestTopDownLeftRightResend(ImageConsumer ic)
DESCRIPTION See ImageProducer. requestTopDownLeftRightResendO for details on how an image consumer should use this method.
PARAMETERS ic The non-nul 1 image consumer requesting the retransmission.
SEE ALSO TmageConsumer.
EXAMPLE See ImageProducer.requestTopDownLeftRightResendO.
616
£
|gtartProduction()
PURPOSE /Xdds an image consumer to the list of consumers interested in pixels.
SYNTAX public void startProductionflmageConsumer ic)
description See ImageProducer.startProductionO for details on how an image con- sumer should use this method.
parameters ic The non-null image consumer ready to receive pixels.
SEE ALSO ImageConsumer.
example: See Imageproducer. startProductionQ.
A
В
R
S
1
Г
V
w
X
61S
java.awt
FlowLayout
FlnwLdyoui
Syntax
public class FlowLayout implements LayoutManager, Serializable
Description
The flow layout manager places components in
rows in lefl-lo-righl. top-to-botlom order. When a
component cannot be placed on a row without
being clipped, a new row is created. The compo-
nents are centered vertically on each row.
C omponent Alignment
A flow7 layout has an alignment property that
determines how each row distributes empty
space. The alignment can be one of three values:
LEFT CENTER, or RIGHT. A flow las out w ith left
FlowLayout E xample ВЕЗ E3
RIGHT |
CENTER | 4| 5|
FIGI KF 135: FlowLayout.
alignment moves the empty space to the right of the row. thereby moving all of the compo
nents left. A flow lav out with right alignment moves the empty space to the left. A How layou
with center alignment divides the empty space and distributes it al the left and right ends of thi
rows, thereby centering all the components.
(raps
The flow layout manager allows you to separate lhe components with gaps. The vertical gap
specifies lhe space between rows, while the horizontal gap specifies the space between compo-
nents.
The vertical and horizontal gaps are also applied around the edges of the container. It you
do not want this space, you can eliminate it only by subclassing lhe container and overriding
its insetsO method. The override should retrieve the peer's required insets (it a peer exists),
subtract the vgap and hgap from the peer's insets, and return (he result. Doing this might make
the insets negative, but it will eliminate the gaps around lhe edges.
mber summary
Constructor FlowLayoutO Creates new FlowLayout instance.
Alignment Methods and Constants r A
CENTER Alignment constant specifying center alignment. В
getAl ignmentO Retrieves the alignment of components using this layout.
LEFT Alignment constant specifying left alignment. V i
RIGHT Alignment constant specifying right alignment. D
setAl ignmentO Sets the alignment of components using this layout. | E
Layout Manager Methods
addLayoutComponentO A no-op. 1
1ayoutContai ne r () Lays out the container's components according to the set । G
lings of the layout manager. ( It
mi ni mumLayoutSi ze О Calculates the minimum dimensions needed to lay out the
components. 1 1
preferredLayoutSizeO Calculates the preferred dimensions needed to lay out the 1 J
removeLayoutComponentО components. 1 A no op. ( К
Gap Methods J,
getHgapO Retrieves the horizontal gap between components. 1 M
getVgapO Retrieves the vertical gap her ween components. (
setHgapO Sets the horizontal gap between components. N
setVgapO Sets the vertical gap between components. | О
Debugging Method i P
toStri ng() Generates a string representation of the layout manager's i
— state. 1 R c
See Also T
BorderLayout, CardLayout, GridLayout, GridBagLayout, java.io.Serializable. c
V
Example
This example creates a frame with a flow layout manager (see Figure 135). Three buttons
labeled LEI F. CENTER. and RIGHT control the alignment of the flow layout. A list compo- X
nent is added to the container to introduce a different height in the row to show that the compo- Y
nents in a row' are centered vertically.
import java.awt.";
import java.awt.event
FlowLayout
java.awt
class Main extends Frame implements ActionListener {
FlowLayout layout new FlowLayout(FlowLayout.RIGI
Main О {
super(“FlowLayout Example”);
List list = new L i st();
A setL ayout(1ayout);
Button b;
В add(b - new Button(“LEFT”));
b.addActionLi stener(thi s);
C list.addltem(°l1st”);
add(list);
D add(b - new Button(“RIGHT”));
b.addActionLi stener(thi s);
E add(b = new Button(“CENTER"));
b.addActionLi stener(this);
add(new Button(”4”));
G add(new Button('l5"));
It setSize(100, 200);
show();
I }
J public void actionPerformed(ActionFvent evt) {
String what - evt .getActionCommandO;
К
if (“LEFT”.equals(what)) {
L layout.setAlignment(Flowlayout.LEFT) ;
} else if (“CENTER".equals(what)) {
M layout.setAlignment(Flowl ayout.CLMER);
} else if (“RIGHT”.equals(what)) {
N layout.setAlignment(FlowLayout.RIGHT);
}
О
Stri ng 1abel;
P swi tch(layout.getAl ignmentO) {
case FlowLayout.LEFT:
Q label - “left”;
break;
R case FlowLayout.CENTER:
label - “center";
S break;
case FlowLayout.RIGH1;
T label = “right";
break;
U default:
label - “example”; // impossible
V }
setTitle(label);
W
inval idateO ;
X val idateO;
}
Y
public static void main(String[] args) {
Z new MainO;
}
}
620
addLayoutComponent)
pURPOSf: A no-op.
SYNTAX public void addLayoutComponent(String name. Component comp) A
DESCRIPTION .A This method is called by the container when a component is added along with a name. However, component names are ignored by ihe flow layout manager. B so this method does nothing. This method needs to be defined in order to sal- c isfy the LayoutManager interface.
parameters comp The non-nul 1 named component that has just been added to the container Ignored. Щ
name The name of the component. Ignored. G
CENTER H I
PURPOSE Alignment constant specifying center alignment. J
SYNTAX public static final int CENTER &
DESCRIPT ION The center alignment causes all of the components in a row to be packed L together and centered. M
EXAMPLE See the class example. N
о
FIowLayout() P
------ ----- ---- ---------------- ------ ------ Q
PURPOSE Constructs a new FlowLayout instance.
SYNTAX public FlowLayoutQ public FlowLayout(int align) $ public FlowLayout(int align, int hgap, int vgap) T
DESCRIPT ION This constructor constructs a new flow layout manager instance with the align- и ment align and the gaps hgap and vgap. If the alignment is not specified, it defaults to CENTER. If the gaps are not defined, they both default to 5. An instance of the flow layout manager can be shared by more than one con- tainer. Also, the flow layout manager can be set on a container at any time. x regardless of the number of the components already in the container.
PARAMETERS al ign hgap The alignment, which must be one of LEFT. CENTFR. or RIGHT. A non-negative integer specifying the horizontal gap in pixels.
Пои Layout
geiAlignmenH )
java.aw t
vgap A non-negatixe integer specif) ing the \ ertical gap in pixels.
si.i. also setAl i gnment () , setHgapO, setVgapO.
i a wipi i See the class example.
B getAlignmentl)
c pi rposi- Retriexes the alienment of components usiiva this lax out. n
sxxixx public int getAlignmentО F.
dl.sc ripi io.\ ?>ee me ciass description юг details on alignment ot components using a now
lax out.
G rl:ti rxs The alignment of components using this lax out: one of LEFT. RIGHT, o- LEN-
II TER.
1 sit \i so setAl i gnment О.
I Lx wipi.i. See class example.
к
1 getHgapO
M
pi'Rposi- Retriexes the horizontal gap between components. \T
sxxiw public int getHgapO
u di sc ripiiox I’hc horizontal gap is initialized bx the FlowLayout constructoi and changed
p using setHgapO. See the class description for details • on horizontal gaps
Q ri и rxs A non-negatixe integer specifying the horizontal gap ii i pixels.
R si i \i so getVgapO, setHgapO.
S i \ wipi i This example creates a frame w ith а
вив||
j. How lax out manager (see Figure
136). Four buttons labeled V+. \-. List
control the \ ertical and LEFT |
V horizontal gaps ol the flow lax out.
Two other buttons arc used to displax
\\ the current \ ertical and horizontal RIGHT ! 1 CENTERI <14
x gaps in effect.
Y
1 Id RI 136: Xertical and horizontal
/ import java.awt.-; naps in a FlowLayout.
import java, awt. event;
class Main extends Frame implements ActionListener {
622
FlowLayout layout - new MowLayoutO lowLayout .CFNTFR);
Button vgapbtn, hgapbtn;
MainO {
super(“Mowl ayout Gaps Example”);
List list = new ListO ;
setLayout(layout);
Button b;
add(b = new Button (“V+’1));
b.addActionli stener(thi s);
li st.add!tem(“List”);
add(list);
add(b = new Button('‘Ht”));
b.addAct ionLi stener(this);
vgapbtn = new Button("Vgap=”-*layout,getVgapO) ;
add(vgapbtn);
add(b new ButtonCV-”));
b.addActionListener(this);
hgapbtn =? new Button(“Hgap=” fl ayout .getHgapO) ;
add(hgapbtn);
add(b = new Button(“H-”));
b.addActionListener(this);
setSize(100, 200);
showO;
}
public void actionPerformed(ActionEvent evt) {
String what = evt. getActionCommandO;
if (“H+’’ .equals(what)) {
layout. setHgapOayout. getHgapO4-5) ;
} else if CH-” .equal s(what)) {
layout.setHgap(Math.max(0, layout.getHgapO-5)) ;
} else if (“V-t".equals(what)) {
layout. setVqap(layout .getVgapO *5);
} else if (“V-”.equals(what)) {
layout.setVgap(Math.max(0, layout.getVgap()-5));
}
vgapbtn. setLabel (“Vgap-”4-l ayout. getVgapO)i
hgapbtn. setLabel (“Hgap-”-layout .getHgapO);
inval idateO ;
vali date();
}
public static void mai n(Stri ng[] args) {
new Mai n();
FlowLayout java.awt
geiVgapl)
getVgapO
Pl'RPt ISE Retrieves the vertical gap between components.
A SYNTAX public int getVgapO
DESCRIKIION Ehe vertical gap is initialized by the FLowLayout constructor and changed
В using setVgapQ. See the class description for details on vertical gaps in a
C flow layout.
D RETURNS A non-negative integer specifying the vertical gap in pixels.
E SEE ALSO getHgapQ, setVgapQ.
EXAMPLE See getHgapQ.
G
H layoutContainer()
I J PURPOSE Lays out the container’s components according to the settings of the layout manager.
К SY VI AX public void 1ayoutContainer(Container cont)
1 DESCRIPTION This method is called by the container cont when the layout is invalidated and
M needs to be redone. In placing the components, the flow layout manager sets the width of the row s to be the current width of the container and resizes the
N components based on their preferred sizes.
() PARAMETERS
P cont The non-nul 1 container using this layout instance.
Q SEE/ALSO Contai ner.
R 1-A AMPLE See LayoutManager.1ayoutContainerQ.
S T LEFT
i: V Pl RPOSL Alignment constant specifying left alignment.
SYNTAX public static final int LEFT
w DESCRIP11ON The left alignment causes all of the components in a row to be packed together
X and moved against the left edge of the container.
Y EX AM PI E See the class example.
z
624
minimum Lay outS ize()
PURPOSE Calculates the minimum dimensions needed to lay out the components.
SYNTAX public Dimension minimumLayoutSize(Container cont)
DESCRIPTION A This method calculates the minimum dimensions needed to lay out the compo- nents in lhe container cont. The minimum dimension of a flow layout is based B on a layout of a single row. More precisely, the minimum dimension is caicu- c lated by determining each visible component's minimum size. The height of the result is determined by the maximum height of these minimum sizes plus 2 times the vertical gap plus any insets required by the container. The width of E the result is the combined width of all of the minimum widths plus (number- of-components + 1) times the horizontal gap plus any insets required by the ™ container. G
parameters cont H The non-null container using this layout instance. 1
RETURNS A non-null Dimension object containing the minimum size of the flow lay- j K
SEE ALSO Component.getMi nimumSizeO , preferredLayoutSizeQ.
L
M
preferredLayoutSize() M
purpose Calculates the preferred dimensions needed to lay our the components. О
syntax public Dimension preferredLayoutSize(Container cont) P
description This method calculates the preferred dimensions needed to lay out the compo Q
nents in the container cont. The preferred dimension of a flow layout is based
on a layout of a single row. More precisely, the preferred dimension is calcu-
lated by determining each visible component s preferred size. The height of $
lhe result is determined by the maximum height of these preferred sizes plus 2 T
times the vertical gap plus any insets required by the container. The width of
the result is the combined width of all of the preferred widths plus (number-of-
components + 1) times lhe horizontal gap plus any insets required by the con v
tainer. W
parameters X
cont The non-nul 1 container using this layout instance.
returns A non-null Dimension object containing the preferred size of the flow lay-
out.
SEE At,so Component.getPreferredSize(), minimumLayoutSize().
blow Layout
removeLayoutCornponenU)
ja\ a.aw t
removeLayoutCom ponent()
purpose This method is a no-op.
symax public void removeLayoutComponent(Component comp)
Л description This method is called by the container comp whenever a component is
В removed from comp. Since the flow layout manager ignores component names,
this method docs nothing. It needs to be defined in order to satisfy the Lay-
outManager interface.
D
PARAMETERS
comp The component about to be removed from the container. Ignored.
G
H 1 RIGHT Pl RPOSE Alignment constant specifying right alignment.
J SYMAX public static final int RIGHT
к [ DESCRIPTION The right alignment causes all of the components in a row to be packed together and moved against the right edge of the container.
EXAMPLE See the class example.
M X
0 set Alignment)
p PI RPOSE Sets the alignment of components in this flow layout.
Q SYNIAX public void setHgap(int hgap)
R DESCRIPTION This method sets the alignment of components in this layout to be al ign. See
s the class description regarding alignment in flow layouts.
T PARAMETERS
I • align One of LEFT. RIGHT, or CENTER.
SEE ALSO getAlignment().
V w EXAMPLE: See the class example.
X
Y setHgapO
z PURPOSE Sets the horizontal gap between components.
SYNTAX public void setHgap(int hgap)
626
DESCRIPTION This method sets the horizontal gap of this layout to be hgap. See the class description for details on the use of gaps in flow layout.
parameters hgap SEE ALSO example setVgapO^ A non-negative integer specifying the horizontal gap in pixels. A getHgapQ , setVgapQ. В See getHgapQ. C I) E
PURPOSE Sets the vertical gap between components.
syntax public void setVgapQ nt vgap) G
DESCRIPTION This method sets the vertical gap of this layout to be vgap. See (he class H
PARAMETERS vgap SEE ALSO EXAMPLE description for details on the use of gaps in How layout. ? J A non-negative integer specifying the vertical gap in pixels. к getVgapQ, setHgapQ. See getHgapQ. L
toStringO M N _ c
purpose Generates a string representation of the layout manager’s state. p
syntax public String toStringO t
description This method generates (he string representation of this layout manager’s state. R
The string contains the layout manager s class name, the size of the two gaps,
and the alignment.
q
This method is typically used for debugging.
Returns A non-nul 1 string representing the layout manager's state.
overrides java.lang.Object. toStringO. '
v
example See java.1ang.Object.toStringQ.
)
java.awt.event
FocusAdapter
A - | Rectangle
В
c
Syntax
public abstract class FocusAdapter implements FocusListener
E
M Description
G The focus adapter is a focus listener where all callback methods are empty implementations.
The purpose of the focus adapter is to make it more convenient for an object to listen for focus
H events. In particular, by using the focus adapter, you can implement only those callback meth-
I ods in which you are interested. Without the focus adapter, you are required to implement all
j callback methods, even if the method is empty.
To use a focus adapter, you create a subclass of FocusAdapter and override the desired
К callback methods. You then create an instance of the focus adapter subclass and call the com
L ponent’s addFocusListenerО method with it. The focus adapter subclass is typically an
inner class.
M
P
MEMBER SUMMARY
! Focus Event Callback Methods
: focusGainedf) Called when this component gains the focus.
focusLostO Called when this component loses the focus.
1 See Also
t,! FocusEvent, FocusListener, java.awt.AWIEventMulticaster,
java.awt.Component.addFocusLi stener О.
v
w
x
Y
628
Example
This example demonMrates how to use a focus adapter to
listen for focus events. The example creates a text area
and a focus adapter. It registers the focus adapter with (he
text area. When the adapter receives a focus event, it
prints the specifics of the event. See Figure 137.
import java.awt.*;
import java.awt.event.~;
class Main extends Frame {
MainO {
super('’FocusAdapter Example”);
TextArea ta - new lextAreaQ;
* FocusAdapter Ex... МЕ1П
Focus adapters are convenient. zJ
Ы J
MGl RE 137: FocusAdapter.
E
// Listen for focus events.
ta.addFocusListener(new FocusEventHandlerC));
add(ta, BorderLayout.CENTER);
pack();
show();
}
class FocusEventHandler extends FocusAdapter {
public void focusGained(FocusFvent evt) {
System.out.print 1n("FOCUS GAINFD: "
+(evt.isTemporaryO ? "temporary" : "permanent"));
}
public void focusLost(FocusEvent evt) {
System.out.println("FOCUS-LOST: "
4 (evt. i slemporaryO ? "temporary" : "permanent"));
}
}
public static void main(String argsH) {
new Mai n():
A
В
C
D
E
О
H
I
J
К
L
M
\
О
p
Q
L>
java.awt.cvcnt
FocusAdapter
focusGained()
focusGainedO
PIRPOSE Called when this component gains the focus.
SYNTAX public void focusGained(FocusEvent evt)
DESCRIPTION This method is called after the source component has gained the focus. This method, by default, has an empty implementation.
PARAMETERS evt The non-nul 1 focus event.
EXAMPLE See the FocusEvent class example.
focusLostO
PIRPOSE Called when this component loses the focus.
SYNTAX public void focusLost(FocusEvent evt)
DESCRIPTION This method is called after source component loses the focus. This method, by default, has an empty implementation.
PARAMETERS evt The non-nul 1 focus event.
EXAMPLE: See the FocusEvent class example.
630
FocusEvent
)
Syntax j
public class FocusEvent extends ComponentEvent
К
Description 1
The focus or keyboard focus is a property of a component and determines where keyboard M
events are delivered. At most one component in the entire system can have the focus.
A component gains the focus in one of three wavs:
О
1. The component can call Component. requestFocusO.
2. The user can interact with the component. p
3. The user can hit the Tab or Shift-Tab key to move the focus from component to compo- q
nent.
R
See Component for more information about the focus. S
All components can fire focus events. A component that loses the focus fires a
FOCUS_LOST event. A component that gains the focus fires a FOCUS_GAIN event. A component
that fires a FOCUS-GAIN event will subsequently fire a FOCUS_LOST event. Since there can be U
only one component with the focus at any time, the component with the focus will fire a v
FOCUS_LOST event before the component receiving the focus will fire a FOCUS_GAIN event.
Listening for Focus Events X
To listen for focus events from an component, the listener must implement the FocusLis-
tener interface. After that, the listener must be registered with the component. It becomes
registered by calling the component's addFocusLi stenerO method. Z
An alternative, and possibly more convenient, way of receiving focus events is to use a
focus adapter. See FocusAdapter for more details.
FocusEvent
java.awt.event
A
В
C
D
G
H
I
J
К
L
V1
N
О
P
Q
R
S
T
U
V
W
X
Y
Z
As with most events, focus events are delivered to its listeners after the operation has
taken place.
Focus Levels
A FOCUS_LOST focus event can have one of two focus level: temporary or permanent. In gen-
eral, if a component fires a temporary FOCUS_LOST event, it is because some operation tempo-
rarily look away the focus and it will restore the focus when it completes. The exact operations
for which temporary FOCUS .LOST events are fired vary by platform. However, the usual situa-
tion are when component .4 loses the focus to component В in another top-level w indow. In
this case, when the focus is restored to A's window, component A will gain the focus. In fact, if
the users clicks a different component in component A\ window, component A will gain the
focus (and fire a FOCUS—GAIN event) and immediately lose it (and fire a FOCUS_LOST event) to
the other component.
In short, when a component fires a FOCUS
FOCUS-CAIN event before any other component in t
The main purpose of the temporary
FOCUS-LOST event is to allow' a component to
visually indicate (for example, in Windows 95. by
a dotted surround) that if the focus was to be
restored to its containing window; that component
would receive the focus.
In general, a component fires a permanent
FOCUS.LOST event when it loses the focus to some
other component in the same window. The exact
ways in which this can happen depend on the plat-
form. Typical ways are when another component
calls Component. requestFocusO or w'hen the
user moves the focus by pressing the Tab or Sliift-
Tab key.
All FOCUS_GAIN events are permanent.
Focus Event Flow
Figure 138 shows how focus events typically flow
through the system. First, the event is fired by a
component peer in response to some user gesture.
This event is posted on the event queue (see EventQueue). When the event makes its way to
the front of the queue, it is given to the component via its di spatchEventO method. The
main purpose of this method is to discard the event if the focus event type is not enabled or if
there are no focus event listeners. Otherwise, dispatchEventO calls processEventO.
which in turn calls different methods depending on the event type. Since this is a focus event.
processFocusEventO is called. The main purpose of this method is to notify the focus event
listeners.
.LOST event, it
he same window.
ComponentPeer
System
Event
Queue
guaranteed to fire a
FocusEvent
J
Component I processEventO
1 4
^processFocusEventOJ
T — '
FocusListener v
0
FIGURE 138: Focus Event Flow.
632
A component can override p rocessFocus Event О to process focus events before they
are delivered to its listeners. The overridden method should call super.processFocus
Event О to ensure that events are dispatched to the component's listeners.
MtyER SUMMARY
Constructor FocusEventO Constructs a FocusEvent instance.
Focus Level Method isTemporaryO Retrieves (he focus event's focus level. |
Item Event Constants FOCUS_FIRSГ FOCUS-GAINED FOCUS_LAST FOCUS.LOST 1 Constant specifying the first id in the range of focus event ids. Event id indicating that the component has gained the focus. Constant specifying lhe first id in the range of focus event ids. ' Event id indicating that (he component has lost the focus. 1
Debugging Method paramString() Gene rate s a stri ng re pre sentin g (he foe u s event 4 stat e.
See Also
FocusAdapter, FocusLi stener,
java.awt.AWTEvent, java.awt.Component.
Example
This example demonstrates how to get focus events from a
component that fires them. The example creates a text area
and listens for focus events from the text area. In response
to a focus event, lhe specifics of the event are printed. See
Figure 139.
This example could have been implemented using a
focus adapter. To see how this is done, see the Focus-
Adapter class example.
к FocusEvent Ex ।
Focus events can be
"temporary or
"permanent'
FIGI’RE 139: FocusEvent.
import java.awt.*;
import java.awt.event;
A
В
C
D
E
и
G
H
1
J
К
1.
M
N
C
F
L
F
5
1
I
x
\
class Main extends frame implements FocusListener {
Main() {
super(‘'FocusEvent Example");
TextArea ta = new TextArea();
// Listen for focus events,
ta.addFocusLi stener(thi s);
FocusEvent
FOCLSJ1RST
java.awt .event
addfta, BorderLayout.CENTER);
pack О ;
show О;
}
Л public void focusGained(FocusEvent evt) {
System.out.print"ln("FOCUS-GAINED: "
В -t (evt. i sTemporaryO ? "temporary” : "permanent"));
}
C public void focustost(FocusEvent evt) {
System.out.println("FOCUS-1 OST: "
D ♦ (evt. i slemporaryO ? ’'temporary" : "permanent"));
}
E
public static void main(String args[]) {
new Mai n();
G }
H
I
, FOCUSJFIRST
К Pl RPOSE Constant specifying the first id in the range of focus event ids.
L SYNI XX public static final int FOCUS_FIRST
M N О P description All action event ids must be greater than or equal to FOCUS_FIRST (value 1004). SLL also FOCUS_LAST. EX/XMPLL See java. awt.Component.processEventO.
Q R FOCUS GAINED
S PI RPOSE Event id indicating that the component has gained the focus.
T SYNTAX public static final int FOCUS-GAINED
L V description A focus event with this event id (value 1004) indicates that the event s source has gained the focus.
W SEE Al so FocusEventC).
X EXAMPI F See the class example.
Y
7. FOCUS. .LAST _ _
Pl RPOSE Constant specifying the last id in the range of focus event ids.
634
SYNTAX public static final int FOCUS_LAST
description All action event ids must be less than or equal to FOCUS_LASf (value J 005).
see ALSO FOCUS-F1RS1.
example See java.awt.Component.processEventО A
В
FOCLS LOST________________________________ __ ____ 1
D
PURPOSE Event id indicating that the component has lost the focus. i:
SYNTAX public static final int FOCUS-LOST
DESCRIPTION A focus event with this event id (value 1005) indicates that the event’s source
has lost the focus.
SEE AL.SO FocusEventO. H
EXAMPLE See the class example. J
J
FocusEventO
— — — — — _ — — — — — L
purpose Constructs a FocusEvent instance.
syntax public FocusEvent(Component source, int id)
public FocusEvent(Component source, int id, boolean temporary)
description This constructor creates a new focus event with source as the component fir- (
ing this event. If temporary is not specified, it defaults to fal se. See the class F
description for more information about temporary focus events.
After the focus event is created, the source object can distribute the event to its
listeners by calling the focus event-related methods in AWTEventMulti-
caster. If the event is not created by source, the creator can deliver the event *
to the source component either by posting the event to the event queue (see
EventQueue.postEvent()) or by calling the source component's Compo-
nent - di spatchEventO method directly.
parameters
source The non-nul 1 object that is firing this focus event. >
id One of the focus event ids.
temporary true if the focus event is to be temporary; fal se otherwise.
SEE also i sTemporaryO , java. awt .AWTEvent .getIDO ,
java.util.Eventobject .getSourceQ-
java.awt.eve nt
roeusEvent
isTemporaryt)
isTemporaryO
purpose Retrieves the focus event's focus level.
SYNTAX public boolean isTemporaryO
DESCRIPTION See the class description for more details about focus levels.
RETURNS true if the event’s focus level is temporary; false otherwise
example: See the class example.
purpose Generates a string representing the focus event's state.
H SYMAX public String paramString()
I DESCRI PHON The returned string contains the name of the focus event and w hether the event
J is temporary or permanent. A subclass of this class should override this method and return a concatenation of its state with the results of
К super.paramString(). This method is called by the
L AWTEvent. toStri ngO method and is typically used for debugging.
M RE1LRNS A non-null string representing the focus event's state.
N O\ ERRIDES java.awt.AWTEvent.paramString().
0 SEE ALSO java.awt.AWTEvent.toStri ngO♦ java.lang.Objeer.toStri ng().
P EXAMPLE Seethe java.awt .AWTEvent class example.
Q
R
S
T
u
V
X
Y
7.
636
FocusListener
N
Syntax 0
public interface FocusListener extends EventListener
i>
Description Q
When an object (listener) wishes to receive focus events from a component that tires them (the R
source component), two things must be done: $
1. The listener must implement this interface and all of the methods required by this inter-
face.
2. The listener must be registered with the source component by making a call to the source L
component’s addFocusLi stenerO method. v
For more information about component events, see FocusEvent. w
___________________________________________________________________________ X
Focus Event Callback Methods z
focusGai ned() Called after the source component gains the focus.
focusLostO Called after the source component loses the focus.
java.awt.eve nt
EocusListener
focusGainedO
See Also
FocusAdapter, FocusEvent, java.awt.AWTEventMulticaster,
java.util.EventListener.
Example
See the FocusEvent class example.
focusGainedO
pi rpose: (’ailed after the source component gains the focus.
SYNTAX public void focusGained(FocusEvent evt)
DESCRIPTION This method is called after the source component has gained the foi
PARAMETERS evt The non-nul 1 focus event.
E;X AMPLE* See the FocusEvent class example.
focusLost()
PI’RPOSEi Called after the source component loses the focus.
SYNTAX public void focusLost(FocusEvent evt)
DESCRIPTION This method is called after source component loses the focus.
PARAMETERS evt I'he non-nul 1 focus event.
EXAMPLE: See the FocusEvent class example.
638
Syntax
public class Font implements Serializable
Description
A font determines how text looks when it is painted. In particular, a font is used when painting
text on a Graphics context and as a property of AWT components. A font has three properties
that contribute to the appearance of the text: the logical name, the style, and the point size. The
properties of a font are specified at the time the font is created; they cannot be changed later.
At present, the AWT system supports only a very small set of fonts and does not allow
your program to access the fonts on your system. This restriction ensures that the fonts used by
a program will look the same on all platforms. However, this restriction will be relaxed in a
future release.
The Default Font
The font of an AWT component can be changed at any time. If an AW'T component has a font
whose value is null, the component will inherit its font from the closest ancestor whose font
is not null.
Logical Font Name
The logical font name determines the shape of the font characters. Hor example, the logical
name SansSerif specifies a font that has variable-width characters, while Monospaced speci-
fies a font that has fixed-width characters. Ifiese logical font names are mapped into real font
names on your system. For example, on Windows, SansSeri f is mapped to Ari al.
The method Toolkit.getFontListO returns a list of valid logical font names. Cur-
rently, the supported logical font names are Serif, SansSerif, Monospaced, Dialog, and
Dialoginput. The use of the logical names TimesRoman, Helvetica, Courier, and
ZapfDingbats is deprecated but still supported. Figure 140 shows a window that displays text
in each of these logical font names. The Font class provides methods and variables to retrieve
the properties of a font.
Font Style
A font’s style determines the weight (thickness) and slant of the font. The font style is really a
combination of style bits. The plain style bit specifics a normal weight font with no slant. The
bold style bit specifies a heavyweight font. The italic style bit specifies a font with slanted
Font
java.awt
characters. I’hc bold style bit can be combined with the italic style bit. Figure 140 shows text
in various font styles.
Font Point Size
A font's point size determines the
size of the font. One point is
approximately 1/72 of an inch.
Although the AWT system tries to
map the logical font names to scab
able fonts, the process isn't guaran-
teed to succeed. So some requested
point sizes may end up being
mapped to a different point size. To
ensure your painting code will
work on all platforms» you should
always retrieve and use a font's
metrics when painting text in the
font (see FontMetrics).
Font Family
I’hc font family is a platform-
specific font name. The platform-
independent logical name is auto-
matically translated to the font fam-
ily at the time the Font object is
created. The font name-to-font
family translation map is specified
via system properties: it cannot be
specified when the Font object is
created.
Font System Resources
The Font object is only a specifica-
tion for a font. The actual font sys-
tem resource that the platform uses
to render text in a specified font is
created only when needed. These
system resources are automatically
managed and in fact cannot be
. Font Example ____________________ВИйТЕЗ
Dialog bold {Dialog)
Dialog bold-ttalic (Dialog)
SansSenf plain (SansSenfl
Sanserif (SansSez/7)
SansSeiif bold (SansSeiif)
SansSerif bold-italic (SansSerif)
Serif plain (Senfi
ttahc (Senj)
Serif bold (Serif)
Sferif bold-italic (£erif)
Monospaced plain (Monospaced)
Monospaced italic (Mo?2ospeced)
Monospaced bold (Monospaced)
Wozios-paced bold-italic (Monospaced)
Helvetica plain (Helvetica)
HeAzet/ca rta//c (HeA/efrca)
Helvetica bold (Helvetica)
Helvetica bold-italic (Helvetica)
T nne sRoman plain (T ime sRoman)
ТзтяегВотлдя зУдйс (ТУтезйоюди.)
TimesRomatt bold (TiitiesRoitian)
TVmefRowan bold-italic (TimesRoNtan)
Courier plain (Courier)
Courier italic (Courier,}
Courier bold (Courier)
Courier bold-italic (Coii-tier)
Dialoginput plain (Dialoginput)
DialogZziput italic (Di alogclnpyt)
Dialoginput bold (Dialoginput)
BialogTnpu t bold-it alic (Dialoglnput)
« .e- «s' «««s' & « 4» «« «s' «s' & & & & «s & я
«««««««««««««««««««««««
FIGI RK 140: Font.
accessed via any AWT methods. You should not worry too much about trying to minimize the
creation of these Font objects.
640
Constructor pont() Constructs a new Font instance. property Methods and Fields getNameO Retrieves this font's logical name. getSizeO Retrieves this font s point size. getStyleO Retrieves this font’s style. i sBoldO Determines if this font is bold. isItalicO Determines if this font is italic. isPlainO Determines if this font is plain. , name Contains this font's logical name. size Contains this font's point size. style Contains this font's style. Style Bits BOLD This style bit is used in creating a bold style font. ITALIC This style bit is used in creating an italic style font. PLAIN This style bit is used in creating a plain style font. Font Methods decodeO Creates a font based on its font specification. getFarrri lyO Retrieves the plat form-specific family name of this font. . getFontO Creates a font based on the value of a system property. ! Peer Method getPeerO Retrieves this font's peer. General Methods equal s О Compares this object with another object for equality. hashCodeО Computes this font’s hash code. A В C D П G El I J К L M N О P Q R
toStri ng О Generates the string representation of the font. j s
See Also T и
FontMetrics, java.io.Serializable. V
w
Example x
This example creates a frame and displays in it all available fonts in all four possible font
styles (see f igure 140).
Z
import java.awt.*;
class Main extends Frame {
int[] styles = {
java.awt
Font
BOLD
Font.PLAIN, Font.ITALIC, Font.BOLD, Font.SOLDI Font.ITALIC};
Stringfl styleNames - {
“plain'’, “italic”, “bold”, “bold-italic”, “plai n-bol d-i tai i c"} ;
Main() {
super CFont Example”);
A
setSize(300, 400);
В show();
}
C
public void paint(Graphics g) {
D int у - 5;
E
(1
II
1
J
К
L
M
N
О
Stringf] fontNames = Toolkit.getDefaultToolkit().gethontList();
for (int i=0; i<fontNames.length; i+-0 {
for (int j-0; j<styles.length; j++) {
Font f = new Font(fontNames[i], styles[j], 13);
FontMetrics fm = g.getFontMetrics(f);
у fm.getAscentO ;
g.setFont(f);
g.drawString(fontNames[i j+” “+styleNames ГjJ
+” (”+f .getramilyO-t-”)”, 5, y) ;
у +- fm.getLeading();
}
У ♦ = 13;
static public void mai n(St ri ng[l args) {
new Mai n();
}
}
Q BOLD
R PURPOSE T his style bit is used in creating a bold style font.
S SYNTAX public static final int BOLD
T DESCRIPTION T his style bit can be or d with the ITALIC style bit to specify a bold-italic style
L font.
V SFF ALSO ITALIC, PLAIN, getStyleO, isBold().
w EXAMPLE These statements create a bold and bold-italic style font.
Font fl = new Font(‘‘Di alog”, Font.BOLD, 12);
Font f2 = new Font(“Dialog”, font.BOLD|Font.ITALIC, 12);
642
decodeO_____________________________________________________
purpose Creates a font based on the font specification.
SYNTAX public static Font decode(String fontSpec)
л
description* This method creates and returns a Font object as specified by the font specifi-
cation fontSpec. fontSpec is a string with the following form: F
<logical font name>-<style>-<point size>
Each of the three font properties are separated by a short dash (-). The logical
font name must be one of the valid logical font names (see the class descrip- 1
tion). The style can be one of plain, italic, bold, or bolditalic. The I
point size can be any positive integer. Table 13 shows some examples of font И
specifications and their equivalent constructor statements.
(
Font Specification _ Equivalent Constructor Statement 1
Monospaced-bold-14 new Font(“Monospaced", Font.BOLD, 14) 1
Monospaced-plain new Font(“Monospaced”, Font.PLAIN, 12)
Serif--18 new FontC'Serif”, Font.PLAIN, 18) F
SansSerif new FontC'SansSerif", Font.PLAIN, 12) 1
Dialog-boldi talic-16 new Font(“D1alog”, Font.BOLD|Font.ITALIC, 16) у
TABLE 13: Examples of Font Properties.
(
The logical font name is required, but the style and point size are optional. If I
the style is not specified or is blank or invalid, plain is assumed. If the point
size is not specified, 12 is assumed.
If the system property propName is not defined and defaultFont is specified, *
default Font is returned. Also, if there is some error in the font specification, ’
defaul tFont is returned. However, if both the system property and defaul t-
Font are not specified, null is returned.
parameters
fontSpec A non-nul! string specifying the font.
returns A Font object or nu 11.
SEE also Font(), getFontO.
example This example creates a bold 14-point monospaced font.
Font f = Font.decode(“Monospaced-bold-14”);
java.awt
Font
equa]s()
equals()
pi RPOsi- Compares this object with another object for equality.
syntax public boolean equalsfObject object)
description Two font objects are equal only if their logical names, styles, and point sizes
В are equal. This method returns true if the two fonts are equal. If they are not
c equal or if object is null oris not of class Font, this method returns false.
D PARAMETERS
object The object with which to compare.
| returns true if the objects are equal; fal se otherwise.
overrides java.1ang.Objoct.equals().
G
t-xample This method displays a string. The specified font is selected into the graphics
H context only if it differs from the currently selected font.
1
Font curFont;
j void paintString(Graphics g, Font f, String s) {
if (!curFont.equals(f)) {
К g.setFont(f);
curFont - f;
L }
g.drawString(s, x ty);
M >
N
О
P
Q
R
S
T
U
V
w
X
Y
Z
Font()
purpose Constructs a new Font instance.
syntax public Font(String name, int style, int size)
description This method constructs a new font (and its peer) with the specified logical
name, style, and point size. The logical name of the font must be one of
Dialog. Dialoginput. Monospaced, Serif. SansSerif, or Symbol. If name
is not one of these, a default font is chosen. The actual font chosen is platform-
dependent.
l he new Font instance can be used in more than one AWT object. For exam-
ple. you could set the font in a number of button instances.
PARAMETERS
name The font's logical name.
size The font's point size.
styl e The font's style.
deprecation The following logical font names have been deprecated. Courier is replaced
by Monospaced. TimesRoman is replaced by Serif. Helvetica is replaced by
644
SansSerif. ZapfDingbats is replaced by use of Unicode characters starting
at \u2700.
seealso Tool к i t.getFontListO.
example This code fragment creates a 36-point bold Serif font and sets it to two but- д
tons.
В
Font f = new Font(“Serif”, Font.BOID, 36);
Button bl * new Button("OK”);
Button b2 = new ButtonC'Cancel ”);
bl.setFont(f);
b2.setFont(f); _
getFamilyO G
‘ H
purpose Retrieves the font’s family name.
syntax public String getFamilyO
description The font family is the platform-specific font name that’s assigned to the font’s
logical name. The font family name is determined at the time the font is ere
ated and cannot be changed. L
returns The font’s family name as a non-null string. M
example This example prints out the family name for each available logical font name. N
import java.awt.*;
class Main extends Frame {
static public void main(String[] args) {
String[] fontNames = Toolkit.getDefaulttoolkit().getFontList();
for (int i=:0; i<fontNames.length; i++) {
Font f = new Font(fontNames[i], Font.PLAIN, 12);
System.out.println(fontNames[i] + ” > " f f .getFami ly()) ;
Output
Dialog -> Dialog
SansSerif -> SansSerif
Serif > Serif v
Monospaced -> Monospaced
java.awt
Г (Hit
getFontl)
Helvetica > Helvetica
TimesRoman > TimesRoman
Courier -> Courier
Dialogjnput -> Dialoginput
ZapfDingbats -> ZapfDingbats
В
getFontO
Ci
H
I
J
к
L
M
N
О
P
Q
R
S
T
U
V
w
X
Y
Z
HRPOSE Creates a font based on the value of a system property.
SYNTAX public static Font getFontfString propName) public static Font getFont(String propName, Font defaultFont)
DESCRIPTION The two forms of this method create and return a Font object associated with the system property name propName. The font specification in the system property value has the form described in decodeO. If the system property propName is not defined and defaultFont is specified. defaultFont is returned. Also, if there is some error in the font specification, defaultFont is returned. However, if both the system property and default- Font are not specified, null is returned.
PARAMETERS
defaultFont The font that is returned if the system property propName is not defined.
propName A non-nul 1 string specifying the system property name.
REIl'RNS A Font object or nul 1.
SEE ALSO decodeO , java, lang.System.getPropertyO.
EXAMPLE This example searches for a system property called “myapp.button.font” and creates a font based on the value of this property. If the property is not found, it returns a 12-point monospaced font.
Font f = Font.getFont(“myapp.button.font”, new Font(“Monospaced”, Font.PLAIN. 12));
getName()
PURPOSE Retrieves the font s logical name.
SYNTAX public String getNameO
DESCRIPTION The font's logical name is specified during the creation of rhe 1 ont object and cannot be changed.
RE 1 CRN'S The font's logical name as a non-nul 1 string.
SEE A1,SO Font, name.
646
geirucn I
EXAMPLE This example method returns true if the logical names for fl and f2 are the same.
boolean compareFontNames(Font fl, Font f2) {
return fl.gethameO .equals(f2 . get Name О ) ;
getPeer() _______
purpose Retrieves this font's peer.
SYNTAX public FontPeer getPeerO
description The font's peer is an internal object created and used by the underlying font machinery. This method should not be used and may be deprecated in the future.
RETURNS '('he possibly null font's peer.
SEE ALSO FontPeer.
getSizeO
PURPOSE Retrieves this font's point size.
SYNTAX public int getSizeO
DESCRIPTION The font's point size is specified during the creation of the Font object and cannot be changed.
RETURNS I'he font’s point size.
SEE ALSO Font.
EXAMPLE This example increases the point size of a font by 1 pt.
Font increasePointSize(Font f) {
return new Font(f. getNameQ , f.getStyleO, f. getSize() + l) ;
getStyleQ
PURPOSE Retrieves this font’s style.
SYNTAX public int getStyleO
DESCRI PTION The font style is a collection of font style bits. To test whether a style bit is included in the font style, use the bitwise “and" operator (see the example).
Font
hashCode()
java.awl
Phe plain style differs from the other style bits in that it is really the absence of
all style bits: hence, it has the value 0. So to test if the font style is plain, test it
against the value 0 (see the example).
A
В
C
L)
E
This method is typically used when saving lhe font style or using it to create
another font with lhe same style. When determining which style bits are
included in lhe font style, it is better to use the methods isBoldO.
isTtalicO, and isPlainf).
reti'Rxs The font's style.
sei-also IsBoldO, IsTtalicO, isPlainQ.
example This example retrieves the default font of a frame and prints its styles.
import java.awt.*;
G class Main {
static public void main(String[] args) {
H Frame f =- new FrameO;
f.packQ; // otherwise the default font is null.
1 int s « f.getFontQ getStyle() ;
*1 System.out.println(“plain: “ + (s =- 0));
System.out.println(“bold: “ i (fs&Font,BOLD) 0));
K System.out. pri ntln(“i tai i c: “ + ((s&Font. ITA1 1C) 0));
M
ОГТРГТ
\ plain: true
bold: false
q italic: false
Q hashCodef)
R pl’rpose Computes the hash code for the font.
S
syntax public int hashCodeO
T
description The font's hash code is an integer that's calculated from the font's properties.
C Two Font objects with lhe same properties will have lhe same hash code.
v However, two Font objects that do not have the same properties might also
have the same hash code, although lhe hash code algorithm minimizes this
w possibility. The hash code is typically used as the key in a hash (able.
X Note, it is not really necessary to cache Font objects, since they are reasonably
Y small. The actual system font resources contain all of the necessary informa-
tion for the system to paint text and so can be much larger. These are automat-
? ically maintained by the AWT system and cannot be accessed.
re i l'rns The font's hash code.
648
isiiOKH I
OVERRIDE java. 1 ang.Object.hashCodeQ.
seealso java . uti 1. Hash table.
example See j ava.1 ang.Object. equa 1 s ().
isBoldO _________ _ ___________
purpose: Determines if this font's style includes the bold style bit.
syntax public boolean isBoldO
returns true if this font’s style includes the BOLD style bit.
SEEALSO BOLD, Font О
example These statements remove a font’s bold style, if present.
if (f.isBoldO) {
f = new Font(f.getNameO , f. gctStyl e Q&-Font. BOLD, f .getSizeO);
}
isltalic()
purpose Determines if this font’s style includes the italic style bit.
syntax public boolean isItalicQ
returns true if this font's style includes the ITALIC style bit.
SEEALSO ITALIC, FontQ.
example These statements remove a font's italic style, if present.
if (f. isltal ic()) {
f = new Font (f.getNameO, f.getStyle()&-Font.ITALIC, f.getSizeO);
isPlain()
purpose Determines if this font's style is plain.
syntax public boolean isPlainO
Returns true if this font's style does not include any style bits besides PLAIN.
SEEALSO BOLD, FontC), ITALIC, PLAIN.
java.awt
Font
ITALIC7
example These statements force a font to be a plain style.
if ( ! f. i sPlainO) {
f = new Font(f .getNameO , Font.PLAIN, f.getSizeO);
}
A
В ITALIC
c PURPOSE Used in creating an italic style font.
D I- SYNTAX
public static final int ITALIC
DEM RIE’IION This constant can be or'd with the BOLD style bit to specif} a bold-italic style font.
G SET ALSO BOLD, getStyleO. isBoldO, PLAIN.
H l-XAMPLL These statements create an italic and a bold-italic font.
I Font fl = new ront(“Monospaced”, Font.ITALIC, 12);
J Font f2 - new FontC'Monospaced” , Font. BOLD I Font. HAL IC, 12);
К L name
M Contains this font's logical name.
PURPOSE
N
SYNTAX protected String name
О DESCRIPTION This field is accessible only by subclasses of Font. It is meant to be read-only
P and should not be changed.
Q SEE AL SO getNameO.
R S PLAIN _
T и PURPOSE This style bit is used in creating a plain font.
v SYNTAX public static final int PLAIN
w DESCRIPTION The PLAIN style bit isn’t really a style bit. It's actually the absence of all other style bits, which means it has the value 0. However, it's convenient to use
X when creating a plain style font.
Y SEE Al.SO BOLD, getStyleO, isPlainO, ITALIC.
Z FXAMPI I This statement creates a plain font.
Font f -= new Font (“Monospaced", Font. PLAIN, 12);
650
size
PURPOSE Contains this font's point size.
SYNTAX protected int size A
DESCRIPTIOS I’hc value in this field is identical to the one returned via getSizeO. This A
field is accessible only by subclasses of Font. It is meant to be read-only and в
should not be changed. c
SEE ALSO getSi ze(). D
style E
PURPOSE Contains this font's style. G
SYNTAX protected int style H
DESCRIPTION The value in this field is identical to the one returned via getStyleO. This 1
field is accessible only by subclasses of Font. It is meant to be read only and J
should not be changed. К
SEE ALSO getStyleO. L
M
toString() N
— .— -— — .— .— -— .— .— —. .— —. —. —. — — — —
PURPOSE Generates the string representation of this font. О
SYNTAX public String toString() P
RETURNS A non-null string representing the properties of this font (style, font family. Q
size, and name). This method is used for debugging output. R
OVERRIDES java. 1 ang .Object. toStri ngO. S
example These statements print a string representation of a font. T
Font f - new FontC'Monospaced” , Font. BOID'Font. [TALK, 12); I’
System.out.pri ntln(f.toString());
System.out.println(f): v
java.awt.peer
FontPeer
Л
B Syntax
C public interface FontPeer
D
Description
The Font class in the AWT is only a specification tor a font. The actual font uses the plat-
Щ form's native font system resource, which is represented by a font peer.
q AWT programmers normally do not directly use font peers. Instead, they deal with AWT
fonts using the Font class. These in turn automatically use and manage their peers. Only
H someone who is porting the AWT to another platform should be concerned with the font peer,
I
j See Also
j ava.awt.Font, j ava.awt.Toolki t.getFontPee гО•
К
I,
M
N
О
P
Q
R
S
T
и
V
w
X
Y
z
652
ics
Syntax
public abstract class FontMetrics implements Serializable
Description
A FontMetrics instance for a particular font
contains information about (he visual attributes
of the font, such as its height and character
widths.
Figure 141 shows the attributes of a font.
The values of these attributes are available
through its font metrics.
; leading
be.gh, Y V '
ф descent
FIGURE 141*. FontMetrics Attributes
Baseline
The baseline is an imaginary horizontal line that cuts through the characters in the font. The
bottom of the character ‘X\ for example, is aligned on the font's baseline. Characters with
descenders, such as the letter are aligned such that only the descender extends below the
baseline. When you are painting text of different font sizes, the text should be painted so that
their baselines connect.
Ascent
The ascent of a font is the distance from the top of the font to the baseline. The ascent is typi-
cally used to determine the location of the font's baseline. The font's ascent is not the same as
the maximum ascent of all the characters in the font. Some characters may extend beyond the
font’s ascent. The maximum ascent of all characters is called the Aw л maximum ascent and is
available in a font metrics.
Descent
The descent of a font is the distance from the bottom of the font to the baseline. The font's
descent is not the same as the maximum descent of all the characters in the font. Some charac-
ters may extend below the descent depth. The maximum descent of all characters is called the
fonts maximum descent and is available in a font metrics.
Leading
The leading is the spacing between rows of painted text. If the text were painted without the
leading, the rows would touch each other. When the ascent does not match the maximum
FontM etrics jaxa.aut
ascent or lhe descent does in the leading space. not match the maximum descent* parts of the charactci max appc.
Height
I'lic height of a lout is the sum ol the font’s ascent, descent* and leading. When puintii g low’
ol ie\1. xou should make the distance between baselines be the font's height. 'I he font's mav
mum height is the sunt of us maximum ascent, maximum descent, and leading.
MEMBER SLMVURY
Constructor Pontvot ric s Constructs a new lon:vetr irs instance
: Size Methods bytesWi dth() charswi dth() <* harvri dth О getwi dths() stri ngWi at hO Determines me width ol au atiax o’hxtcs. Determines the width ol an in rax ol ch.mulcts Rclncxesihe width of a ciiar; ctci hi the lout Ren iexes die width ol (he {;к chi.iinctcis m the lort. Deteiniincs the pixei widtn o* a <riag
Font Metric Attribute Methods
qetAccent() jetDescent ( ) lot dei qht(1 qet Leadi) ^etv-axAdvanc e( 1 ;jpt MaxAsc ent О qervaxDe$cent О Retriexcs die loin's jsccm Reiitcxcs inc hмн\ ccsccnt. Ren icxes die tout's rcighi Reibexcs the font's '.cjJiiie Reiriexcsuie w\hlio! the w idcst ctL.mcc: n the loin Reti icxcs die fora'-* гглтинч ascent Retfexcs the Ion;\ m.ixin rri J/sccrt
Voiit Fields and Methods
font qot: o^t f') 1 ac Ion: lio’P w tik It ria Ion; trettk s we-c icawi Rcii icxes ihc loin js/c. к» ctcalc 1 nr I »:it :n. 11 < s
1>еЬицц|11ц Method tobti i nq() (icnciates j sfaig icptcsc’H.. ю : o| ric :<• a rieiik s
Deprecated Method qervax?e<ent(' Repa^edhx qe t Max De sc. er t(!
See Also
^ont, java.’о.Seri a 1i/abIe
6>4
Example
This somewhat elaborate exam-
ple demonstrates how to dis-
play text in multiple font styles
and sizes. The text is input
from a file, and formatting
codes are embedded in the
text. The text is painted in a
default font, and the formatting
codes can change one attribute
of the font at a time—its name,
style, or size. Figure 142 shows
a screen shot of the example.
Figure 143 shows the input file
used to generate the screen
shot.
FontMetrics Example ИЕВ
The baseline is an I ГПЭС| IПЗ Гу
IlFlb thdt uuti-. through the characters I Fl the
font. The bottom of the character x , for
baseline. Characters with descenders such as the
letter у
descender extends below the baseline. When
painting text of different font sizes , the text should
be painted such that their baselines connect.
FIGURE 142: FontMetrics.
Input Format
A formatting code begins with the left angle character <. If the text that follows the < is a num-
ber, the current font si/c is changed to that number. If the code is <h. the font style is changed
to bold. If the code is <i. the font style is changed to italics. If the code is <p. the font style is
changed to plain. Otherwise, the font’s name becomes the text following the < character.
To make it clearer to see the rectangles in which each line of text is painted, the back-
ground of each line alternates between black and white.
Implementation Notes: The leading for text is displayed above that line, except for the first
line, which docs not have any leading. The leading used is the maximum leading for all of the
fonts that appear on that line. For simplicity’s sake, the text is parsed into words and format-
ting codes; all the words and formatting codes are kept in a Vector object.
< 15 <SansSerif The <i baseline <p <15 is an <32 <b
imaginary <15 <i horizontal <p line that cuts through
the <9 characters <15 in the font.
The bottom of the character <Monospaced X,
<SansSerif for example, is <32 aligned <15 on the font’’s
< i baseline. <p <15 Characters with <9 descenders <15 such as
the letter <Monospaced y. <SansSerif are <32 aligned
<15 such that only the ^b descender <p extends below
the <i baseline, <15 w'hen painting text of different
font sizes, the text should be painted such that their
< i baselines <p <15 connect.
FIGI RE 143: FontMetrics Example Input File.
FontMetrics
java.awt
import java.awt.*;
import java.io.*;
import java.util
class Main extends Frame {
Vector tokens - new VectorO;
Font defaultFont - new Font(“Serif”, Font.PL AIN, 12);
Main(String filename) throws lOException {
super(*TontMet ri cs Example”);
Streamfokenizer st
new StreamTokenizer(new FileReader(filename));
Font f - defaultFont;;
int t - st. nextTokenO ;
do {
switch (t) {
case ‘:
t = st. nextTokenO ;
switch (t) {
case StreamTokenizer.TT_NUMBER:
f = new Font(f .getNameO, f.getStyleO, (int)st .nva I);
break;
case StreamTokenizer.TT .WORD:
switch (st.sval.charAt(0)) {
case ‘b’:
f - new Font(f.getNameO , Font.BOLD, f.getSize());
break;
case ‘i *:
f = new Font (f.getNameO , Font.ITALIC, f.getSizeO);
break;
case ‘p’:
f - new Font(f.getNameO , Font.PLAIN, f.getSizeO) ;
break;
default:
f = new Font(st.sval, f.getStyleO, f.getSize()):
break;
}
}
tokens.addLiement(f);
break;
case StreamTokenizer,TT_WORD:
tokens.addElement(st.sval);
break;
case StreamTokenizer.TT_NUMBER:
tokens.addElement(Stri ng.valueOf((i nt)st.nval));
break;
case StreamTokenizer.T1_FOL:
break;
default:
tokens.addElement(St ring.valueOf((char)t)) ;
break;
}
t - st.nextTokenO ;
} while (t StreamTokenizer.TT_FOF);
setSize(300. 300);
showO ;
int line * 0;
656
void paintl ine(Graphics g, Font f. int start, int end,
int y, int ht, int at) {
// adjust for insets
int x = 0 + getlnsetsO left;
у += getlnsetsO . top;
A
FontMetrics fm =- g.getFontMetrics(f);
В
if (line+* % 2 -= 0) {
g.setColor(Color.black); C
g.fi1IRect(0, yr getSize()-width, ht) ;
g.setColorfColor.white); D
} else {
g.set€olor(Color.white); E
g. fil 1 Rect(0, y, getSizeO .width, ht); MB
g.setColor(Color.black);
}
g.setFont(f); G
for (int i=start; i<end; i + O {
Object tk = tokens.elementAt(i); H
if (tk instanceof Font) {
g.setFont(f - (Font)tk); I
fm g.getFontMetricsO ;
} else { J
g.drawString((String)tk, x, у + ас);
x i- fm.stringWidth((String)tk) + fm.charWidth(‘ ‘); K
public void paint(Graphics g) {
Insets insets = getlnsetsO;
int w - getSize().width-insets.left-insets.right;
Font f - defaultFont; О
Font startFont = f;
FontMetrics fm = g.getFontMetrics(f); P
g.clearRect(0, 0, w, getSize().height); Q
g.setFont(f);
R
int start 0, x = 0, у 0;
int ht - fm.getMaxAscentО + fm.getLeading(); $
int base fm.getMaxAscent();
line 0:
for (int i^0; i<tokens. size() ; i-н-) {
Object token = tokens.elementAt(i);
if (token instanceof Font) {
f - (Font)token;
g.setFont(f);
fm = g.getFontMetrics(f);
} else {
x *=: fm.stringWidth((String)token) ;
if (x > w) {
paintl ine(g, startFont, start, i, y, ht, base);
startFont - f;
start - i;
у +- ht;
x = ht = base = 0;
} else {
FontMetrics java.awt
bytesWidth()
if (у 5Я 0) {
ht = Math.maxfht, fm.getMaxAscent() + fm.getDescentQ);
base = Math.max(base, fm.getMaxAscent());
} else {
ht = Math.max(ht, fm.getHeightО ):
base - Math.max(base, fm,getAscent()*fm.getLeadingO);
}
x += fm.charWidth(‘ ‘);
}
}
}
paintl ine(g, startFont. start, tokens.size(), y, ht, base);
}
static public void main(String[] args) {
try {
new Kai n(args[0]);
} catch (TOFxception e) {
System.err.println(“usage: java Main <input.file>”);
}
}
bytes Width()
PURPOSE Determines the width of an array of byres.
SYNTAX public int bytesWidth(byte[] data, int offset, int count)
DESCRIPTION This method determines the width of count number of bytes in the byte array data starting at the index offset when displayed using this font merries. The bytes represent 8-bit characters. The bytes are converted to 16-bit chars and then supplied to charsWi dth () -
PARAMETERS count The number of bytes to consider, count + offset must be less than the length of data.
data offset The non-nul 1 array of bytes. The index of the first byte to consider in data; offset must be less than the length of data.
RETt RNS The pixel width of the bytes in data that are displayed.
SEE ALSO charsWidth() , stri ngWidthQ.
EXAMPLE: See getMaxAdvanceO.
658
VJIUI > /
charsWidthO
PURPOSE Determines the width of an array of characters.
SYNTAX public int char.$Width(char[] data, int offset, int count)
DESCRIPTION This method determines the width of count number of characters in the char- acter array data starting at the index offset.
PARAMETERS count The number of characters to consider, count * offset must be less than the length of data.
data offset The non-null array of characters. The index of the first byte to consider in data; offset must he less than the length of data.
RETURNS The pixel width of the characters in data when displayed.
SEE ALSO bytesWidthO, stringWidthf).
EXAMPLE See getMaxAdvance().
charWidthf)
PURPOSE Retrieves the width of a character in the font.
SYNTAX public int charWidthfchar ch) public int charWidth(int i)
DESCRIPTION This method retrieves the width of the character ch in the font of this font met- ric. If an integer i is specified, it is equivalent to charWidthC(char)i).
PARAMETERS ch The character whose width is to be retrieved.
1 The character whose width is to be retrieved, i is first converted to a char.
returns The pixel width of the character when displayed.
SEEALSO stringWidth().
example See the class example.
font
PURPOSE I he font from which the font metrics were created.
SYNTAX protected Font font
SEE ALSO getFontQ.
java.awt
EontMetrics
FontMetrics()
FontMetrics()
purpose Constructs a new FontMetrics instance.
syntax protected FontMetrics(Font font)
description This constructor creates a new FontMetri cs instance using the font font.
PARAMETERS
font I'he non-nul 1 font.
e:xampu This example demonstrates the most com
mon use of the FontMetrics class—
painting lines of text. The example prints
tw o lines of output. Notice that when using
Graphics.drawString(), you need to
add the font’s ascent to the \-coordinate.
See Figure 144.
import java.awt.*;
class Main extends Frame {
Main() {
super(“FontMetrics Example");
setSize(150, 75);
showO ;
}
public void paint(Graphics g) {
Font f = new Font(“Monospaced”, Font.ITALIC+Font.BOLD, 18);
FontMetrics fm = g.getFontMetrics(f);
int у = getlnsetsO. top;
int x = getlnsetsO .left;
g.setColor(Color.blue);
g.setFont(f);
g.drawStringC’Fi rst Line”, x, у + fm.getAscentO) ;
у fm.getHeight() ;
g.drawString(“Second Line”, x, у + fm.getAscentO);
}
public static void main(String[] args) {
new Main();
}
}
660
gCl/\SLCim )
getAscentO
PURPOSE Retrieves the font's ascent.
SYNTAX public int getAscentO
returns The font’s ascent in pixels.
SEE ALSO getMaxAscentО.
example See the class example.
getDescent()
PURPOSE Retrieves the font's descent.
SYNTAX public int getDescentO
RETURNS I'he font’s descent in pixels.
SEE ALSO getMaxDescentQ.
example: See the class example.
getFontO — --
PURPOSE Retrieves the font used to create the font metrics.
SYNTAX public Font getFontO
RETURNS The non-null font used to create the font metrics.
EXAMPLE See the getMaxAdvance().
getHeightQ
PURPOSE Retrieves the font's height.
SYNTAX public int getHeightO
description This method retrieves the font's height, which is the sum of the values getLeadingO + getAscentO + getDescentO. The font's height is used to determine the pixel distance between the baselines of adjacent lines of text.
returns The font’s height in pixels.
example See the class example.
FontMetrics
ja\ a aw t
gcltcading( )
getLeading()
Pl RPOSE Retrieves the font's leading.
SX N 1 \\ public int getLeading()
DESCRIPTION This method returns the font's leading, which is the line spacing between adja cent lines of text.
RETURNS The font's leading in pixels.
EXAMPLE See the class example.
a V a
getMaxAdvancc()
pi'rpo.si Retrieves the width of the w idest character in the font.
syntax public int getMaxAdvanceC'
retirns The maximum width of the widest character in the font in pixels; - 1 if tli<
\ alue is not available.
example This example takes an arrax of
characters and displays each
character in a box. See Figure
145. All the boxes are of equal
size. The maximum ascent, de-
scent. and advance \alucs are
used to ensure that the charac-
ters do not extend outside the
boxes. The font's leading size
. , \ I IGI RI 145: FontMetrics.getMaxAdvanceC)
is used to separate the boxes
and pad the interior of the
boxes. Pressing the + ke\ increases the size of the font; pressing l ic - ke;
decreases the size of the font.
import java.awt.-;
import java.awt.event.*;
class Main extends Frame {
int fontPointSize = 40;
char[] message = {‘J’, ‘a’, ‘v’, ‘a’};
MainQ {
super(“getMaxAdvance Example”);
addKeyLi stenerfnew KeyEventHandlerO);
setSize(300, 150);
662
show() ;
public void paint(Graphics g) {
Insets insets = this.getlnsetsO;
int w - getSizeO .width-insets, left-insets, right;
int h « getSizeO-height-insets .top-insets.bottom; A
int x insets.left;
int у - insets.top; В
FontMetrics fm -= g.getFontMetrics(
new Font(“Seri f” t Font. BOLD+-Font. ITALIC, fontpointsize)); C
// Determine size of one box. Add some padding (use the leading D
// value) around the inside of each box.
Dimension dim - new Dimension(fm. get Max Ad vance ()^ 2’"fw. get Lcadi ng() , E
fm. getMaxAscentО + fm.getMaxDescentO + 2*fm,getLeading()); Щ
// Determine bounding rectangle for all boxes; include some spacing
// between the boxes. G
Rectangle r -= new Rectangle(0, 0,
message. length -r dim.width + (message, length-1) * fm.getLeadi ng(), H
dim.height);
1
//Now center the rectangle,
r.setLocation(x+(w-r.width)/2, y+(h-r.height)/2); J
g.clearRect(x, y, w, h); К
g. set Font (fm. getFontO);
for (int i=0; i<message.length; i++) { L
int cW 5= fm.charsWidth(mes$age, i, 1);
int cH = fm.getMaxAscentО + fm.getMaxDescentO + fm.getleading(); M
g.drawChars(message, i, 1, r.x + (dim.width-cW)/2, N
r.y + (dim.height-cH)/2 + fm.getMaxAscentQ);
g.drawRect(r.x, r.y, dim.width-1, r.height 1); О
r.x 4-- dim.width * fm.getLeadi ngO ;
} P
}
Q
class KeyFventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) { R
char key = evt.getKeyCharO;
if (key == '*’) { S
fontPointSi ze+*;
} else if (key ==*-’){ T
fontPoi ntSize--;
} G
repai nt();
} V
}
w
static public void main(5tringfl args) {
new Main(); X
}
} Y
Z
java.awt
FontMetrics
getMaxAscenU)
getMaxAscent()
Pl'RPOSE Retrieves the font’s maximum ascent.
SYMAX public int getMaxAscentO
A REIIRNS The font’s maximum ascent in pixels.
в SEE ALSO getAscentO.
c EXAMPLE See getMaxAdvanceO-
D
i-: getMaxDecent() deprecated
(i PURPOSE Replaced by getMaxDescentO-
н SY VI AX public int getMaxDecentO
DI-.PR К ATI OS Replace the usage of this deprecated method, as in
I int md - fm.getMaxDecent0;
.1 with
к int md = fm.getMaxDescent();
L M getMaxDescent()
N PURPOSE Retrieves lhe font's maximum descent.
<) SYNTAX public int getMaxDescent0
P RETURNS The font's maximum descent.
Q SEE ALSO getDescent().
R EXAMPLE Sec getMaxAdvanceO.
S 1 get Widths()
L Pl RPOSE Retrieves the width of the first 256 characters in the font.
V SYNTAX public intLI getWidthsO
W RETURNS A 256-element array containing the widths of the first 256 characters in the
X font.
Y EXAMPLE 'This example displays text in columns, in top-to-bottom and left to-ri^hi order.
Z Sec Figure 146. The string can contain the newline character, which starts a new column. The descent of the font is used to determine the spacing between columns.
664
import java.awt.*;
import java.io.*;
import java.util.*;
class Main extends Frame {
StringReader is = new StringReaderf
“Hel lo\nWorld.’\nHow are\nyou\ntoday?”); j
int[J charWidths; |
I
Main() {
super(“getWidths Example”); j
setFont(new Font(“SansSerif”, Font.PLAIN, |
20)); j
setSize(300, 200); j
show(); s
} i
public void paint(Graphics g) {
int x = getlnsetsO . left,
у = getlnsetsO . top;
int ch;
char[] chs = new char[l];
FontMetrics fm = g.getFontMetricsO;
if (charWidths == null) {
charWidths = fm.getWidthsO ;
}
try {
i s.reset();
while ((ch = is.readO) != -1) {
if (ch == ‘\n’) {
x += fm.getMaxAdvance() + fm.getDescentO;
у = getlnsetsO .top;
conti nue;
}
chs[0] = (char)ch;
g.drawChars(chs, 0, 1,
x (fm.getMaxAdvance()-charWidths[ch])/2,
у + fm.getAscent());
у += fm.getHei ght();
}
} catch (lOException e) {
System.err.println(e);
}
static public void main(String[] args) {
new Mai n();
I
FontMetrics
java.awt
stringWidth()
string Width()
Pl’RPOSE Determines the pixel width of a siring.
S> MAX public int stringWidthfString string)
DESCRIPTION This method determines the pixel width of a string. The result is equivalent to using charWidthO to add together the widths of the individual characters.
RETVRNS The width of the string in pixels.
PARAM! IT RS stri ng The non-null string whose width is to be determined.
SEP Al SO bytesWidthQ , charsWidth().
EXAMPI I- See the class example.
toString() —
PURPOSE Generates a string representation of this font metrics.
SYNTAX public String toStringO
DESCRIP 1 ION This method returns lhe string representation of this font metric. The result string contains lhe values for all of the font metrics's attributes. This method is typically used for debugging.
RE'U RNS A non-null string representing the font metrics's state.
OVERRIDES java. lang.Object. toStringO.
EXAMPLE See java.lang.Object.toStringO.
666
Frame
__________________J
Syntax
public class Frame extends Window implements MenuContainer
A
В
c
-•2.. - -,L о
E
и
G
H
Description 1
A frame is a window with additional properties: a title bar. a menu bar. a border, a cursor, and J
an icon image.
к
The Title Property L
The title bar is a strip across the top of the frame that displays a short description of the frame,
called the title. The title can be changed at anv time.
N
The Resizable Property o
A resizable frame can be resized by the user. The resizable property can be changed at any
time. The precise steps to resize the frame are platform dependent.
Q
The Cursor Property
The frame normally displays the default cursor—typically an arrow—when the cursor is
moved anywhere in the frame. This cursor shape can be changed at any time using Compo- S
nent .setCursorO, The exact cursor shapes available are platform-dependent. T
The Iconimage Property
A frame can be assigned an icon image. The icon image is a way to graphically represent the v
frame. It is up to the platform windowing system as to how the icon image is used. For exam
pie, most platforms will display the frame's icon when the frame is iconified.
X
Coordinates and Sizes
A frame has a nonempty inset because of the title bar, menu bar, and border. The frame has an
interior area in which you can paint and place components. I he insets of a frame can change 7*
because of the menu bar. For example, if the window is made small enough so that the menu
Frame
java.awt
A
В
C
D
E
G
H
1
J
К
L
M
N
О
I’
Q
R
S
T
U
V
w
X
Y
z
bar requires additional lines in order to display the menu labels, getlnsetsO .top will
increase.
The origin of the frame is at the top-left comer of the frame. The v- and у-coordinates in
the frame’s bounds indicate the location of the frame on the screen.
Events
The frame fires the same events as a window. See the Window and WindowEvent classes for
more details.
Constructor
FrameO
The Property Methods
getlconlmageO
getTitleO
isResizableO
setlconlmageO
setResizableO
setTitleO
Constructs a new F rame instance.
Retrieves this frame’s icon image.
Retrieves this frame's title.
Retrieves this frame's resizable state.
Sets the image to display when this frame is iconified.
Sets this frame’s resizable property.
Sets this frame's title.
Menu Bar and Popup Menu Methods
getMenuBarO
removeО
setMenuBarO
Peer Methods
addNotifyO
disposeO
Debugging Method
paramStringO
Retrieves this frame's menu bar.
Removes this frame’s menu bar or popup menu.
Sets this frame’s menu bar.
Creates this frame’s peer hierarchy.
Destroys this frame's peer hierarchy.
Generates a string representing this frame's state.
Deprecated Constants and Methods
CROSSHAIR-CURSOR
DEFAULT-CURSOR
E-RESIZE-CURSOR
getCursorTypeO
HAND-CURSOR
MOVE-CURSOR
N_RESIZE_CURSOR
NE-RESIZE—CURSOR
NW_RESIZE-CURSOR
S-RESIZE—CURSOR
Replaced by Cursor .CROSSHAIR-CURSOR.
Replaced by Cursor. DEFAULT-CURSOR.
Replaced by Си rsor. E-RESIZE-CURSOR.
Replaced by Component .getCursorО ,getType().
Replaced by Cursor. HAND-CURSOR.
Replaced by Cursor.MOVE-CURSOR.
Replaced by Cursor. N_RESIZE_CURSOR.
Replaced by Cursor.NE-RESIZE_CURSOR.
Replaced by Cursor .NW_RESI2E-CURSOR.
Replaced by Cursor. S-RESIZE_CURSOR.
668
^MEMBER summary
se_resize_cursor Replaced by Cursor.SE_RESIZE_CURSOR.
setCursorO Replaced by Component. setCursor ()-
SW_RESIZE_CURSOR Replaced by Cursor. SW_RESIZE_CURSOR.
TEXT-CURSOR Replaced by Cursor.TEXT-CURSOR.
W_RESIZE_CURSOR Replaced by Cursor.W_RESIZE_CURSOR.
WAIT_CURSOR Replaced by Cursor .WAIT_CURSOR.
Example
This example creates a frame whose
interior is exactly 150 pixels high
and 150 pixels wide. Clicking any-
where in the interior causes a new
frame to appear. Its northwest corner
will be at the exact position you
clicked (see Figure 147).
import java.awt.'';
import java. awt.event. ;
class Main extends Frame {
// The contractor creates a frame with a window size that gives
// the desired interior size.
Mainf) {
super(“Frame Example”);
// Calling addNotifyO creates the peers; otherwise insetsO
// does not return the right values.
addNoti fy();
Insets insets = getlnsetsO;
setSize(insets.1 eft + insets.right + 150,
insets.top + insets.bottom + 150);
// Add listener
this.addMouseListener(new MouseEventHandler());
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent pvt) {
// x, у are in interior coordinates
// must be translated to screen coordinates.
Rectangle bounds = getBoundsO;
int x - evt.getXO 4 bounds.x;
Frame
java.awt
addNotify()
int у = evt.getY() + bounds.y;
A
В
C
D
E
(j
H
1
J
К
L
M
N
О
P
// Set location of new frame
Mai n m - new Mai nO;
m.setLocation(x, y);
m.show();
static public void main(String[j args) {
(new MainQ) . show() ;
1
}
addNotifyO
pvrpose Creates this frame's peer hierarchy.
syntax public synchronized void addNotifyO
description This method creates this frame's peer hierarchy, if necessary. The frame's peer
is created by calling the Toolkit.createFrameО method. This method
should be called before the frame's minimum or preferred size is calculated.
The methods pack() and show() automatically call addNotifyO.
overrides Window. addNotifyO.
see also Component. Component.mi ni mumSi ze(). Component.prefer redSize О.
Toolkit. Window.packO. Window. showO.
example See the class example.
Q
r CROSSHAIR-CURSOR DEPRECATED
S plrpose Replaced by Cursor .CROSSHAIR_CURSOR.
syntax public static final int CROSSHAIR-CURSOR
L
v DEFAULT-CURSOR
w -------------- ------------- ---- —
purpose Replaced by Cursor .DEFAULT-CURSOR,
л
syntax public static final int DEFAULT-CURSOR
DEPRECATED
670
dispose!)
PURPOSE
syntax
DESCRIPTION
OVERRIDES
example
import
import
Destroys the frame's peer hierarchy.
public synchronized void dispose()
A
This method destroys the frame s peer hierarchy, it it exists, thereby treeing
any resources used by the peers. The state of the frame hierarchy is left intact
and can be reused. The peer hierarchy can be restored by calling addNo-
tify().
Wi ndow. di spose().
This example creates two buttons. One creates a frame, and the other disposes
of it. See Figure 148. Upon initialization, the dispose button is disabled. When
a frame is created, the create button is disabled and the dispose button is G
enabled. The original frame also handles the Wi ndowEvent. WINDOW-CLOSING u
*- n
event and disposes of itself.
I
J
К
I.
M
N
О
p
java.awt.-'; q
java. awt .event. * ;
class Main extends Frame implements ActionListener {
Button btnCreate = new Button (“Create Frame’’);
Button btnDispose = new Buttonf“Dispose Frame’’);
Frame f; -p
MainQ { L-
super (“di spose Example’’);
V
btnDi spose.setEnabled(true);
add(btnCreate, BorderLayout.NORTH;; YV
add(btnDispose, BorderLayout.SOUTH);
X
// Add Listeners
btnDispose.addActi onListenerfthis;; y
btnCreate.addActionLi stener(this;;
this.addWindowListener(new WindowEventHandler()); у
setSizer100, 100);
showC);
1
Frame
java.awt
E_RESIZE_CURSOR
A
В
C
f)
G
H
I
J }
public void actionPerformed(ActionEvent evt) {
if (evt .getSourceQ — btnCreate) {
btnCreate. setEnabled(false) ;
btnDispose.setEnabled(true);
f = new Frame(“New Frame’1);
f,setBounds(100, 100, 100, 100);
f. show() ;
} else if (evt.getSourceQ == btnDispose) {
btnCreate.setEnabled(true);
btnDi spose.setEnabled(false);
f.di spose();
}
}
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
di spose();
}
}
static public void main(String[] args) {
new MainQ ;
}
К
L E_RESIZE_CURSOR /жглиита»
M
N purpose Replaced by Cursor. E_RESIZE-CURSOR. syntax public static final int E_RESIZE__CURSOR
Q FrameO
R purpose Constructs a new Frame instance.
S syntax public Frame()
Г public Frame(String title)
11 description The two forms of this constructor create a new invisible Frame instance with
V the title title. If title is not specified, it defaults to ‘’Untitled." The icon image property is initially null. The cursor is initially
w Cursor .DEFAULT-CURSOR. The frame is initially resizable. The new frame
X has a border layout manager (see BorderLayout).
Y PARAMETERS title I'he string specifying the frame's title.
7.
672
£Л-1
. example This example creates two frames: one with a title and one without. The second
frame is created at a different location.
import java.awt.*;
class Main { A
static public void mai n(Stri ng[] args) {
Frame fl = new Frame(‘Trame Example”); В
Frame f2 - new FrameO;
C
fl.setSize(200t 100);
fl.show(); D
f2.setBounds(100, 100, 200, 100);
f2.show(); E
G
getCursorType() deprecated
........................................ -........................ i
purpose: Replaced by Component.getCursorО .getTypeQ. J
SYNTAX public int getCursorTypeO К
RETURNS The frame's cursor type. L
DEPRECATION Replace the usage of this deprecated method, as in int cursorType = frame.getCursorlypeQ; M
with Nl
int cursorType = frame.getCursorO .getTypeQ . 0
p
getlconlmage() q
PURPOSE Retrieves the frame's icon image. R
SYNTAX public Image getlconlmageO S
RETURNS The frame's icon image. The return value can be null. This means the icon image has not yet been changed. T L
SEEALSO setlconlmageO. V
EXAMPLE See setlconlmageO. w
x
getMenuBarf)
purpose Retrieves the frame's menu bar.
SYNTAX
public MenuBar getMenuBar()
java.au t
F rame
getTitlef)
RETURNS The frame's menu bar. The return value is null if the frame does not have a menu bar.
EXAMPLE See MenuBar .add().
G
H
1
J
К
I.
M
N
()
p
Q
R
S
T
ir
V
w
X
Y
7
getTitle()
purpose Retrieves the frame's title.
symax public String getTitleO
returns A string containing the frame's title. The result value may be nul 1.
see also setTi tleQ.
example See setTi 11e О.
HAND_CURSOR DEPRECATED
purpose Replaced by Cursor. HAND .CURSOR.
SYNTAX public static final int HAND.CURSOR
isResizableC)
purpose Retrieves the frame's resizable stale.
syntax public boolean isResizableO
returns true if the frame is currently resizable; false otherwise.
example See setResizableO.
MOVE-CURSOR _______________ DEPRECATED
purpose Replaced by Cursor.4OVE_CURSOR.
syntax public static final int MOVF_CURSOR
N-RESIZE-CURSOR DEPRECATED
pi rpose Replaced by Cursor .N_RESIZt_CURSOR.
syntax public static final int N._RESIZE_CURSOR
674
flERESIZECLRSOR
Replaced by Cursor.NE_RESIZE_CURSOR.
public static final int NE RFSIZE_CURSOR
NW,RESIZE_CURSOR
purpose Replaced by Cursor.NW_RESIZE_CURSOR.
SYNTAX public static final int NW_RLSIZE_CURSOR
DEPRECATED
DEPRECATED
paramStringO
purpose Generates a string representing the frame’s state.
syntax protected String paramStringO
description rhe string representation of a frame consists of its container siring representa-
tion. its title, and whether the frame is resizable.
A subclass of this class should override this method and return a concatenation
of its state with the results of super.paramString(). This method is called
by the toStringO method and is typically used for debugging.
returns Л non-nul 1 string representing the frame’s slate.
overrides Container. paramStri ng().
see also Component.toSt ri ng()t j ava.lang.Obj ec t.toSt r i ng().
example 'Phis example show's how to override the paramStringO method. The sub-
class appends an extra piece of state (myData) to the result.
import java.awt.*;
class Main extends Frame {
String myData « “Testing";
MainO {
superC’paramString Example”);
}
protected String paramStringO {
String str - super.paramStringO ;
if (myData !- nul1) {
str += myData-” + myData;
)
return str;
}
static public void main(String[] args) {
Frame
java.awt
remove()
Main m - new Mai n();
System.out.pri ntln(m);
}
}
A
В
c remove()
И RPOSE
E_, SYNTAX
DESCRIPTION
G
It
I
J PARAMETERS
К comp
I.
OVER RIDES
M
EXAMPLE
N
()
P
Q
R
Removes the frame's menu bar or popup menu.
public synchronized void remove(MenuComponent comp)
This method removes the menu component comp from the frame. If comp is a
MenuBar instance that is installed as this frame's menu bar. this frame's menu
bar is removed.
If comp is a PopupMenu instance that is installed for this frame, it is removed.
If comp is not installed in the frame, this method call is ignored.
The nomnull menu component (MenuBar or PopupMenu) to remove from the
frame.
Component. removeO.
This example creates a frame with a *
menu bar and a checkbox component. If
the checkbox state is true, then the menu
bar is visible: otherwise, ihe menu bar is
removed. See Figure 149. See Compo-
nent. add() for an example of popup
menu removal.
import java.awt.";
import java.awt.event;
class Main extends Frame implements TtemListener {
MenuBar mb - new MenuBarO;
Checkbox cb = new Checkbox(“Display Menu Bar"):
Main() {
superCTemove Example1');
Menu m = new Menu(“Menu”);
m.add(“MenuIterT);
mb.add(m);
add(cb, BorderLayout.SOUTH);
cb.addltemLi stener(thi s);
pack() ;
676
show();
} public void itemStateChangedfItemEvent evt) { if (evt.getSourceO cb) { if (cb.getStateO) { setMenuBar(mb); } else { remove(mb); } } } static public void main(String[l args) { new Main(); } ] Л в c I) E n G H
S_RES1ZE_CURSOR DEPRECATED
purpose Replaced by Cursor. S_RESIZE_CURSOR, 1 J
SYNTAX public static final int S_RESIZE_CURSOR К
L
SE_RESIZE_CURSOR DEPRECATED M
purpose Replaced by Cursor .SE_RESIZE_CURSOR. N
syntax public static final int SE_RESI7F_CURSOR ()
P
SW_RESIZE_CU RSOR DEPRECATED Q
purpose Replaced by Cursor. SW_RESIZE_CURSOR. R
S
SYNTAX public static final int SW RESTZE_CURSOR
T
setCursor() deprecated U
—
purpose Replaced by Componente. setCursor (). V Vi
syntax public void setCursor(int cursorType) X
parameters у
cursorType An integer specifying one of the valid cursor types.
exceptions
IllegalArgumentException
If cursorType is not a valid cursor type.
java.awt
Frame
set Icon! mage( I
DFPRFX’ATIOS Replace the usage of this deprecated method, as in set Cursor(F’rame. MOVE-CURSOR); v\ ith setCursor(Cursor.getPredefi nedCursor(Cursor.MOVE-CURSOR));
SEE ALSO Cursor.
setlconlmagef)
PURPOSE Sets the image to display when this frame is iconified.
SYX'T'AX public synchronized void setlconlmage(lmage image)
DESCRIP 11()\ This method sets image to be the image displayed when this frame is iconified. Note: Not all platforms support the concept of iconifying a w indow.
PARAMEIERS image The non null icon image.
SF-F ALSO getlconlmageC).
EXAMPLE This example sets the frame's icon image from a file. Pushing the button toggles the display of the icon image in the frame. Iconify the frame to see the icon image being used for the frame's icon. See Figure 150.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ActionListener {
boolean showiconimage - false;
Main(St ring filename) {
superC’setlconlmage Example”);
try {
Image image = getToolkit().getlmage(filename);
setlconlmage(image);
} catch (Exception e) {
e.printStackTraceO;
}
Button b;
addfb = new Button(“Icon Image"), BorderLayout.SOUTH);
b.addActionl istener(this);
setSize(50, 150);
show();
}
public void actionPerformed(ActionFvent evt) {
678
showiconimage = !showiconimage;
repai nt () ;
}
public void paint(Graphics g) {
if (showiconimage) {
Insets insets = getlnsetsO; A
g.drawImage(getIconImageO, insets.left, insets.top, this);
} В
static public void main(Stri ng[] args) {
if (args, length == 1) { Г)
new Mai n(args[0]);
} else { Ь
System. err. pri ntl n (“usage: java Main <image file>"); MH
H
I
setMenuBar()
purpose Sets this frame’s menu bar.
L
syntax public synchronized void setMenuBar(MenuBar menubar)
M
description This method sets the frame’s menu bar to be menubar. If the frame already has
a menu bar. the current menu bar is first removed. The frame becomes the
menu bar’s parent. О
PARAMETERS P
menubar The non-nul 1 menu bar to set.
example This example creates two menu bars
and two buttons. Clicking one button
installs one of the menu bars; clicking s
the other installs the other menu bar. T
See Fimire 151.
Г
v
import java.awt.-';
import java . awt. event. '; YV
class Main extends Frame implements ActionListener {
MenuBar mbl = new MenuBarf);
MenuBar mb2 = new MenuBarf);
MainfStrinq title) {
super(rirle):
Menu menu;
menu - new Menu(“Menu bar 1“);
rrame
jaxa.awt
seiResizable()
A
В
D
E
G
H
1
J
К
L
M
\
О
p
Q
R
menu. add(‘‘One");
mbl. add(rrenu) ;
setMenuBar(mbl);
menu - new Menu(*‘Menu bar 2”) ;
menu. add(“Two");
mb2.add(menu);
Button b;
add(b = new ButtonC'^enu bar 1"), BorderLayout.WEST);
b.addActionLi stener(this);
add(b - new ButtonC'Menu bar 2”), BorderLayout,FAST);
b.addAct ionLi stener(thi s);
pack();
show();
}
public void actionPerformed(ActionEvent evt) {
String what = evt .getActionCommandO ;
if (“Menu bar 1”.equals(what)) {
setMenuBar(mbl);
} else if(“Menu bar 2” .equal s(what)) {
setMenuBar(mb2);
}
}
static public void main(Stringf] args) {
Main m = new MainCsetMenuBar Example’');
1
}
setResizablef)
purpose Sets lhe resizable property.
syniax public synchronized void setResizable(boolean resizable)
description This method sets this frame to be resizable or nonresizable. If resizable is
true, lhe frame becomes resizable; otherwise, it becomes nonresizable.
PARAMETERS
resizable If true, the frame becomes resizable; otherwise, the frame becomes nonresiz-
able.
example This example creates a frame with a
checkbox indicating whether the frame
should be resizable. Clicking the check-
box changes the resizable property of
the frame. See Figure 152.
680
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ItemListener {
Checkbox cb;
MainQ {
super(“setResizable Example”); A
cb new Checkbcx(“Resizable”, null, i sResizableO );
add(cb, Bordertayout.NORTH); В
cb.addltemListener(this);
pack О: C
show():
} f>
public void itemStateChanged(ItemEvent evt) { E
setResizable(cb.getStateO) ; MB
И
static public void main(String[] args) { G
new Main О;
} н
J
setTitleQ_____ _______________
purpose Seis this frame's title.
syntax public synchronized void setTitle(String title)
description This method seis this frame's title to be the string title.
PARAMETERS
title The string specifying the frame's new title. A value of nul 1 clears the title.
see auso getTi tleQ.
example This example creates a text ।
field in a frame, initialized I
with the frame's current title.
Pressing Return while in the
text field sets the frame's title
to the text in the text field. See
Figure 153.
import java.awt.*;
import java.awt.event;
class Main extends Frame implements ActionListener {
TextField t - new TextField(50);
MainQ {
super (‘‘setTitie Example");
t.setTextfgetTitle()); // Initialize with current title.
К
I.
M
N
0
P
Q
R
S
T
t:
V
w
X
Y
java.awt
Frame
ТЕгХТ CURSOR
add(t, BorderLayout.NORTH);
t.addActionLi stener(this);
pack();
show();
public void actionPerformed(ActionEvent evt) {
set!i tle(evt.getActionCommandO);
static public void main(StringO args) {
new 4ain();
}
J
TEXT_CURSOR
pi rposl Replaced b\ Cursor.TEXT-CURSOR.
symax public static final int TEXT CURSOR
W_RESIZE_CURSOR
purpose Replaced by Cursor.W_RESIZF-CURSOR.
SYVIAX public static final int Vv_RESIZE_CURSOR
WAITJXRSOR
pl rposf. Replaced by Cursor.WAIT_CURSOR.
SYxiax public static final int WAIT. CURSOR
DEPRECATED
DEPRECATED
DEPRECATED
682
FramePeer
A
В
D
Syntax
public interface FramePeer extends WindowPeer
Description
The frame component (see the Frame class) in the >\WT uses the platform s native implemen- I
tation of a frame. So that the AWT frame behaves the same on all platforms, the frame is j
assigned a peer, whose task is to translate the behavior of the platform's native frame to the
behavior of the AWT frame.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they l
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java. awt counterparts. <
See Component and Tool ki t for additional information about component peers.
Peer Methods
setlconlmageO
setMenuBarO
setResizableO
setTitleO
----------------------------n
I
Sets the image to display when this frame is iconified.
Sets this frame's menu bar.
Sets this frame s resizable property.
Sets this frame's title.
C
F
s
1
I
V
See Also
java.awt.Component, java.awt.Frame, java.awt.Toolkit,
j'ava. awt .Tool ki t. createFrameO •
FramePeer java.awt.peer
setlconlmageO
setlconlmagef)
Pt’RPOSE Sets the image to display when this frame is iconified
A SYNTAX PARAMI J ERS void setlconTmagefTmage image)
В image fhe icon image to be displayed.
c SEEALSO java .awt. Frame. setlconlmageO.
D
(• setMenuBarf)
PLRPOSF Sets this frame’s menu bar.
ll H SYNTAX PARAMETERS void setMenuBar(vienuBar menubar)
1 menubar The non-null menu bar to set.
J SEE ALSO java.awt.Frame.setMenuBar().
к
L setResizable()
M \ PURPOSE Sets this frame's resi/able property.
о SYNTAX void setResizablefboolean resizable)
PARAMETERS
p resizable If true, the frame becomes resi/able; otherwise, the 1
Q able.
R SEE ALSO j ava.awt.Г rame.setResi zab1e()•
S
T setTitle()
frame becomes non res iz-
и
Pl RPOSE Sets this frame’s title.
V SYNTAX void setTitle(String title)
W PARAMETERS
X title rhe string specifying the frame's new title. A value of nul 1 clears the title
Y SEE ALSO j ava. awt. Frame. setTi tl e ().
z
684
Graphics
Syntax
public abstract class Graphics
Description
The graphics context is an object used
to paint on a drawing surface, lhe
drawing surface is a rendering device
such as a screen or a printer. The draw-
ing surface can also be an off-screen
image (see Figure 154). A drawing sur-
face has three properties that may
affect a graphics context: a background
color, a foreground color, and a font.
These three properties are sometimes
used to initialize a new graphics con-
text created from a drawing surface.
When you are painting to the
screen, the AWT system supplies you
with a graphics context via the Compo-
nent. paint() and Compo-
Drawing
surface
Screen
drawLineO—►
Printer
FIGURE 154: Graphics Context Drawing Surfaces.
nent .updateO methods. See the Component class for details. When painting to the printer,
you must obtain a graphics context with a call to Printlob.getGraphics(). See PrintJob
for more details. When painting to an off-screen image, you create a graphics context on the
image that you can paint to any time you wish. However, if you want to paint any part of the
off-screen image to the screen, you need to do it indirectly through the Compo-
nent. repai nt О method. See the Component class for details.
Л drawing surface can have more than one graphics context, and multiple contexts can be
used simultaneously. Also, a graphics context can be cloned and each context can have a dif-
ferent property set. Having more than one graphics context, each with different property sets,
can be useful in some situations when you need to constantly switch property values while
painting a complex image.
In general, a graphics context should be disposed of as soon as it is no longer needed. Th is
is because a graphics context is usually associated with a system resource. Such system
resources are typically large but limited,
Graphics
java.awt
(0P>
У
FIGURE 155: Graphics
Coordinates.
The Origin and Coordinates
I he v-coordi nates of a graphics context moves from left to right; the left edge has coordinate
0. The у-coordinates of a graphics context moves from top to bottom; the top edge has coordi-
nate 0.
The graphics context has an origin, which is initially at the
coordinates (0, 0) (see Figure 155). The coordinates supplied by the
graphics operations are relative to the origin. The origin can be
moved at any time. For example, if the origin is at (10.10) and a cir-
cle is painted at (5, 5), the circle will appear on the drawing surface
at (15,15).
The Background and Foreground Colors
A graphics context has both a background and foreground color. If
the drawing surface is a native component, the colors are inherited
from the component. Changes to the component's color do not affect the colors in the graphics
context. Otherw ise, the background color is white and the foreground color is black.
When a graphics context is created, its background color is assigned and cannot be
changed or queried. The only method that uses the background color is clearRectO. The
foreground color is used by all of the other painting operations and can be changed at any time.
The Font
The graphics context has a font that is used when you are painting text. If the drawing surface
is a native component, the initial font of the graphics context is copied from the cunent font of
the component. Changes to the drawing surface’s current font do not affect the font in the
graphics context. The graphics context's font can be changed at any time. See setFont() for
an example that uses fonts.
Paint Modes
A graphics context can be in one of two paint modes: normal or xor. In normal paint mode, the
background colors have no effect on the paint operation. That is, if you paint a black circle, it
will appear as a black circle no matter on what color background it was painted.
Xor paint mode is more complicated. In the simplest terms, if you paint the same object
twice while you are in xor mode, the object disappears. Also, when you paint the object for the
first time, it won't appear in rhe correct color. The color that appears is based on both the fore-
ground and background colors; the exact color chosen is platform-dependent.
In xor paint mode, one special color called the xor color will not affect the foreground
color. Thar is. if you paint on an xor color colored background, the foreground color will come
out as expected. However, the previous rule of painting the same object twice still applies.
One final effect of xor paint mode: If the foreground color is the same as the xor color, the
painting operation is ignored.
Xor mode is typically used in dragging operations. During the drag, the outline ot the
object is painted in xor mode. After the object is moved, the old outline is erased simply by
686
painting the outline in the same place. This optimization is much more efficient than having to
repaint the background to erase the old outline of the object.
See setXORModeO for an example that uses xor paint mode.
The Clipping Area
The clipping area is used to constrain the results of the painting operations so that they affect
only a specific area. In particular, painting operations are effective only inside the clipping
area; any painting done outside the clipping area is ignored. Hor example, to implement a rect-
angle with scrolling text, you would set a clipping area around that rectangle so that lhe scroll-
ing text would not affect the surrounding area when you draw the string. As of Java 1.1.2, the
clipping area is restricted to a rectangle. In future releases, the clipping area will be able to be
any shape.
Image Painting
The drawlmage О method is used to paint images in a graphics context. There are many vari-
ants of the method that lets you scale, flip, and crop lhe image.
Initial Values
For some drawing surfaces, when a graphics context is created from the drawing surface, three
properties of the graphics context are initialized with the current settings of the drawing sur-
face. In particular, if the drawing surface is a native component, the background and fore-
ground color and font of the graphics context are initialized from the same three properties of
the component. This is not true if the drawing surface is a lightweight component or a printed
page.
IER SUMMARY
Constructors and Destructors
createO Constructs a new Graphics object that has (he same properties as I this graphics context.
disposeO finalizeO GraphicsO Releases this graphics context's system resources. Releases this graphics context's system resources. Constructs a new Graphi cs object.
Color Methods getColorC) setColorО Retrieves this graphics context's foreground color. Sets this graphics context's foreground color. j
Paint Mode Methods setPai ntModeO setXORModeO Sets this graphics context to normal paint mode. Sets this graphics context to xor paint mode.
Continued
Graphics
java.awt
MEMBER SUMMARY
z\
в
c
D
к
F
H
I
J
К
L
M
\
О
Clipping Methods
clipRectO
; getClipO
getClipBoundsO
setCl ipO
Painting Methods
clearRectQ
copyAreaO
draw3DRectО
drawArcQ
drawl ineO
drawOval()
drawPolyli ne()
drawpolygon О
drawRectO
drawRoundRectO
fiH3DRect()
fillArcO
I fillOvalO
fi11 PolygonO
fillRectO
filIRoundRectО
Shrinks this graphics context's dipping area.
Retrieves this graphics context's clipping area.
Retrieves the clipping area’s bounds of this graphics context.
Sets the clipping area of this graphics context.
Paints a rectangle with the background color on this graphics context.
Copies an area of the drawing surface to another area of this drawing
surface.
Paints a 3D outline around a rectangle on this graphics context.
Paints an elliptical arc inside a rectangle on this graphics context.
Paints a line on this graphics context.
Paints an oval outline inside a rectangle on this graphics context.
Paints an open polygon outline on this graphics context.
Paints a closed polygon outline on this graphics context.
Paints an outline around a rectangle on this graphics context.
Paints an outline of a rectangle with rounded corners on this graphics
context.
Paints a rectangle that has a 3D outline on this graphics context.
Paints a filled elliptical arc inside a rectangle on this graphics context.
Paints an oval area on this graphics con text.
Paints a closed polygon on this graphics context.
Paints a rectangular area on this graphics context.
Paints a rectangle with rounded comers on this graphics context.
p Font and String Methods
Q drawBytesO Paints an array of bytes as characters on this graphics context
l> drawCharsO Paints an array of characters on this graphics context.
К drawStringO Paints a string on this graphics context.
S getFontO Retrieves this graphics context s font.
T : getFontMetricsO Retrieves the font metrics for a font.
1 setFontO Sets this graphics context's font.
i; Image Method
V drawimage О Paints an image on this graphics context.
w Translate Method
X translateQ
Moves this graphics context’s origin.
Y Debugging Method
Z toStringO Deprecated Method getCli pRect() Generates a string representation of this graphics context's state. Replaced getClipBoundsO.
688
Example
This example paints three colored figures h demon- strates the simplest example of painting on the screen. See Figure 156. 1 A
import java.awt.-; В
class Main extends Frame { c
Main() {
super(“Graphics Example”); n
setSize(200, 100); show() ; i j p;
}
public void paint(Graph!cs g) { F
Insets insets = getlnsetsO; int x = insets.left; И
int у = insets.top; H
Polygon polygon = new' Polygon(); polygon.addPoint(x+125, y); polygon.addPoint(x+100, y+50): I 1
polygon.addPoint(x+150, y+50); J
g.setColor(Col or.red); g.fi11 Oval(x, у, 50, 50); к I
g.setColor(Col or.green); g.fi11Rect(x+50, у, 50, 50); g.setColor(Col or.blue); 1- M
g.fi11 Polygon Cpolygon); } N
static public void main(String[] args) { О
new Main(); i p
j } Q R
clearRectf)
PI'Rposl Paints a rectangle with the background color on this graphics context.
syntax public abstract void clearRect(int x, int y, int width, int v
hei ght)
w
OESC ripiiox This method paints the area defined b\ x. y. width, and height w ith this
graphics context's background color. If either wi dth or height is less than or X
equal to 0. the method call is ignored. y
PARAMI.’IFRS у
height The height of the rectangular area in pixels.
Graphics
clipRcch )
ja\ a.aw l
wi dth The width of the rectangular area in pixels.
X The v-coordinate in pixels.
У The у-coordinate in pixels.
SET: ALSO drawRect(), fillRectQ.
A EXAMPLE This example paints successive!) smaller and
В smaller rectangles, alternating between lhe
C background and foreground colors. Sec Fig-
D ure 157.
import java.awt.-';
I
class Main extends Frame {
Main О {
super(“clearRect Example”);
setBackground(Color.bl ack);
setSize(200, 200);
show();
j
К
L
M
N
()
P
Q
R
S
T
public void paint(Graphics g) {
Insets insets - this.getlnsets();
int x = insets.left, у = insets.top;
int w = getSizeO.width-insets.left-insets.right;
int h = getSi ze() . hei ght-msets . top-i nsets . bottom;
g.setColor(Col or.red);
while (w > 0 && h > 0) {
g.clearRect(x++, y++, w, h);
g.fi11Rect(x++, y++, w-2, h 2);
w - = 4 ;
h -= 4;
}
}
static public void main(String[] args) {
new Mai n();
}
I'
v clipRect()
pi rpose Shrinks this graphics context's clipping area.
* SYNTAX public abstract void clipRect(int x, int y, int width, int
Y height)
У oescriphon The intersection of this graphics context clipping area and the rectangle
tied b_\ x. y. width, and height becomes the new clipping area.
690
PARAMETERS height width The height of the rectangle in pixels. The width of the rectangle in pixels.
X The л-coordinate in pixels.
У The у-coordinate in pixels.
SEEALSO getClipO , getCl i pBoundsQ . setClipO-
EXAMPLE See createO.
copyAreaf)
PURPOSE Copies an area of the draw ing surface to another area cd’ the draw ing surface.
SYNTAX public abstract void copyAreafint x, int y, int width, int height, int del tax, int deltay)
DESCRIPTION This method copies the pixels on the screen in the rectangular area defined by x, y. width, and height (o the area defined by x+deltax. y+deltay. width, and height. If some window is partially- occluding the scrolled area, the paintO method will be called to repaint the damaged area. Optimally, the clipping area of the graphics context supplied by the paintO method will be exactly as large as needed. However, on some platforms this may not be the case.
PARAML 1ERS del tax deltay height width The horizontal distance from the source in pixels. I'hc vertical distance from the source in pixels. The height of the source in pixels. The w idth of the source in pixels.
X The А-coordinate of the source in pixels.
У The y-coordinale of the source in pixels.
example. This example creates a canvas that paints a scrolling histogram. Sec Figure 15S. The histogram is scrolled 1 pixel to the right, and a new line of data is added on the left. The copyAreaQ method is straight- forward. unless some window is par- tial!} occluding the area being scrolled. In this case, the paintO method is called to paint the ’ dam- aged” areas. A blue rectangle is painted to indicate a complete paint, while a
java/awt
Graphics
copyArea()
red rectangle is painted u> indicate a partial paint. A paint call is partial if the
dimensions of getClipBoundsO are smaller than size().
So that you can invoke a partial paint, a checkbox component allows you to
show or hide a 1-pixel-wide window that will overlap the scrolling histogram.
The scrolling histogram is embedded in another panel to guarantee that the
overlapping window w ill overlap the scrolling histogram. If the overlapping
window* is a sibling of the scrolling histogram, there is no way to control
whether the overlapping window' will appear above or below the scrolling his-
togram.
import java.awt.*:
import java.awt.event.*;
class Main extends f-rame implements ItemListener {
Panel panel - new Panel О;
MainCanvas cv = new MainCanvasO;
Canvas overlap = new Canvas О;
Checkbox cb - new Checkbox(“Overlap”, null, false);
Main() {
super(“copyArea Example");
panel.setLayout(new BorderLayout());
panel.add(cv, BorderLayout.CENTER);
add(overlap);
add(pane1);
add(cb);
cb.addltemLi stener(th i s);
overlap.setBackground(Col or.green);
overlap. setVi si ble(fal se) ;
setSize(400, 100);
showO;
}
// In order to get the overlapping window to overlap another,
// we need to implement our own specific layout.
public synchronized void doLayoutO {
Insets insets = this.getlnsetsO;
Dimension d - cb.getPreferredSize();
int w = getSizeO.width - insets.1eft-insets.right;
int h = getSizeO.height - insets.top-insets.bottom;
panel.setBounds(insets.left, insets.top, w, h-d.height);
cb.setBounds(insets.left, getSizeO.height-insets.bottom-d.height,
w, d.height);
overlap.setBounds(insets.1 eft, insets.top, 1, h);
}
public void itemStateChanged(ItemEvent evt) {
overlap. setVi si bl e(cb .getStateO ) ;
}
static public void main(String[J args) {
692
new Mai n();
}
}
class MainCanvas extends Canvas implements Runnable {
MainCanvasO {
(new Thread(this)).start();
}
// Returns an integer in the range [0..Г-1].
int random(int r) {
return (int)(Math.floor(Math.random()*r));
}
public void update(Craphics g) {
int w = getSizeO .width;
int h = getSize().height;
// shift right by 1 pixel.
g.copyArea(0, 0, w-1, h, 1, 0);
g.clearRect(0, 0t 1, h);
g.drawLine(0, random(h), 0, h);
}
public void paint(Graphics g) {
int w = getSize().width;
int h = getSize().height;
Rectangle r = g .getCl i pBoundsO ;
if (r -= null . i (r.width == w && r.height h)) {
g.setColor(Color.blue); // full repaint
} else {
g.setColor(Color.red); // partial repaint
}
g.fi1IRect(0, random(h), w, h);
}
public void run() {
while (true) {
try {Thread.sleep(100);} catch (Exception e) {};
repai nt();
}
}
}
create()
PURPOSE Constructs a new Graphics object that has the same properties as this graphics context.
SYNTAX public Graphics createO public Graphics create(int x, int y, int width, int height)
ja\ a.aw I
Graphics
createt )
;\ di st ripi к)\ If x. y. width, and height arc specified, (he new graphics context will be translated by x and у and a rectangular clipping area set. More precisely lie second overload is similar to Graphics g2 = g.createO; g2.translated, y);
В g2.clipRect(0, 0, width, height);
C The main difference i< that the clipping area in the created graphics context
I) H F cannot grow. In the previous code, it is possible to grow the clipping area with a call to setCl i p(). PAR W1I-: 1'1.RS height The pixel height of lhe area. width The pixel w idth of lhe area.
H I x The \-coordinate. у The v-coordinate. rmi r\s A non-null graphics context.
.1 si i \i so translate().
К i xwipii This example requires three different
1. nono\erlapping clipping rectangles on lhe drawing surface. See l iguie 15е).
M Two copies of the supplied graphics context arc created, and a clipping rectan- gle is sei on the copies. Finally, (he original graphics context is clipped, since
X no more clipping rectangles need to be sei.
() import java. awt.
P class Main extends Frame {
Q Main О { super (“create Example’’);
R setSize(200, 200); showO ; }
S Г void paintFigure(Graphics g, int w, int h) { g.clipRect(5, 5, w-10, h-10);
и g.fi1lOval(0, 0, w, h);
V i public void paint(Graphics g) { Insets insets = this.getlnsets() ;
w X int x = insets.left, у = insets.top; int w = getSizeO.width-insets.left-insets.right; int h = getSize().height-insets.top-insets.hottom;
Y Graphics g2 = g.create(x, y, w/3, h); g2.setColor(Col or.red); paintFigure(g2 , w/3, h); g2 . di sposeO ; g2 = g. create(x-+w/3, y, w/3, h) ; g2.setColor(Col or.green);
694
paintfigure(g2, w/3, h);
g2.disposeO ;
// Safe to use original one.
g.translate^ + w*2/3, y) ;
g.setColor(Col or.blue);
paintFigure(g, w/3, h) ;
}
static public void main(String[] args) {
new Main();
E
E
disposeQ________________________________ Ц
purpose Releases this graphics context s system resources. tf
syntax public abstract void disposeO I
description This method releases any system resources that this graphics context has been J
using. Any further method calls on this object after it has been disposed of are
ignored.
Calling this method is not strictly necessary because the garbage collector will **
eventually call this graphics context’s finalize О method, which in turn will M
call disposef). However, when graphics contexts are created at a fast rate.
the overall system performance may be helped by explicitly disposing of this
graphics context. °
seealso finalizeO. p
example SeecreateO- Q
R
draw3DRect() S
----------------- -------------- ---------- ----------- ----------------------- •[
purpose Paints a 31) outline around a rectangle on this graphics context.
syntax public void draw3DRect(int x, int y, int width, int height,
boolean raised)
OESCRtPWN This method paints a 1-pixel-thick outline around the rectangle defined by x,
y. width, and height. The left and lop edges of the outline are within the X
specified rectangle, but the right and bottom edges are just outside the defined y
rectangle. Hence, this method actually draws width+1 horizontal lines and
height+1 vertical lines. Note that this method will paint a single pixel if z
width and height are both 0. Use drawBDRect(x, у, width' 1, height-1)
Graphics
draw 3DReet()
java.awt
to paint the 3D outline inside the specified rectangle. If either width or
height is less than 0. the method call is ignored.
If raised is true, the 3D effect is done by lightening the left and top edges
and darkening the right and bottom edges. If rai sed is fal se. the left and top
edges are darker and the right and bottom edges arc lighter. The lighter and
darker color shades are generated by the Col or.brighter() and
Col or. darker (J methods, respectively.
This method uses the foreground color to calculate the lighter and darker col-
ors for the 3D rectangle. A common mistake is to forget to set the foregiound
color before calling this method. Generally, the foreground color should be set
to the background color so that the 3D colors are based on the background.
However, depending on the background color, the calculated 31) colors are not
always very good. So you may have to experiment with different colors to
achieve a better 3D effect.
1 I’ARAMI-lT.RS
.1 hei ght The height of the rectangular area in pixels.
к 1 rai sed Specifies whether the area should be raised or lowered.
1 . wi dth The width of the rectangular area in
M pixels.
N X The .v-coordinate in pixels.
() У The у-coordinate in pixels.
SI.1. ALSO Co lor.brighter(),
P Col or.darker(), fi113DRect().
Q IX VMI’I I- 'This example paints a 3D border just
R within the frame’s paintable area. The 3D border is thicker than 1 pixel.
S T ('licking toggles the 3D border between a raised border and a lowered
1 1 border. Figure 160 shows a raised bor-
11 der. Figure 161 shows a lowered bor-
V der.
W ...
import java.awt."';
Y import java.awt.event.*;
Y class Main extends Frame {
int borderWidth = 5;
У boolean raised = true;
MainQ {
super(“draw3DRect Example’);
696
setSize(200, 200);
addMousel istener(new MouseEventHandlerQ);
show() ;
public void paint(Graphics g) { A
Insets insets = this.getlnsetsO ;
int x ~ insets.left, у - insets.top; В
int w -= getSizeO .width-insets, left-insets, right;
int h == getSize().height-insets.top-insets.bottom; C
w -- 1; // draw inside the rectangle. P
h -- 1; // draw inside the rectangle.
g. setColor(getBackgroundO); В
for (int i-0; i <borderWidth; i+O {
g.draw3DRect(x++, y+-s w, h, raised); F
g.fi 1 IRect(x, y, w+1, h+1); 11
}
I
class MouseCventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) { J
raised = ’raised;
repaintO; К
}
} L
static public void main(String[] args) { M
new Main();
} N
}
О
P
drawArc() Q
к
purpose Paints an elliptical arc inside a rectangle on this graphics context.
S
syntax public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle) Г
descripwn This method paints a 1 pixel-thick elliptical arc in the foreground color within
the rectangle defined by x. y. width, and height. If either width or height is у
less than 0. the method call is ignored.
Logically, you form the arc first by using the drawOval () method to paint an
oval inside the rectangle. Next, define a horizontal line that originates from the x
oval's center and extends to the containing rectangle’s right edge. Then anchor у
the line at the oval's center and rotate the line startAngle degrees from its
starling position. If startAngl e is positive, rotate counterclockwise; if start-
Angle is negative, rotate clockwise. The intersection of this line and the oval's
Graphics
draw Л ret )
ja\ a.aw i
outline is the starling point for (he arc. I inalix. continue rotating the :ine
arcAngle degrees. Again, if arcAngle is positne. lotate counterclockwise;
otherwise, rotate clockwise. All the points that intersect this line and the oxal s
outline during the rotation are included in (he arc.
PAR XMt 1 LRS
ar cAnqle
hei qht
startAnqle
width
x
У
I hc angle in degtecs ( *60 degrees in a circle) th a I specihcs (he end ol ihc ux.
arcAng 1 e is relatixe io start Angle.
I he height of the rectangular area in pixels.
Ihc angle in degrees (360 degrees in a circle) that spec dies the start ol the arc:
a \ alue of 0 is al the * o’clock position.
I he width of the rectangular
area in pixels.
I he v-coordinatc in pixels.
1 he \-coordinate in pixels.
f i 1 1 Arc О.
This example draws a 270-
degree arc starting at 0 degrees.
Four labels are used io show the
start angle positions. See Figure
102.
import
java.awt
class vain extends Frarre {
vain() {
super(“drawAr< Fxarp'e”) ;
add(new
1 ayout. (. L.M 14) ;
add(new
add(new
add(new
add(new
sctSize(200. 200):
showf):
MainCarvas(), Border
Label(“90”, «_abel. CENTER), BorderLayout.NORTH):
Label(“270”. I abe' . Ct X'lrR). BorderLayout . SOUTH) :
Labe 1(“0”), BoraerLayout.EAST):
Label(“180”), Border! ayout.M Si);
static public void ma:n(String[ ; args) {
new Main():
}
class vjintanvas extends Canvas {
public void paint(Graphics g) {
q . urawArc (0, 0, get Si zeO . wi dth , getSizeO . height , 0, 2Z0):
urawrcyiesi)
drawBytesO_______ _____________________ ____________
purpose Paints an array of bytes as characters on this graphics context
SYNTAX public void drawBytes(byteLJ buf, int offset, int count, int x,
i nt y) A
description This method is equivalent to В
drawStringfnew Stringfbuf, 0, offset, count));
Seethe drawStringO method for details.
D
parameters
buf The non-null array of bytes to paint. H
count The number of characters in buf to paint. p
offset The starting index of the first character in buf to paint.
x The л-coordinate of the baseline in pixels. Ml
у The у-coordinate of the baseline in pixels. H
SEE also drawChars(), drawStringO, FontMetrics. I
example See drawStringO. j
К
drawCharsO 1
...... . . м
purpose Paints an array of characters on this graphics context.
N
SYNTAX public void drawChars(charP bufT int offset, int count, int x,
int y)
description This method is equivalent to p
drawString(new Stringfbuf, offset, count)); q
See the drawStringO method for details.
R
PARAMETERS
buf The non-nul 1 array of characters to paint. S
count The number of characters in buf to paint. I
offset The index of the first character in buf to paint.
x The x-coordinate of the baseline in pixels.
У The у-coordinate of the baseline in pixels. v
SEE also drawBytesO, drawStringO, FontMetrics.
example See drawStringO. x
Graphics
drawlmage()
java.awt
drawImageO
Pl RPOSL
SYNTAX
A
В
C
I)
E
F
(i
H
1 DE'SCRiPWN
J
К
L
M
N
()
P
Q
R
S
T
t; PARAMETERS
V bgColor
w dxl
X dx2
Y dyl
Z dy2 hei ght image
Paints an image on this graphics context.
public abstract boolean drawlmageflmage image, int dxl, int dyl,
Imageobserver observer)
public abstract boolean drawlmage(Image image, int dxl, int dyl,
Color bgColor, ImageObserver observer)
public abstract boolean drawImageCImage image, int dxl, int dyl,
int width, int height, ImageObserver observer)
public abstract boolean drawlmage (Image image, int dxl, int dyl,
int width, int height, Color bgColor, ImageObserver observer)
public abstract boolean drawImageCImage image, int dxl, int dyl,
int dx2, int dy?, int sxl, syl, int sx2, int sy2, Color
bgColor, ImageObserver observer)
public abstract boolean drawImageCImage image, int dxl, int dyl,
int dx2, int dy2, int sxl, syl, int sx2, int sy2. Color
bgColor, ImageObserver observer)
The first four forms of this method paint the image image such that its north-
west corner is at pixel location (dxl. dyl). If width and height arc specified,
the image is scaled so that its width is width and its height is height. A nega-
tive width or height indicates that proportional values are to be used. This
means that, for example, if width is negative, then a width should be chosen
so that the image maintains its correct portions when the height is supplied. If
both width and height are negative, the width and height of the original
image are used.
The last two forms of this method paint the subimage specified by the source
coordinates (sxl, syl, sx2. sy2) of image image to the rectangle specified by
the destination coordinates (dxl. dyl, dx2. dy2). The source subimage is
scaled and mapped to the destination rectangle such that (sxl, syl) maps to
(dxl, dyl) and (sx2, sy2) maps to (dx2. dy2). By specifying appropriate val-
ues for the coordinates, you can flip the image horizontally or vertically.
If observer is non-null, it will receive updates as the image is loaded. See
the ImageObserver class for more information.
The color to use for transparent pixels in the image. If nul 1 or unspecified, no
color is used.
The x-coordinate of the northwest corner of the destination rectangle in pixels.
The r-coordinate of the southeast corner of the destination rectangle in pixels.
The v-coordinate of the northwest corner of the destination rectangle in pixels.
The у-coordinate of the southeast corner of the destination rectangle in pixels.
The height of the scaled image in pixels.
The image to paint.
700
drawlmagef J
observer The image update observer. This value may be null.
sxl The л-coordinate of the northwest corner of the source rectangle in pixels.
SX2 The л-coordinate of the southeast corner of the .source rectangle in pixels.
$yl The у-coordinate of the northwest corner of lhe source rectangle in pixels.
Sy2 The у-coordinate of the southeast comer of the source rechanneling pixels,
width The width of the scaled image in pixels.
returns true if lhe image is completely loaded or scaled and was painted successfully:
fal se otherwise.
I
(
I
I
1
SEE Also Image, ImageObserver.
EXAMPLE
This example renders
an image five differ-
ent ways using
drawlmage О: origi-
nal size, shrunken to
one-fourth the size,
enlarged to twice the
size, flipped horizon-
tally; and flipped ver-
tically. See Figure
163.
FIGURE 163: Graphics. drawlmage О •
I
h
I
import java.awt.*;
class Main extends Frame { <
Image image;
Main(String filename) { *
superC'drawTmage Example”); <
try {
image = getToolkit(),getlmage(filename); p
setlconlmage(image);
} catch (Exception e) { ч
e.printStackTraceO;
} I
setSize(400, 200); L
show();
I V
public void paint(Graphics g) { V
Insets insets = getlnsetsO;
int x = insets.left, у = insets.top; у
int w = image.getWidth(this);
int h - image.getHeight(this); у
// original у
g.drawlmage(image, x, y, this);
// shrinken
g.drawRect(x, y, w/4+1, h/4+1);
Graphics
drawLinc()
java.awl
A
В
С
D
Е
h
Н
I
J
К
L
М
N
О
Р
Q
R
S
1'
и
V
W
X
Y
7
g.drawImage(imageT x*l, y*l, w/4, h/4, this);
// horizontally flipped
g. dr awl mage (i mage, x-«-w, y, x+2*w, y^-h, w. 0, 0, h, this);
// vertically flipped
g.drawlmage(image, x*2*w, y, x+3*wt y*h, 0. h, w, 0, this);
// enlarged; use -1 to indicate proportional height
g.drawlmage(image, x + 3’fw, y. 2-w, -1, this);
}
static public void mai n(Stri ng [] args) {
if (args.length -= 1) {
new Main(args[0]);
} else {
System.err.println(“usage: java Main <image file>”);
}
}
}
У
drawLine()
pr rpose Paints a line on this graphics context.
syxtax public abstract void drawLine(int xl, int yl, int x2, int y2)
description This method paints a I -pi xel-thick line between the coordinates txl. yl) and
(x2. y2) in the foreground color. The pixel at (x2. y2) is included in the line.
The drawLineO object al wax s draws at least I pixel.
PARAMETERS
The first point's л-coordinate in pixels.
The first point's у coordinate in pixels.
The second point's r-coordinate in pixels.
The second point's у-coordinate in pixels.
see al so drawPolyline().
example This example paints a series of con-
nected lines. Sec Figure 164. Each time
the mouse is clicked or dragged, a new
line is added to lhe line list. This exam-
ple also demonstrates how to use the
updatef) method to avoid redrawing
all of the lines and thus avoid flicker.
import java.awt.-’,
import java.awt.event;
import java.util
FIGIRE 164: Graphics. drawLine().
702
kirapnicN
drawLinet)
java.awt
class Main extends Frame {
Vector points - new VectorQ;
int lastDrawnPoint - 0;
Main() {
super(“drawLine Example");
setSize(200, 200);
addMousel istener(new MouseEventHandlerQ);
addMouseMot!onl istenerCnew MouseMotionFventHandler());
showQ ;
}
public void paint(Graphics g) {
Point curPt = null;
for (int i^0; i<points.size(); i+-t) {
Point pt =* (Point)points .elementAt (i);
if (curPt null) {
g. drawLi ne(curPt. x t curPt.y, pt.x, pt.y);
}
curPt = pt;
}
lastDrawnPoint points.si?e();
}
public void update(Graphics g) {
Point curPt - null;
lastDrawnPoint = Math.max(0, lastDrawnPoint-1);
for (int i=lastDrawnPoint; i<points.size(); i+*) {
Point pt - (Point)points.elementAt(i);
if (curPt 1 - null) {
g.drawLine(curPt.x, curPt.y, pt.x, pt.y);
}
curPt - pt;
}
lastDrawnPoint - points.size();
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(Mouse£vent evt) {
poi nts.addElement(evt.getPo i nt());
repaintO;
}
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent evt) {
poi nts. addFleirentCevt. getPoi nt()) ;
repai nt();
}
static public void main(String[J args) {
new Mai n();
1
Graphics
drawOvaK)
java.awt
drawOval()
purpose Paints an oval outline inside a rectangle on this graphics context.
syntax public abstract void drawOval(int x, int y. int width, int
height)
description This method paints a 1-pixel-thick oval outline in the foreground color within
the rectangle defined by x, y, width, and height. It either width or height is
less than 0, the method call is ignored.
PARAMEI ERS
height The height of the rectangular area in pixels,
width The width of the rectangular area in pixels.
x The л-coordinate in pixels.
у The у-coordinate in pixels.
SEE ALSO fillOvalQ.
example This example creates a frame and reads
numbers from standard input. See Fig-
ure 165. Each line from standard input
contains a coordinate. When two coor-
dinates are retrieved, they form a point
and a circle is painted around the point.
import java.awt.*;
i mnri rf- nt-i 1 "i< *
FIGI RE 165: Graphics.drawOval().
import java.io.*;
class Main extends Frame {
Vector points = new VectorO;
Main О {
super('‘drawOval Exampl e’1);
setSize(200, 200);
show();
void addPoint(Point p) {
points.addElement(p);
repaint();
}
public void paint(Graphics g) {
Insets insets = getlnsetsO;
int x = insets.I eft, у = insets.top;
for (int i=0; i<points.size(); i++) {
Point p = (Point)points.elementAt(i);
g.drawOval(x+p.x-5, y+p.y-5, 10, 10);
}
704
java.awi vrupum
draw Pol ygon()
static public void mai n(Stri ng[] args) {
} } Main m = new Main(); BufferedReader dis = new BufferedReader(new InputStreamReader(System.in)); while (true) { try { m.addPoint(new Point( Integer.parselnt(di s.readLine()), Integer.parselnt(di s.readLine()))); } catch (Exception e) { e.pri ntStackT race(); System.exi t(l); } }
drawPolygonQ
PURPOSE Paints a closed polygon outline on this graphics context.
SYNTAX public void drawpolygon(Polygon polygon) public abstract void drawPolygon(int[] xPoints, int[J yPoints, int nPoints)
DESCRIPTION Л polygon is a collection of lines connecting a series of points. The polygon is closed, meaning a line is automatically drawn between the first and last points if the two are different. This method paints a 1 -pixel-thick polygon in the fore- ground color using the specified set of points. The points are either specified by the polygon polygon or by two arrays xPoints and yPoints. In the latter form. xPoints[i] and yPoints[i] together specify a point in the polygon. The series of points from index 0 to nPoi nts-1 specifies the ordered list of points in the polygon.
PARAMETERS nPoints polygon xPoints yPoi nts The number of points in xPoi nts and yPoi nts. The non-nul 1 polygon to paint. The non-nul 1 array of r-coordinates (in pixels) in the polygon. The non-nul 1 array of у-coordinates (in pixels) in the polygon.
SEE ALSO drawPolyline(), fi11 Polygon(), Polygon.
Graphics
ja\ a.aw t
draw Pol\gone )
1 4 XMPLh This example Pa,nls polsgon. When the —Td'Ix"| mouse is clicked or dragged, a new point is added to the polygon. Sec Figure 166. у
A В import java . awt.__
C import java, awt. event .*•; ~
1) L 1 class Main extends Frame { Polygon polygon new PolygonO; I IGl RF 166: Graphics .drawPolygonO • Main О { super(“drawPolygon Example”);
addMouseLi stener(new MouseEventHandl er()); addMouseMoti onLi stener(new MouseMotionFventHandler()1;
H 1 setSize(200, 200); show(); }
J public void paint(Graphics g) {
К g.drawPolygon(polygon) ; }
L // The default update method clears the screen which causes
M // flicker. This override avoids this, public void update(Graphics g) {
N paint(g); 1
() class MouseEventHandler extends MouseAdapter {
P public void mousePressed(MouseEvent evt) { polygon.addPoi nt(evt.getX(), evt.getY(1);
Q repai nt(); }
R T } class MouseMotionEventHand1 er extends MouseMotionAdapter { public void mouseDragged(MouseEvent evt) { polygon.addPoint(evt.getX() . evt . getYQ); repa i nt() ;
U } }
V static public void main(StringLJ args) {
W new Main(); } 1
Y
706
java.awt
Graphics
dra w Poly line()
drawPolyline()
pl'rposi Paints a nonclosed polygon outline on this graphics context.
syntax public abstract void drawPolу 1ine(int[] xPoints, int[] yPoints,
int nPoints)
description A nonclosed polygon is a collection of lines connecting a series of points in
which a line is not automatically drawn between the first and last points if the
two points differ. This method paints a 1 pixel-thick nonclosed polygon in the
foreground color using the specified set of points.
The points are specified hy two arrays xPoints and yPoints. xPoints[i]
and yPointsfi] together specify a point in the polygon. The series of points
from index 0 to nPoints-1 specifies the ordered list of points in the polygon.
PARAMEIERS
nPoints
xPoints
yPoi nts
SEE ALSO
The number of points in xPoints and yPoints.
The non-null array of r-coordinates (in pixels) in the polygon.
The non-null array of v coordinates (in pixels) in the polygon.
drawLineO, drawPolygon, fi 11 Polygon(). Polygon.
example This example paints a polyline. When
the mouse is clicked or dragged, a new
point is added to the polyline (until 100
points have been added). See Figure
167.
import java.awt.*;
import java.awt.event;
class Main extends F-rame {
int[] xPoints = new int[100];
int[] yPoints new intJT00];
int nPoints = 0;
FIGURE 167:
Graphics.drawPolylineО.
Main() {
super(“drawPolyline Fxample”);
addMouseLi stenerfnew MouseEventHandler());
addMouseMotionListener(new MouseMotionEventHandler());
setSize(200, 200);
show();
}
public void paint(Craphics q) {
g.drawPo1 у 1ine(xPoints, yPoints, nPoints);
// The default update method clears the screen which causes
// flicker. This override avoids this.
public void update(Graphics g) {
Graphics
drawRcctt)
jasa.awt
pai nt (g);
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseFvent evt) {
if (nPoints < 100) {
xPoints[nPoints] - evt.getXO;
yPointsLnPoints] - evt.getYQ;
++nPoi nts;
}
repai nt Q ;
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent evt) {
if (nPoints < 100) {
xPoints[nPoints] - evt.getXO;
yPoi nts [nPoi nts] = evt.getYQ;
+^nPoi nts;
}
repaintQ ;
}
static public void main(String[] args) {
new MainQ ;
}
}
drawRect()
HURPOSH Paints an outline around a rectangle on this graphics context.
SYMAX public void drawRectfint x, int y, int width, int height)
DESCRIPTION This method paints a 1-pixel-thick outline around the rectangle defined b\ x. y. width, and height. The left and top edges of the outline are within the specified rectangle, hut the right and bottom edges are just outside the defined rectangle. Hence, this method actually draws width+1 horizontal lines and height+1 vertical lines. Note that it will paint a single pixel if width and height are both 0. Use drawRectfx, y, width-1, height-1) to paint the outline inside the specified rectangle. If either width or height is less than 0. the method call is ignored.
PARAMETERS height width X У The height of the rectangular area in pixels. The width of the rectangular area in pixels. The ^-coordinate in pixels. The у-coordinate in pixels.
708
Graphi'
drawRccl
java.awt
SEE ALSO
exam pi л:
clearRect(), fillRect().
This example demonstrates how to
implement an “outline rectangle/'
which is typically used for selecting
objects in a user interface or for defin-
ing the size and location of new objects.
See Figure 168. In this example, you
create a rectangle by clicking and drag-
ging an outline of a rectangle until you
are satisfied with the size of the rectan-
gle. When you release lhe mouse, a per-
manent rectangle is drawn on the
display. The outline rectangle is painted
using xor paint mode, you need not
repaint the entire background each time
lhe outline rectangle changes size. See
setXORModeO for more details.
H|drawRect Example |W[il|?f 1
FIGURE 168: Graphics.drawRect ().
import java.awt.*;
import java.awt.event;
import java.uti1.*;
class Main extends Frame {
MainQ {
super(“drawRect Example”);
add(new MainCanvas(), BorderLayout.CENTER);
setSize(200, 200);
show();
}
static public void main(String[] args) {
new Mai nO;
}
}
class MainCanvas extends Canvas {
Vector rects = new VectorO;
int startX, startY;
Rectangle oldRect, newRect;
MainCanvasO {
addMouseListenerfnew MouseEventHandler());
addMouseMotionListener(new MouseMotionEventHandlerO);
}
public void paint(Graphics g) {
update(g);
public void update(Graphics g) {
// First erase old rect.
if (oldRect != null) {
Graphics
draw Round Rect()
java.awt
g.setXORMode(Color.whi te);
g.drawRect(oldRect.x, oldRect.y, oldRect.width, oldRect.height):
g.setPaintModeO;
}
// Now paint rectangles.
for (int i-0; i<rects.size(): i++) {
Rectangle r - (Rectangle)rects.elementAt(i);
g.drawRect(r.x, r.y, r.width, r.height);
}
if (newRect 1= null) {
g.setXORMode(Color.whi te);
g.drawRect(newRect.x, newRect.у, newRect.width, newRect.height):
g. set^ai ntModeO ;
}
oldRect = newRect;
newRect nul1;
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
int x - evt.getXO, у - evt.getYQ;
startX = x;
startY - y;
newRect = new Rectangle(x, у, 1, 1);
repai nt();
}
public void mouseReleased(MouseEvent evt) {
int x = evt.getXO, у = evt.getYO;
rects.addFlement(new Rectangle(startX, startY,
х-startX, y-startY));
newRect - nulI;
repaintO :
}
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent evt) {
int x = evt.getXO, у = evt.getVO;
newRect = new Rectangle(startX, startY, х-startX, y-startY);
repaint();
}
}
}
drawRoundRect()
pl rpose Paints an outline of a rectangle with rounded corners on this graphics context.
sxni.ax public abstract void drawRoundRect(int x, int y, int width, int
height, int arcWidth, int arcHeight)
description 1’his method paints a 1-pixel-thick rounded-rectangular outline in the fore-
ground color within the rectangle defined by x. y. width, and height. If either
width or height is less than 0. the method call is ignored.
710
java.awt
krIUpiliV?>
dniwRou nd Recti )
arcWi dth and arcHeight specify the shape and size of the arc to use for each
corner. Logically, the arcs are formed by defining a rectangle of width arc-
Width and height arcHeight and calling drawOval О using this rectangle.
The rectangle is then sliced into four equal-sized quadrants. Each quadrant
yields an arc for one of the rectangle's corners. If either arcWidth or
arcHeight is 0, the painted rectangle will not have rounded corners. If either
arcWidth or arcHeight is less than 0. both arcWidth and arcHeight are set
to 0.
parameters
arcHeight The height, in pixels, of the ellipse used to generate the rounded corners,
arcWidth The width, in pixels, of the ellipse used to generate the rounded corners,
hei ght The height of the rectangular area in pixels.
width The width of the rectangular area in pixels.
x The x-coordinate in pixels.
у The v-coordinate in pixels.
SEE ALSO fi 1 IRoundRectO.
example This example implements a button
with rounded corners. If the button is
clicked, the outline and text change
color. See Figure 169,
FIGURE 169:
Graphics .drawRoundRectO.
import java.awt.*;
import java.awt.event. *;
class Main extends Frame {
Main О {
superC'drawRoundRect Example”);
addfnew MainCanvasO, BorderLayout.CENTER);
setSizeflSe, 80);
showf):
}
static public void main(String[] args) {
new Mai n();
}
}
class MainCanvas extends Canvas {
String label = “Round Button”;
boolean down;
MainCanvas () {
addMouset istenerfnew Mousel-ventHandler());
}
class MouseFventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
down = true;
repaintO ;
г
Graphics
drawStringt)
jaxa.awt
public void mouseReleased(MouseEvent evt) {
down - false;
repaintO ;
}
}
public void paint(Graphics g) {
int w getSizeO .width;
int h = get Size().height;
FontMetrics fm = g.getFontMetrics();
if (down) {
g.setColor(Color.red) ;
} else {
g. setColor(Color.Ыack);
}
g.drawRoundRect(0, 0, w-1, h-1, 20, 20);
g.drawString(label, (w-fm.stringWidth(label))/2,
(h-fm.getHeight())/2+fm.getAscent());
}
}
drawString()
PURPOSE Paints a string on this graphics context.
SYMAX public abstract void drawString(String string, int x, int y)
DESCRIPTION. This method paints the string at position хт у using the current font and fore- ground color. Only lhe characters of lhe string are painted: the background of lhe characters is not. The color of the characters is determined by this graphics context's foreground color. The position x, у specifics the baseline of the string (not the northwest corner of the string, as do most other methods). To paint the string such that the north- west corner of the string is at a point p. add the font ascent to p.y. For exam- pie: Font fm = getFontMetrics() ; // get metrics of current font drawStri ng(string, p.x, p.y+fm.getAscent();
PARAMF I ERS string X У The non-null string to be painted, fhe л-coordinate of the baseline in pixels. The у-coordinate of the baseline in pixels.
SEE ALSO Font.getAscent(), drawBytesO, drawCharsO.
712
Graphics
drawString()
java.awt
example:
This example de-
fines a canvas that
paints a line of text
on top of a colored
background. It also
creates a choice
component to let
AaBbCcDdEeFft
you adjust the size E1GCRE 170: Graphics. drawStringO •
of the font. See f ig-
ure 170.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ItemListener {
MainCanvas cv = new MainCanvasQ;
Choice choice = new ChoiceQ;
MainO {
super(‘‘drawString Example’’);
for (int i=4; i<60; i +- 4) {
choi ce. addltem(‘“'+i) ;
}
choi ce.select(0);
choi ce.addltemLi stener(thi s);
cv.setFontSize(4);
cv.setSize(300, 100);
add(cv, BorderLayout.CENTER);
add(choice, Borderlayout.SOUTH);
pack() ;
show();
public void itemStateChanged(IternEvent evt) {
String what = (Stri ng) (evt .getltemQ) ;
cv.set FontSize(Integer.parseint(what));
static public void mainCStringfl args) {
new Mai n();
class MainCanvas extends Canvas {
void setFontSize(int size) {
Font f = getFontO ;
if (f == null) {
f - new Font(“Serif”, Font.PLAIN, size);
} else {
f - new Font(getFont().getNameO, getFontO . getStyl e() , size);
}
setFont(f);
repai nt();
Graphics
fil!3DRect()
java.awt
public void paint(Graph!cs g) {
String s - “AaBbCcDdbeFfGgHhli 1 jKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz’';
FontMetrics fontM - g.getFontMetrics();
В
C
D
I:
F
g.setCo lor(Col or.white);
g.fi11Rect(0, 0, fontM.stringWidth(s). fontM.getHeightO);
g, set Col or(Co lor.bl ack);
g.drawString(s, 0. fontM.getAscentO):
}
}
filBDRectQ
Fi
I
.1
К
L
M
N
()
P
Q
R
S
T
L
V
W
X
Y
Z
pi rposi. Paints a rectangle that has a 3D outline on this graphics context.
syntax public void fi113DRect(int x, int y, int width, int height,
boolean raised)
description This method paints a rectangle defined by x. y, width, and height and a 3D
outline aroutul this rectangle. The left and top edges of the outline are within
the specified rectangle, but the right and bottom edges are just outside the
defined rectangle. Hence, this method actually draws width+1 horizontal lines
and height+1 \ertical lines. Note that it will paint a single pixel it width and
height are both 0. L*se fil 1 BDRectfx, у, width-1, height 11 to paint the
3D outline inside the specified rectangle. If either width or height is less than
0. the method call is ignored.
If raised is true, the 3D effect is done by lightening the left and top edges
and darkening the right and bottom edges. If rai sed is fal se. the left and top
edges are darker and the right and bottom edges are lighter. The lighter
and darker color shades are generated bx the Color.brigherO and
Co 1 or. darker О methods, respectively
PARAMETERS
hei ght The height of the rectangular area in pixels.
rai sed Specifies whether the 3D effect should appear raised or lowered.
width The width of the rectangular area in pixels.
x The д-coordinate in pixels.
у I he y<oordinate in pixels.
SEE also Color,bri ghterO , Col or. darkerO , draw3DRect() .
714
EXAMPLE
This example paints a 3D border just within
fillАгс()
the frame's paintable area. See Figure 171.
I’he 3D border is thicker than 1 pixel, ('lick-
ing toggles the 3D border between a raised
border and a lowered border.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame {
FIGURE 171:
Graphics.fil 13DRectQ .
boolean raised - true;
MainQ {
superQfi 11 3DRect Example’1):
addMouseL i stener(new MouseEventHandlerQ);
setSize(200, 200);
show():
public void paint(Graphics g) {
Insets insets - this.getlnsetsO;
int x = insets.left, у = insets.top;
int w getSizeO .width-insets, left-insets, right;
int h - getSize().height insets♦top-insets.bottom;
w -=₽ 1; // draw inside the rectangle.
h -= 1; // draw inside the rectangle.
g. setColor(getBackgroundQ);
g.fi 11 3DRect(x*-+-, y+*, w, h, raised);
class MouseEventHandler extends MouseAdapter {
public void mousePressed(Mousetvent evt) {
raised = Iraised;
repai nt О;
static public void main(String[] args) {
new MainQ ;
fillArc()
PCRPOSI-
SYNTAX
Paints a filled elliptical arc inside a rectangle on this graphics context.
public abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle)
Graphics
fi 11 Ai c()
java.aw I
A
В
C
D
E
Г
(i
H
I
J
К
I.
M
N
()
P
Q
R
S
T
I1
V
w
X
Y
Z
description This method paints a filled elliptical arc in the foreground color within lhe
rectangle defined by x. y, width, and height. If either width 01 height is
less than 0, the method call is ignored.
Logically, you form lhe arc first by using the drawOval () method to paint an
oval inside the rectangle. Next, define a horizontal line that originates from the
oval's center and extends to the containing rectangle's right edge. Then anchor
the line at the oval's center and rotate the line startAngle degrees from its
starting position. If startAngle is positive, rotate counterclockwise: if
startAngle is negative, rotate clockwise. The intersection of this line and the
oval's outline is the starting point for lhe arc.
Next, continue rotating lhe line arcAngle degrees. Again, if arcAngle is pos-
itive. rotate counterclockvvise: otherwise, rotate clockwise. All of the points
that intersect this line and the oval's outline during the rotation are included in
the arc.
PARAMEI I RS
arcAngle
hei ght
startAngle
wi dth
x
У
SEE ALSO
EX AM PI I
The angle in degrees (360 degrees in a circle) that specifies the end of the arc
arcAngle is relative to startAngle.
l he height of the rectangular area in
pixels.
The angle in degrees (360 degrees in a
circle) that specifies the start of lhe arc.
The width of the rectangular area in
pixels.
The \-coord inate in pixels.
The у-coordinate in pixels.
drawArc().
This example draws a 270-degree arc
starting at 0 degrees. Four labels arc
used to show the startAngle posi-
tions. See Fimire 172.
I IGI’RE 172: Graphics.fi11Arc().
import java.awt.
class Main extends Frame {
Main О {
super(“fi1]Arc Example”);
add(new MainCanvasQ, BorderLayout. CENTER);
add(new Label(“90”, Label.CENTER), BorderLayout.N0R1H);
add(new Label(“270”, Label.CENTER), BorderLayout.SOUTH);
add(new Label(“0”), BorderLayout.EAST);
add(new Label(“180”), BorderLayout.WEST);
setSi ze(200, 200);
show();
}
716
iava.awt
urapm
fillOv a
static public void main(String [] args) {
new Mai n ();
}
}
class MainCanvas extends Component {
public void paint(Craphics g) {
g.fi11Arc(0, 0, getSize().width, getSize().height, 0, 270);
}
}
fillOvaK)
purpose Paints an oval area on this graphics context.
syntax public abstract void fi1lOval(int x, int y, int width, int
hei ght)
descrip Iion This method paints an oval area on this graphics context. The oval area is
defined to be the largest oval that fits into the rectangle defined by x. y. width,
and height, It is filled with the foreground color. If either width or height is
less than or equal to 0. the method call is ignored.
PARAMETERS
height The height of the rectangular area in pixels,
width The width of the rectangular area in pixels,
x The л-coordinate in pixels.
у The v-coordinate in pixels.
seeaeso drawOval ().
EXAMPLE
This example creates and initializes an
off-screen image with a circle-shaped
pattern. See Figure 173. The image is
then used to "tenure" the frame's paint-
able area. For demonstration purposes,
the image is scaled to half its size when
painted.
p^fillOval Example
import java.awt.-;
class Main extends Frame {
Main О {
super(“fi11 Oval Example”.):
setSi ze(400, 200);
show Г) ;
FIGI RE 173: Graphics . fil lOval () .
public void painr(Craphics qj {
Graphics
fil IPolygont)
java.awt
int iSize = 50;
Insets insets = thi s. getlnsetsO ;
int startx = insets.left, starty = insets.top;
int w = getSizeO.width-insets, left insets.right;
int h = getSizeO.height-insets.top-insets.bottom;
Image image = createlmage(iSize);
for (int y=0; y<h; у +- iSize) {
for (int x=0; x<w; x += iSize) {
g.drawlmage(image, startx+x, starty+y, iSize, iSize, null);
}
}
}
Image createlmage(int size) {
Image im - createlmage(size, size);
Graphics g - im.getCraphics();
Rectangle r = new Rectangle(size, size);
g. setColor(getBackgroundO) ;
g.fi1lRect(0, 0, size, size);
while ( ! r. i sFmptyO) {
int c ~ r.x * 2 * 63 / size;
g.setColor(new Color(255 c, 150, Ctl50));
g.fi1lOval(r.x, r.y, r.width, r.height);
r.grow(-lt 1);
}
return im;
}
static public void main(StringLJ args) {
new h^ai n() ;
}
filiPolygonf)
PURPOSE Paints a closed polygon on this graphics context.
SYNTAX public void fi11 Polygon(Polygon p) public abstract void fil1Polygon(int[] xPoints, int[] yPoints, int nPoints)
DESCRIFIION A polygon is a collection of lines connecting a series of points. The polygon is closed. This means a line is automatically drawn between the first and last points. This method paints a polygon in the foreground color using the speci- fied set of points. The points are either specified by the polygon polygon or by two arrays xPoints and yPoints. In the latter form. xPoint[i] and yPoi ntsfi ] together specify a point in the polygon. The series of points from index 0 to nPoi nts-1 specify the ordered list of points in the polygon.
718
j;i x a.aw i
Graphic
I i 11 Pol ygon i
If the number of points is fewer than 3. lhe method call is ignored. It parts of
lhe polygon o\erlap. the e\en-odd fill rule (otherwise known as an alternating
rule) is applied.
PARAMI IFRS
nPoi nts The number of points in xPoi nts and yPoi nts.
polygon The non-null polygon to paint.
xPoints The non-null array of.v-coordi nates lin pixels) in lhe polygon.
yPoints The non-null array of/-coordinates i in pixels) in lhe polygon.
SEE ALSO
drawPolygon(), Polygon.
example This example paints a filled polygon.
See Figure 174. When the mouse is
clicked or dragged, a new point is
added to the polygon. Double-clicking
clears the polygon.
fillPolygon Example ВПЯЕЗ
import java.awt.-';
import java.awt.event.*;
class Main extends Frame {
Polygon polygon = new Polygon();
Main() {
super(“fi11 Polygon Example”);
FIGI RE 174:
Graphics.fill Polygon()•
addMouseLi stener(new' MouseEventHandl er()) ;
setSize(200, 200);
show();
public void paint(Graphics g) {
g.fi11 Polygon(poiygon);
}
class vouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
Insets insets = getlnsetsO;
int x = insets.left, у = insets.top;
if (evt.getClickGountО 1) { // double-click
polygon = new Polvgonf);
}
poi ygon . addPoi nt ( x - evt.getXO. У + evt.getYO);
repai nt О ;
}
static public void main(String [ j argsj {
new Mai nО ;
1
Graphics
java.awt
fillRccf ()
fill Rect()
purpose Paints a rectangular area on this graphics context.
symax public abstract void fillRect(int x, int y, int width, int
height)
nt -.scrip i ion This method paints the area defined by x. y. width, and hei ght with the fore
ground color If either width or height is less than or equal to 0, the inethoi
call is ignored.
PAR.AMrit.RS
height
width
x
У
SEE- ALSO
The height of the rectangular area in pixels.
The width of the rectangular area in pixels.
The v-coordinate in pixels.
The у-coordinate in pixels.
clearRectO, drawRectO.
EXAMPLE
This example creates
a frame with two
choices and a drawing
area. See Figure 175.
The choices specify
the color and shape
of a figure. Clicking
anywhere in the draw-
ing area draws the
specified figure at the
mouse coordinates,
fillRect() is used
to draw the rectangle
and squares.
FIGURE 175: Graphics. filIRectO .
import java.awt.*;
import java.awt.event.*;
U
V
w
X
Y
Z
class Main extends Frame {
String[] figureNames = {"circle", ‘'oval", ‘’square’’, "rectangle’’};
String[] colorNames =- {‘‘red’’, "green”, "blue”, “yellow"};
Color[J colorValues = {Color.red, Color.green,
Color.blue, Color.yellow};
Choice chFigure » new ChoiceO;
Choice chColor - new ChoiceO;
int curX, curY;
MainO {
super(“fi11Rect Example”);
Panel p - new Panel(new Gridlayout(1, 0));
720
Graphic
fillRoundRecU
java.awt
for (int i-0; i<figureNares. length; i + O {
chFi gure.addltem(f i gureNames [i j) ;
}
for (int i-0; i<colorNames.1ength; i++) {
chColor.additem(colorNames'i ]);
}
p.add(chColor);
p.add(chFigure);
add(p, BorderLayout.NORTH);
addMouseListener(new MouseEventLi stenerO);
setSize(300, 300);
show();
public void update(Graphics g) {
g. setCol or (colorValues [chCol or. get Sei ectedlndexO ]);
switch (chFigure .getSel ectedlndexO) {
case 0: // circle
g.fi!10val(curX, curY, 30, 30);
break;
case 1: // oval
g.fi1lOval(curX, curY, 30, 50);
break;
case 2: // square
g.fi11Rect(curX, curY, 30, 30);
break;
case 3: // rectangle
g.fi1lRect(curX, curY, 30, 50);
break;
}
class MouseEventListener extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
curX = evt.getXO ;
curY = evt.getYO ;
repaintO ;
}
static public void main(String[J args) {
new Main();
fillRoundRectf)
purpose Paints a rectangle with rounded corners on this graphics context.
syntax public abstract void fi11RoundRect(int x, int y, int width, int
height, int arcWidth, int arcHeight)
Graphics
fill Round RecU)
java.awt
DESCRIPTION
This method paints a rounded rectangle in the foreground color within the rect-
angle defined by x. y. width, and height. If either width or height is less
than 0. the method call is ignored.
arcWidth and arcHeight specify the shape and size of the arc to use for each
comer. Logically. you form the arc by defining a rectangle of width arcWidth
and height arcHeight and calling drawOval () using this rectangle. Then
slice the rectangle into four equal-sized quadrants. Each quadrant \ields an arc
for one of the rectangle's corners. If either arcWidth or arcHeight is 0. the
painted rectangle will not have rounded corners. If either arcWidth or
arcHeight is less than 0. both are set to 0.
PARAMEIERS
arcHeight
arcWidth
height
wi dth
x
У
SI F ALSO
l ХАМП.Е
The height, in pixels, of the ellipse used to generate the rounded corners,
the width, in pixels, of the ellipse used to generate the rounded corners.
The height of the rectangular area in pixels.
I'he w idth of the rectangular area in pixels.
The л-coordinate in pixels.
The y-coordinate in pixels.
d rawRou ndRec t().
This example implements a simple
framework for measuring the cost of
operations in the Graphics class. See
Figure 176. You select the graphics oper-
ation to time by using the choice compo-
nent at the bottom of the window.
Clicking the main display area starts a
timer thread and calls the repai nt О
method. 7'his method causes the
pai nt О method to be called, pai nt О
enters a tight loop, executing the
selected operation. I'he timer thread
waits for 5 sec and then signals the
H^fillRoundRect Ex ЕИ
ifiDRoimdRect
1Ы
FIGIRE 176:
Graphics.fillRoundRectО.
pai nt() method to exit its tight loop. The results are then printed to standard
output.
import java.awt.’;
import java.awt.event;
class Main extends Frame -implements Item! istener {
MainCanvas cv = new MainCanvasО 5
Choice c z- new ChoiceO;
MainO {
super(“fillRoundRect Example");
add(cv, Border!ayout.CENTER);
722
java.awt
ii rapn ics
fill RoundRect()
c.additem("create/dispose”);
c . addItem(“drawRect ”) ;
c.addItem(”drawRoundRect") ;
c. addltem("f i 11 Rect") ;
c.addltem("fi1IRoundRect");
add(c, BorderLayout.SOUTH);
c.addTtemListener(this);
setSize(200, 200);
show() ;
}
public void itemStateChanged(ItemFvent evt) {
cv.operation = c.getSelectedlndexQ ;
}
static public void mai n(Stri ngfl args) {
new Mai n();
}
}
class MainCanvas extends Component implements Runnable {
int operation;
Thread timerThread;
MainCanvasQ {
addMouseListener(new MouseEventHandlerQ);
}
public void paint(Graphics g) {
int w - getSize().width-1;
int h = getSizeO .height-1;
if (timerThread !=? null) {
int count = 0;
long startTime - System. currentTiireMi 11 i s() ;
switch (operation) {
case 0:
while (timerThread null) {
Graphics g2 = g.createO;
g2.dispose();
count+*;
}
case 1:
while (timerThread !- null) {
g.drawRect(0, 0, w, h);
count*+;
}
case 2:
while (timerThread !- null) {
q.drawRoundRect(0t 0, w, h, 20, 20);
count-»-*;
}
case 3:
while (timerThread null) {
g.fi11Rect(0, 0T w, h);
count++;
}
java.awt
Graphics
finalize!)
case 4:
while (timerThread 1- null) {
g. fi 1iRoundRect(0, 0t w, h. 20t 20);
count+*;
}
}
A Syst em.out.pri nt ((double)count"1000.0
/ (double)(System.currentTimeMi1lis()-startTime));
В System.out.println(“ paints/second");
}
C }
D public void run() {
try {
li Thread. si eep(5000) ;
} catch (InterruptedException e) {
F }
timerThread = null;
}
H class ^ouseEventHandler extends MouseAdapter {
public void mousePressed(MouseFvent evt) {
I if (timerThread == null) {
timerThread - new Thread(MainCanvas.this);
J tirrerihread. start();
repai nt();
К }
}
M
N
° finalize()
I4RP( >Sl£
Q SYMAX
R DESOR1PIK
S
T
L OVERRIDES
V SEE A I.SO
W EX AM PI E
Releases this graphics context's system resources.
public void finalize()
T his method simply calls the di sposeO method. After this call, this graphics
context can no longer be used. This method is normally called by the garbage
collector after this graphics context has been reclaimed.
j ava. 1 ang.Object.f i nali ze ().
di spose().
See java.1ang.Obj ect.fi nali ze().
getClip()
Retrieves this graphics context's clipping area.
stmax public abstract Shape getClipO
724
j a v <i. ci w i
getClipBoundsO
DESCRIPTION The clipping area defines a set of pixels that can be affected by painting opera- tions; any painting done outside the clipping area is ignored. As of Java 1.1.2, the clipping area is restricted to a rectangle. In future releases, the clipping area will be able to be any shape.
returns A possibly null Shape object containing the clipping area.
SEE A1.SO clipRectO, getClipBoundsO, setClipQ, Shape.
EXAMPLE See the Wi ndow class example.
getClipBounds()
PURPOSE Retrieves the clipping area’s bounds of this graphics context.
SYNTAX public abstract Rectangle getClipBoundsO
DESCRIPTION This method returns a rectangle that will contain the dipping area. The return result may be null, in which case the clipping area includes the entire visible area of the drawing surface.
RETURNS A new, possibly null Rectangle object containing the bounds of the clipping area.
SEE AI50 clipRectO, getClipO, setClipO.
exampit: See the Wi ndow class example.
getClipRect()
DEPRECATED
PURPOSE Replaced by getClipBoundsO.
SYNTAX public abstract Rectangle getClipRectO
RETURNS A new Rectangle object containing the clipping area. The return value may be null.
DEPRECATION Replace the usage of this deprecated method, as in Rectangle rect = graphics.getCl ipRectQ ; with Rectangle rect = graphics.getClipBoundsQ;
getColor()
purpose Retrieves this graphics context’s foreground color.
syntax public abstract Color getColorO
Graphics
java.au i
getFontf)
re-1 i rns I'he non-nul 1 foreground color.
SEX ALSO Color T setColorO.
EXAMPLE
A
В
C
D
E
F
This example uses getColorQ to get
the current foreground color of the
graphics context and draws some dots
of a different color than the current
color. See Figure 177.
irrport java.awt.5';
getCoior Example EJ
H
I
J
К
L
M
N
О
P
Q
R
S
class Main extends Frame { . .................—
int dotSize 15, hgL’RE 177: Graphics.getColor()-
MainO {
super(“qetCol or Example”);
setSize(150, 150);
show();
}
public void paint(Graphics g) {
Insets insets - this.getlnsetsO ;
int w - getSizeO.width-insets.left-insets.right;
int h = getSizeO.height-insets.top-insets.bottom;
Color orig g.getColor();
int red = orig.getRedO , blue - orig.getBlueO , green = orig.getGreenO ;
int у - 50, x ~ dotSize;
for (int i=0; i<10; in-) {
g.setColor(new Color(red+-10, green*-10, blue*=10));
g.fi1lOval(insets.1 eftx%dotSize, insets.top+y-y%dotSize,
dotSize, dotSize);
x t- dotSize;
}
}
static public void main(Stringfl args) {
new Mai n();
}
1
T
I1
getFont()
W PURPOSE.
X SYNTAX
Y RETURNS
7 SEE AL SO
Retrieves this graphics context's font,
public abstract Font getlontO
The current non-nul 1 font.
Font, setFontO.
726
Jd Vil.itWI
gctFontMetricsf)
example This example dis
plays the attributes
of the frame s default
font. See Figure 17K.
’ getFont Example_____________________1
family=Dialog name=Dialog style=0 size=12
import java.awt.*; FIGURE 178: Graphics.getFontО
class Main extends Frame {
Mainf) {
super(“getFont Example*');
setSize(300, 100);
showQ ;
}
public void paint(Graphics g) {
Insets insets -= getlnsetsO;
Font f = g.getFontO;
FontMetrics fm = g.getFontMetrics(f);
g.drawStri ng(“fami ly=’*-rf .getFamil y()t" name=”*f. getNameO
i” style-"+f.getSty1e()♦" size-"+f.getSize(),
insets.1 eft410, insets.top+20);
}
public static void main(String[J args) {
new MainO ;
}
}
getFontMetricsf)
PURPOSE Retrieves the font metrics for a font.
syntax public FontMetrics getFontMetrics() public abstract FontMetrics getFont^etrics(Font font)
DESCRIPTION Fhe two forms of this method retrieve the font metrics for the font font. If font is not specified, it defaults to this graphics context's current font.
parameters font I’he non-null font.
returns The non-null font metrics for font.
SEEALSO Font, FontMetrics, getFontO.
example See the FontMetri cs class example.
java.awt
Graphics
Graphics()
Graphicsf)
A
В
C
D
E
F
perposi: Constructs a new graphics context.
syntax protected GraphicsO
description The background and foreground color and font arc inherited from the drawing
surface. The initial paint mode is normal.
A graphics context cannot be directly created from this constructor (note that
the constructor is protected). The graphics context is supplied by classes that
provide a drawing surface; for example. Component .getGraphicsO and
Image .getCraphi cs().
see M s<) createQ.
example See Component.getGraphicsO- Image.getGraphics().
H
I
J
К
I.
M
N
О
p
Q
R
S
T
и
V
w
X
Y
Z
setClip()
Pt rpose Sets this graphics context's clipping area.
syxux public abstract void setClip(int x, int y, int width, int height)
public abstract void setClipfShape clipshape)
DESCRIPTION
PARAMETERS
cli pShape
hei ght
wi dth
x
У
This method sets the new clipping area
to be the rectangle defined by x, y,
wi dth, and hei ght or the shape cl i p-
Shape. See the class description for
details on lhe clipping area.
The Shape object to use for the clip-
ping area. Only instances of Rectan-
gle are currently supported.
The height of the rectangle in pixels.
The w idth of the rectangle in pixels.
The л-coordinate in pixels.
The у-coordinate in pixels.
SEEi also getCli p() t getCl i pBoundsO ,
setClipO.
setClip Example F •' F7
FIG I RE 179: Rotating Polygon.
example This example creates a random polygon and continuously rotates it. You can
observe part of lhe rotating polygon by dragging a viewport around the screen.
The viewport is implement by means of a clipping area. Just before the poly-
gon is painted on the graphics context, a clipping area is set to the exact size of
728
Jl<*4A.UWl KfICVjJlllV
setClipt
the viewport. This causes only the part of the polygon inside the viewport to be
seen. See Figure 179.
import java.awt.-;
import java.awt.event.♦;
class Main extends Frame {
// Returns a random number in the range [0 .. r)
static int random(int r) {
return (int)Math.floor(Math.random()*r);
}
public static void main(String[] args) {
Frame f = new Frame("setClip Example”);
Polygon polygon = new PolygonO;
// Create some random points. The points are no
// more than 100 pixels from the origin.
for (int i=0; i<25; i++) {
polygon.addPoi nt(random(200)-100, random(200)-100);
}
// Layout and show components.
f.add(new PolygonRotator(polygon), BorderLayout.CENTER);
f.setSize(200, 200);
f.show();
}
}
class PolygonRotator extends Canvas implements Runnable {
Polygon origPoly;
Polygon curPoly;
Rectangle view = new Rectangle(0, 0, 100, 100);
PolygonRotator(Polygon polygon) {
origPoly = polygon;
// Listen for mouse events.
addMouseLi stener(new MouseEventHandler());
addMouseMotionListener(new MouseMotionEventHandlerO);
// Start the rotating thread.
(new Thread(this)).start();
}
public void paint(Graphics g) {
// Draw an outline around the view.
g.drawRect(view.x-1, view.y-1, view.width+l, view.height+1);
// Set the clipping area.
g.setClip(view.x, view.y, view.width, view.height);
// The following would have worked just as well.
// g.c1ipRect(view.x, view.y, view.width, view.height);
// Now paint the polygon.
if (curPoly 1- null) {
// Place the polygon at the center of the canvas.
g.translate(size(),width/2, sizeC).height/2);
java.awt
Graphics
setClipf)
A
В
C
D
к
F
H
I
J
К
L
M
N
О
P
Q
R
S
T
I’
V
w
X
Y
7.
g.drawPolygon(curPo 1 y);
}
}
// Returns a rotated copy of p at the angle a.
Polygon rotate(Polygon pt double a) {
Polygon q = new PolygonQ;
q.xpoints - new int Гр-npointsj;
q.ypoints = new int[p.npointsJ;
q.npoints - p.npoints;
for (int i-0; i<p.npoints; i+*) {
q.xpointsfij -
(i nt) (p. xpoi nt s[i j *Math. cos(a)-p. ypoi nts [i ] ’'Math. si n(a));
q.ypoints[i] -
(int) (p. xpoi nts [i J *Math. si n(a)*p. ypoi nt s [i ] ’'Math. cos (a)) ;
}
return q;
}
// If non-null. location of the down click.
Point mouseDown;
class vouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
if (view, inside(evt.getXQ T evt.getYO)) {
// Record the down click on if inside view.
mouseDown - evt.getPoint();
mouseDown.translate(-view.x, -view.y);
}
public void mouseReleased(MouseEvent evt) {
mouseDown = null;
}
class MouseMotionEventHandler extends ^louse^otionAdapter {
public void mouseDragged(MouseEvent evt) {
if (mouseDown != null) {
// ^love the view,
view.move(evt.getX()-mouseDown.x, evt.getYO-mouseDown.y);
repaintO;
}
}
}
public void run() {
double angle - 0.0;
try {
while (true) {
// Create a rotated version of the original polygon.
curPoly - rotate(origPolу, angle);
// Change the angle at .1 radian every tick,
angle += .1;
repai nt():
Thread.sleep(100);
}
} catch (Exception e) {
e.pri ntStackT race();
730
Graph к
self 'olor
setColorf)
pirposi. Sets this graphics context's foreground color.
s>xta\ public abstract void setColor(Color color)
descripiiox This method sets this graphics context's foreground color to color.
PARAMETERS
color The non-null new foreground color.
see also Color, getColorQ.
example. This example is a set of random colored dots.
A thread is created to continual 1\ change the
colors of lhe dots. Sec Figure 1K0.
import java.awt.
class Main extends Frame implements Runnable {
int dotSize = 15;
MainQ {
super(“setColor Example”);
setSize(150, 150);
show() ;
(new Thread(this)).start();
}
// Returns an integer in the range [0..Г-1).
int random(int r) {
return f i nt)(Math.f1oor(Math.random()' r));
}
public void update(Graphics g) {
Insets insets = this.getlnsetsО;
int w = getSize().width-insets.left-insets.right;
int h = getSizeO•height-insets.top-insets.bottom;
for Tint i=0; i<10; i**) {
int x = randomfw), у = randomfh;;
g.setColor(new Col or(randomC256), random(256). random(256)) j:
g . fi 11 Oval (i nsets . 1 ef t + x -x’;'dot Si ze, insets. top+y-y%dotSi ze ,
dotSi ze. dotSi zej ;
setColor Ex... НИЁ1ЕЗ
« ttt* S *
•••
I IGLRE 180:
Graphics.setColor().
publi c void run О {
while ft rue) {
try {Thread.sieepC100j;} catch {Exception e) {}
repai nt ();
java.awt
Graphics
selF’onK)
static public void mai n(St ri ng [] args) {
new Mai n();
}
A }
В
C
[)
E
Г
setFont ()
PURPOSE
Sets this graphics context's font.
syntax public abstract void setFont(Font font)
G
description This method sets this graphics context's font to font. The font affects onh the
H
I
J
К
L
M
N
()
P
Q
R
S
T
и
V
w
X
Y
Z
PARAMETERS
string drawing operations.
font The non-nul 1 font.
see also drawBytes(), drawChars(),
drawString(), Font, getFontO.
example This example paints some text at differ-
ent point sizes. The text is white
painted on a black background. See
Figure 181.
import java.awt.’';
class Main extends Frame {
Main О {
super("setFont Example”);
setBackground(Color.bl ack);
setForeground(Color.white);
setSize(200, 200);
showQ ;
}
set Font Example
TittKJFxMJiri ill 2 pOdCJ
TimesRoman at 16 points.
TimesRoman at 24 ]
TimesRoman al
TimesRoma
T irnael? nr
FIGI KE 1X1: Graphics . setFont О .
public void paint(Craphics g) {
Insets insets = getlnsetsO;
int x = insets.left, у = insets.top;
for (int i=8; i<8*10; i+= 8) {
Font f = new Font("Serif”, Font.PLAIN, i);
FontMetrics fm = g.getFontMetrics(f);
g.setFont(f);
g.drawString(f.getName()+” at " + if” points.",
x, y+fm.getAscent());
у += fm.getHeight();
}
}
static public void main(String[] args) {
732
ja\a awl
Graphic*
wlPaimMode(
new Mai nf);
}
}
setPaintMode()
PURPOSE Sets this graphics context to normal paint mode.
SYNTAX public abstract void setPaintModeO
description This method sets this graphics context to normal paint mode. See the class description for details about paint modes.
SEE ALSO setXORModeO •
EXAMPLE See setXORModeO.
setXORModef)
PURPOSE
Seis this graphics context to xor paint mode.
SYNTAX
public abstract void setXORMode(Color xorColor)
DESCRIPTION
parameters
xorColor
This method sets this graphics context
to xor paint mode using the xor color
xorColor. See the class description
for details of how xor paint mode uses
the current foreground color and xor-
Color. Pixels of colors other than
those two colors will he changed in an
unpredictable, but reversible, manner.
If you draw the same figure twice, all
pixels will be restored to their original
\ alues.
The non-null xor color.
I K,I RE 182: Graphics. setXORModeO .
SEE ALSO
setPai ntModeO •
exampi El This example creates a four-band colored background and paints a black circle
on the background in xor paint mode. See Figure 182. l he circle can be mo\ed
around the background so that you can sec lhe xor mode paint effect. Black is
xor'd with green so that when the circle is on green, il appears black and when
it is on black, it appears green. When the black circle is on some other color, il
simply appears in some color other than black Four lines in different colors
Graphics
java.awt
setXORModei)
are also painted to see the xor inode paint effect. Notice that the green Itn
not show up at all.
import java.awt.";
import java.awt.event.*;
class Main extends Frame {
int curX, curY, newX, newY;
Main() {
superC'setXORMode Example”);
setSize(200, 200);
addMouseMotiont istener(new MouseMotionLventHandlerO) ;
showO ;
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
newX * evt .getX() ;
newY = evt.getYO;
repaint О;
}
}
void drawLines(Graphics g, int x, int y, int w, int h) {
g.setXORMode(Color.green);
g.setColor(Color.red);
g.drawline(0, 0, x, y);
g.setColor(Col or.green);
g.drawLine(w, 0, x, y);
g.setColor(Col or.blue);
g.drawl ine(0, h, x, y) ;
g.setColor(Color.yellow);
g.drawLine(w, h, x, y);
g.setColor(Color.black);
g, f iHOval (x-20, y-20, 40, 40);
}
public void update(Craphics g) {
Insets insets = thi s. getlnsetsO ;
int w = getSizeO.width insets.left-insets.right;
int h = getSize().height-insets.top-insets.bottom;
// Erase old image.
drawLines(g, curX, curY, w, h);
// Paint new one.
drawlines(g, newX, newY, w, h):
curX - newX;
curY = newY;
}
public void paint(Graphics g) {
Insets insets -• this.getlnsetsO ;
int startx = insets.left, starty = insets.top;
int w = getSize().width-insets.1 eft-insets.right;
int h - getSize().height-insets.top-insets.bottom;
g. setPai ntModeO ;
734
jiivci.awi
Ml ctpIII
toStri ng(;
} g.setColor(Color.red); g.fi11Rect(startx, starty, w/3, h); g.setColor(Color.green); g.fi1IRect(startx*w/3, starty, w/3, h); g.setColor(Col or.blue); g.fi1lRect(startx+w*2/3, starty, w/3, h); g.setColor(Color.black); g.fi HRect(startx, starty+h/3, w, h/3); drawLines(g, newX-curX-w/2, newY=curY=h/2, w, h):
static public void main(String[] args) {
new Main();
}
}
toString()
PURPOSE Generates the string representation of this graphics context s state.
SYNTAX public String toStringO
DESCRIPTION This method generates the string representation of this graphics context. The string contains this graphics context’s class name and lhe results of calling paramStringO. This method is typically used for debugging.
RETURNS A non-null string representing this graphics context’s suite.
OVERRIDES java.lang.Object,toString()
SEE ALSO Component. paramStringO.
EXAMPLE. See java.1ang.Object.toString().
translate!)
PURPOSE Moves this graphics context’s origin.
SYNTAX public abstract void translate(int x, int y)
description This method moves this graphics context’s origin to x, у relative to the current origin. The coordinates of all subsequent graphics operations are interpreted relative to the new origin. Note that the new origin is located relative to the current one. So if you call translate^, 5), translate^. 0) will not restore the origin to its original location. To do that, you need to call translatef- 5, -5).
java.aw I
Graphics
translated )
PARAMETERS
X
У
The v-coordinate in pixels.
The v-coordinate in pixels.
EXAM PI 1
This example creates a component that
paints a histogram and a scroll bar to
scroll the histogram. See Figure 1 S3.
The histogram is always twice as high
as the available display area. I hc his-
togram is always painted in its entirety,
and the scroll bar shifts the origin
using the translateC) method. You
can select one of the histogram bars by
clicking it. The example also demon-
strates how to translate a position that
is in mouse coordinates into graphics
context coordinates.
FIGI RE 1X3: Graphics . transl ate О
import java.awt.'';
import j ava. awt. event;
p class Main extends Frame implements AdjustmentListener {
MainCanvas cv = new MainCanvasQ;
M Scrollbar sb = new Scrol1 bar(Scrol1 bar.VERTICAL, 0, 40, 0. 100);
N Main О {
super(“translate Example’’);
О add(cv, BorderLayout.CENTER);
add(sb, BorderLayout.EAST);
P
sb.addAdjustmentLi stener(thi s);
q setSize(200, 200);
show();
R 1
3 public void adjustmentValueChanged(AdjustmentEvent evt) {
System.out.pri ntln(sb.getValue());
у cv.setOrigin(0, -cv.getSize() .height * sb.qetValue() / 100);
}
U
static public void main(String[] args) {
V new Mai n();
}
W }
X class MainCanvas extends Component {
int thick;
Y doublet] values = new double[100];
int curX, curY;
7 int originX, originY;
MainCanvasO {
for (int i=0; i<values.1ength; i++) {
736
JdVd.dWt
KIl dpi J к.
translaie(
values [i] - Math.random();
}
addMousel istener(new MouseEventHandler());
}
void setOrigin(int x, int y) {
originX = x;
originY = y;
repaintO ;
}
public void paint(Graphics g) {
int w = getSizeO .width;
thick - getSizeOheight*2/values.length;
g.translate(originX, originY);
for (int i=0; i<values.length; i++) {
int c - (int)(Math.floor(255 * values[i]));
if (curY >= i * thick && curY < (i+1) : thick) {
g.setColor(Color.red);
} else {
g.setColor(new Color(c, c, c));
}
g.fi1iRect(0, i * thick, (int)(w * values'ij), thick);
}
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
curX = evt.getXO - originX;
curY = evt.getYO - originY;
repaintO;
}
}
}
java.awt
GridBagConstraints
4.... (y.-A J
A * GridftayCo'r.strains» | • __ _________
в 4 —J
c
Syntax
public class GridBagConstraints implements Cloneable, Serializable
[•
i Description
НИ A gridbag is a collection of components laid out using the gridbag layout manager (see
e Gri dBagLayout). Each component in the gridbag has a set of constraints that determines its
H size and position in the gndbag. These constraints are defined with a GridBagConstraints
j instance and are associated with a component. There are seven gridbag constraints.
J Fill
К The fill constraint determines whether to stretch a component to fill the component's display
! area. There are four fill types. See fill later in this section for an example that uses these till
types.
M
A tichor
If a component is not stretched to completely fill its display area, the audit n- constraint speci-
0 fits the component's position in its display area. There are nine anchor types. See anchor later
P in this section for an example that uses these anchor types.
Q Size
R A component can span more than one column or row, l he size constraint specifies the number
of columns or rows that the component occupies.
T Internal Padding
Fhe internal padding constraint is used to adjust the width and height of a component after
Component, mi nimumSize О or Component. preferredSizeO is called. Separate values con-
v trol the width and height. See 1 padx later in this section for an example that uses internal padding.
w
Insets
The insets constraint for a component is applied to a component's display area. An inset has
Y four values to control the inset at the four edges. A positive inset at an edge reduces the display
area at that edge. See i nsets later in this section for an example that uses insets.
738
java.awt GridBagConstn
Position
A component can be positioned at a particular cell location in the gridbag. Cells in the gridbag
are addressed by v- and y-coordi nates.
Weights
Each component in the gridbag has a non-negative gridbag weight constraint. Together, the
component weights define a weight for each column and row in the gridbag. The calculation
fordoing this is discussed later in this section.
The column and row weights determine how columns and rows stretch and shrink when
the container is made larger or smaller and how extra space is distributed among the columns
and rows. The extra space is determined by subtracting the container size from the preferred
size for the gridbag. The preferred size of the gridbag is calculated by laying out all of the
components in the gridbag using their preferred sizes. Here is how the extra space is distrib-
uted. First, no space is given to any row or column that has zero weight. The amount that a col-
umn (or row7) gets depends on its weight in relation to the total weight for all of the columns
(or rows) of the gridbag. For example, if the weight of a column c is 1 and the total weight is
10 (including c’s weight), column c gets one-tenth of the total extra space.
If the total weight for all of the columns (or rows) is 0. then the extra space is distributed
around the gridbag. For example, if the total w eight of all of the columns is 0. the gridbag will
be horizontally centered in its container.
It is important to note that if two components C and I) both have weight 1, they will not
necessarily be the same size. Only if C's and D's preferred sizes are identical will they be the
same size. This is because only the extra space (after Cs and IXs preferred sizes are subtracted
from the total available space) is distributed to C and I). For example, if C's preferred size is
10, D's preferred size is 20, and the extra space is 40 pixels, then C will be 30 pixels wide and
D will be 40 pixels w ide.
The following steps describe how column and row weights are derived from component
weights:
I. Consider all of the components in a column whose grid widths are 1. The weight for that
column is the maximal weight for those components.
2. Now consider all of the components w hose grid widths are greater than 1. Consider them
in the order that they were inserted into the container. Suppose component C spans col-
umns ei.ej and that the combined weight of these columns is и. If C s weight is less than
w, nothing happens. If C’s weight is greater than и. the extra weight is distributed among
the columns. The distribution is based on the relative weight of the columns, so if one col-
umn has a weight of 1 while another has a weight of 5. the first column gets one-sixth of
the extra weight. After the extra weight has been distributed, any remaining weight is
given to the last column of the span. Л zero weight column never gets any extra weight
unless the column is the last column of the span and all of the columns in the span have
zero weights. These rules also apply to each row.
(i ridBagConstrai nts
java.awt
If the container’s dimensions are smaller than the gridbag s preferred size, the gridbag lay-
out manager either attempts to shrink some rows or columns smaller than their preferred sizes
or simply clips the components so that they appear off the container’s visible area. You cannot
control how the gridbag layout manager decides to fit a gridbag layout into an area smaller
than the preferred size.
MEMBER SUMMARY 1
Constructor GridBagConstrai nts() i Constructs a new GridBagConstraints instance.
Size Type Constant Fields RELATIVE 1 Specifies that subsequent cells in the row or column be occupied. । except for the last cell.
REMAINDER Specifics that subsequent cells in the row or column be occupied. |
1 Fill Type Constant Fields
I BOTH Specifies a fill in both directions.
1 NONE Specifies no fill (the default).
1 HORIZONTAL Specifies a horizontal only fill.
| VERTICAL Specifies a \ertical-only till.
1 Anchor Type Constant Fields
I CENTER Specifies center positioning.
। EAST Specifies east positioning.
| NORTH Specifies north positioning.
। NORTHEAST Specifies northcast positioning.
। NORTHWEST Specifies northwest positioning.
| SOUTH Specifies south positioning.
i SOUTHEAST Specifies southeast positioning.
1 SOUTHWEST Specifies southwest positioning.
| WEST Specifics west positioning.
| Fields
1 anchor Holds the component's anchor constraint.
। fill Holds the component’s fill constraint.
j gridheight Holds the component's height in cells.
1 gridwidth Holds the component's width in cells.
1 gridx Holds the a-coordinate cell location for the component.
1 gridy Holds the y-coordinalc cell location for the component.
. insets Holds the insets constraints for the component.
1 ipadx Holds the internal padding for the component's width.
1 ipady Holds the internal padding for the component's height.
। weightx Holds the component's column weight.
1 weighty I Holds the component s row weight.
740
java.awt
iinanagv onsiramis
anchoi
MEMBER SUMMARY
Cop} Method cloneO Creates a cop\ of the gridbag constraints.
See Also
java.io.Serializable.
Example
See GridBagLayout.
anchor
pi rposi. Holds the component’s anchor constraint.
syntax public int anchor
descrip'I ion There are nine anchor types, one for r^n each edge and each corner of a display L=^J area and one for the center of the dis- play area: CENTER. EAST. NORTH. NORTHEAST. NORTHWEST. SOUTH. anchor Example BRIE
nw n ne
SOUTHEAST. SOUTHWEST, and WEST example This example creates a З-х-З gridbag with limp buttons ^t*p Lioiifp 1 Xd. P'u*h w d e
V\ Jill 1111 ] v 17 Cl 11 v >1 i S . JLL 1 IL-lllL I <>t. L^clvl 1 button represents an anchor type. All but the center button have a fill con- straint of BOTH. Clicking a button mod- sw s se
ifies the center button’s anchor constraint. FIGI RE 184: import java.awt.-'; import java.awt.event; public class Main extends Frame implements ActionListener { Component centerButton; GridBagLayout gbl = new GridBagLayout('); Grid hag Anchor Tjpes.
Main О {
superC anchor Example");
GridBaqConstraints c = new Gri dBaqConst rai ntsf) ;
setLayout(gbl);
GridBagConstraints
anchor
java.awt
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty - 1;
makeButton(thi s, "nw”t c, 0, 0);
makeButton(thi s, “n”, c, 1» 0);
makeButton(thi s, ‘ne", c, 2, 0);
makeButton(thi s, "w”, c, 0, 1);
makeButton(thi s, "e”, c, 2, 1);
makeButtonfth i s, "sw", c, 0, 2);
makeButton(thi s, “s”. c, 1, 2);
makeButton(thi s, “se”, c, 2, 2);
// Make center button.
c.fi11 - GridBagConstraints.NONE;
centerButton = makeButton(thist “с”, с. 1, 1);
setSize(200, 200);
show() ;
}
Component TiakeButton(Container cont, String label,
GridBagConstraints c, int x, int y) {
GridBagLayout gbl * (GridBagLayout)cont.getLayout();
Button b new Button(label);
cont.add(b);
c.gridx = x;
c.gridy = y;
gbl.setConstraints(b, c) ;
b.addActionl. i stener(thi s) ;
return b;
}
public void actionPerformed(ActionEvent evt) {
String arg = evt .getActionCommandO ;
GridBagConstraints c = gbl.getConstraints(centerButtoi
if ("n”.equals(arg)) {
c.anchor = CridBagConstraints.NORTH;
} else if (“s”.equals(arg)) {
c.anchor = GridBagConstraints.SOUTH;
} else if (“e”.equals(arg)) {
c.anchor = GridBagConstraints.EAST;
} else if (“w”.equals(arg)) {
c.anchor r- GridBagConstraints.WEST;
} else if (“nw”.equals(arg)) {
c.anchor = GridBagConstraints.NORTHWEST;
} else if (“ne".equals(arg)) {
c,anchor = GridBagConstraints-NORTHEAST;
} else if (“sw”.equals(arg)) {
c.anchor = GridBagConstraints.SOUTHWEST;
} else if ("se”.equals(arg)) {
c.anchor = GridBagConstraints.SOUTHEAST;
} else if ("c”.equals(arg)) {
c.anchor = GridBagConstraints.CENTER;
}
gbl.setConstraints(centerButton, c);
invalidateO ;
validateO;
742
JdVd.dWt
KIl dpi J к.
translaie(
values[i] - Math.random();
}
addMousel istener(new MouseEventHandler());
}
void setOrigin(int x, int y) {
originX = x;
originY = y;
repaintO ;
}
public void paint(Graphics g) {
int w = getSizeO .width;
thick - getSizeO. height*2/values. length;
g.translate(originX, originY);
for (int i=0; i<values.length; i++) {
int c (int)(Math.floor(255 * values[i]));
if (curY >= i * thick && curY < (i+1) i thick) {
g.setColor(Color.red);
} else {
g.setColor(new Color(c, c, c));
}
g.fi1iRect(0, i * thick, (int)(w * values'ij), thick);
}
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
curX = evt.getXO - originX;
curY = evt.getYO - originY;
repaintO;
}
}
}
java.awt
GridBagConstraints
1 4.... (у.-., j
A * GridftayCo'r.strains» | • __ _________
в 4 —J
c
Syntax
public class GridBagConstraints implements Cloneable, Serializable
[•
i Description
НИ A gridbag is a collection of components laid out using the gridbag layout manager (see
e GridBagLayout). Each component in the gridbag has a set of constraints that determines its
H size and position in the gndbag. These constraints are defined with a GridBagConstraints
j instance and are associated with a component There are seven gridbag constraints.
J Fill
К The fill constraint determines whether to stretch a component to fill the component's display
! area. There are four fill types. See fill later in this section for an example that uses these till
types.
M
A tichor
If a component is not stretched to completely fill its display area, the anchor constraint sped-
0 fits the component's position in its display area. There are nine anchor types. See anchor later
P in this section for an example that uses these anchor types.
Q Size
R A component can span more than one column or row, l he size constraint specifies the number
of columns or rows that the component occupies.
T Internal Padding
Fhe internal padding constraint is used to adjust the width and height of a component after
Component, mi nimumSize() or Component, pref er redSizeO is called. Separate values con-
v trol the width and height. See i padx later in this section for an example that uses internal padding.
w
Insets
The insets constraint for a component is applied to a component's display area. An inset has
Y four values to control the inset at the four edges. A positive inset at an edge reduces the display
area at that edge. See i nsets later in this section for an example that uses insets.
738
java.awt GridBagConstn
Position
A component can be positioned at a particular cell location in the gridbag. Cells in the gridbag
are addressed by v- and y-coordi nates.
Weights
Each component in the gridbag has a non-negative gridbag weight constraint. Together, the
component weights define a weight for each column and row in the gridbag. The calculation
fordoing this is discussed later in this section.
The column and row weights determine how columns and rows stretch and shrink when
the container is made larger or smaller and how extra space is distributed among the columns
and rows. The extra space is determined by subtracting the container size from the preferred
size for the gridbag. The preferred size of the gridbag is calculated by laying out all of the
components in the gridbag using their preferred sizes. Here is how the extra space is distrib-
uted. First, no space is given to any row or column that has zero weight. The amount that a col-
umn (or row7) gets depends on its weight in relation to the total weight for all of the columns
(or rows) of the gridbag. For example, if the weight of a column c is 1 and the total weight is
10 (including c’s weight), column c gets one-tenth of the total extra space.
If the total weight for all of the columns (or rows) is 0. then the extra space is distributed
around the gridbag. For example, if the total w eight of all of the columns is 0. the gridbag will
be horizontally centered in its container.
It is important to note that if two components C and I) both have weight 1, they will not
necessarily be the same size. Only if C's and D's preferred sizes are identical will they be the
same size. This is because only the extra space (after Cs and /Ts preferred sizes are subtracted
from the total available space) is distributed to C and I). For example, if C's preferred size is
10, D's preferred size is 20, and the extra space is 40 pixels, then C will be 30 pixels wide and
D will be 40 pixels w ide.
The following steps describe how column and row weights are derived from component
weights:
I. Consider all of the components in a column whose grid widths are 1. The weight for that
column is the maximal weight for those components.
2. Now consider all of the components w hose grid widths are greater than 1. Consider them
in the order that they were inserted into the container. Suppose component C spans col-
umns ei.ej and that the combined weight of these columns is и. If C s weight is less than
w, nothing happens. If C’s weight is greater than и. the extra weight is distributed among
the columns. The distribution is based on the relative weight of the columns, so if one col-
umn has a weight of 1 while another has a weight of 5. the first column gets one-sixth of
the extra weight. After the extra weight has been distributed, any remaining weight is
given to the last column of the span. Л zero weight column never gets any extra weight
unless the column is the last column of the span and all of the columns in the span have
zero weights. These rules also apply to each row.
(i ridBagConstrai nts
java.awt
If the container’s dimensions are smaller than the gridbag s preferred size, the gridbag lay-
out manager either attempts to shrink some rows or columns smaller than their preferred sizes
or simply clips the components so that they appear off the container’s visible area. You cannot
control how the gridbag layout manager decides to fit a gridbag layout into an area smaller
than the preferred size.
MEMBER SUMMARY 1
Constructor GridBagConstrai nts() i Constructs a new GridBagConstraints instance.
Size Type Constant Fields RELATIVE 1 Specifies that subsequent cells in the row or column be occupied. । except for the last cell.
REMAINDER Specifics that subsequent cells in the row or column be occupied. |
1 Fill Type Constant Fields
I BOTH Specifies a fill in both directions.
1 NONE Specifies no fill (the default).
1 HORIZONTAL Specifies a horizontal only fill.
| VERTICAL Specifies a \ertical-only till.
1 Anchor Type Constant Fields
I CENTER Specifies center positioning.
। EAST Specifies east positioning.
| NORTH Specifies north positioning.
। NORTHEAST Specifies northcast positioning.
। NORTHWEST Specifies northwest positioning.
| SOUTH Specifies south positioning.
i SOUTHEAST Specifies southeast positioning.
1 SOUTHWEST Specifies southwest positioning.
| WEST Specifics west positioning.
| Fields
1 anchor Holds the component's anchor constraint.
। fill Holds the component’s fill constraint.
j gridheight Holds the component's height in cells.
1 gridwidth Holds the component's width in cells.
1 gridx Holds the a-coordinate cell location for the component.
1 gridy Holds the у-coordinate cell location for the component.
. insets Holds the insets constraints for the component.
1 ipadx Holds the internal padding for the component's width.
1 ipady Holds the internal padding for the component's height.
। weightx Holds the component's column weight.
1 weighty I Holds the component s row weight.
740
iinanagv onsirainis
anchoi
java.awt
MEMBER SUMMARY
Cop} Method cloneO Creates a cop\ of the gridbag constraints.
See Also
java.io.Serializable.
Example
See GridBagLayout.
anchor
pi rposi. Holds the component’s anchor constraint.
syntax public int anchor
descrihi ion There are nine anchor types, one for r^n each edge and each corner of a display area and one for the center of the dis- play area: CENTER. EAST. NORTH. NORTHEAST. NORTHWEST. SOUTH. anchor Example BRIE
nw n ne
SOUTHEAST. SOUTHWEST, and WEST example This example creates a З-х-З gridbag with ninp buttons ^t*p Eiо11гр 1 Xd. P u h w d e
V\ Illi lllllv ULlllvMiS. JLL 1 1 LI 1 v I <>t. l^clvl J button represents an anchor type. All but the center button have a fill con- straint of BOTH. Clicking a button mod- sw s se
ifies the center button’s anchor constraint. FIGI RE 184: import java.awt.''; import java. awt. event public class Main extends Frame implements ActionListener { Component centerButton; GridBagLayout gbl = new GridBagLayout('); Grid hag Anchor Tjpes.
MainQ {
superC anchor Example");
GridBaqConstraints c = new Gri dBaqConst rai ntsQ ;
setLayout(gbl);
GridBagConstraints
anchor
java.awt
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty - 1;
makeButton(thi s. “nw”t c, 0, 0);
makeButton(thi s, “n”, c, 1» 0);
makeButton(thi s, ‘'ne’’, c, 2, 0);
makeButton(thi s, “w”, c, 0, 1);
makeButton(thi s, "e”, c, 2, 1);
makeButton(th i s, “sw”, c, 0, 2);
makeButton(thi s, “s”. c, 1, 2);
makeButton(thi s, ‘'se”, c, 2, 2);
// Make center button.
c.fi11 - GridBagConstraints.NONE;
centerButton = makeButton(thist “с”, с. 1, 1);
setSize(200, 200);
show();
}
Component TiakeButton(Container cont, String label,
GridBagConstraints c, int x, int y) {
GridBagLayout gbl (GridBagLayout)cont.getLayout();
Button b new Button(label);
cont.add(b);
c.gridx = x;
c.gridy = y;
gbl.setConstraints(b, c) ;
b.addActionL i stener(thi s);
return b;
}
public void actionPerformed(ActionEvent evt) {
String arg = evt.getActionCommandO;
GridBagConstraints c = gbl.getConstraints(centerButtoi
if (“n” .equal s(arg)) {
c.anchor = CridBagConstraints.NORTH;
} else if (“s”.equals(arg)) {
c.anchor = GridBagConstraints.SOUTH;
} else if (“e”.equals(arg)) {
c.anchor = GridBagConstraints.EAST;
} else if (“w”.equals(arg)) {
c.anchor r- GridBagConstraints.WEST;
} else if (“nw,’.equals(arg)) {
c.anchor = GridBagConstraints.NORTHWEST;
} else if (“ne".equals(arg)) {
c,anchor = GridBagConstraints-NORTHEAST;
} else if (“sw”.equals(arg)) {
c.anchor = GridBagConstraints.SOUTHWEST;
} else if C‘se”.equals(arg)) {
c.anchor = GridBagConstraints.SOUTHEAST;
} else if ("c”.equals(arg)) {
c.anchor = GridBagConstraints.CENTER;
}
gbl.setConstraints(centerButton, c);
invalidateO ;
validateO;
742
java.awt
Vi гш E»ag4~ uiis i rai n is
BOTH
static public void ma i n(St ri ng;.] args) {
new Ma in();
}
}
BOTH
PURPOSE Fill type that specifies a fill in both directions.
SYNTAX public static final int BOTH
DESCRIPTION T his constant field specifies that the component is to he stretched both hori- zontally and vertically to fill its display area. This constant is used in the f i 11 field.
SEE ALSO fill.
EXAMPLE See fill.
CENTER
PURPOSE Anchor type that specifies center positioning.
SYNTAX public static final int CENTER
DESCRIPTION This constant field specifies that lhe center of the component is to he anchored to the center of its display area. This constant is used in the anchor field.
SEE ALSO anchor.
EXAMPLE See anchor.
PURPOSE Creates a copy of the gridbag constraints.
SYNTAX public Object cloneO
description This method makes a copy of the gridbag constraints. The new gridhag con- straints have a complete copy of all of the values, including a new copy of the insets object. Changing any value in the new gridbag constraints will not affect this instance.
returns Л copy of these gridbag constraints.
java.awt
GridBagConstraints
HAST
ovi•rridi s java, lang .Object. clone().
i \ \mpi I
GridBagConstraints c = new GridBagConstraints();
GridBagConstraints cCopy = (GridBagConstraints)c.clone();
EAST
c PI । RPOSE Anchor type that specifics cast positioning.
1) S'iM \\ public static final int EAST
E DESCRIPTION This constant field specifies that the east corner of the component is to be
E anchored to the east corner of the component's display area and centered \erli-
cally. This constant is used in lhe anchor field.
H SI 1 Al so anchor.
l.XAMPEI Sec anchor.
к
1. PURPOSE SYNTAX This field holds the fill constraint for a component, n 11 h "1 i r int fill
M ME» fill Example ilsJEl
N () DESCRIPTION SEE ALSO EXAMPLE I'hc fill type specifies how the component is stretched within its display area. NONE, VERTICAL, HORIZONTAL, BOTH. This example creates a 2-X-2 gridbag that has four labels. Bach label has a different fill constraint. See Figure 185. none j horizontal
P Q R S vertical both
I f i mport java.awt.-; 1 IGl RI 1X5: GridBagConstraints .fill.
V public class Main {
static void makeLabel(Container cont, String label,
W GridBagConstraints c, int fill) {
GridBagLayout gbl = (GridBagLayout)cont.getLayout();
X Label b = new Label(label, Label.CENTER);
b.setBackground(Col or.blue);
Y b.setForeground(Color.white);
cont.add(b);
Z c.fill = fill;
gbl.setConstraints(b, c);
}
744
JC1 v <LUVH
U111U3
GridBagConstraints()
static public void main(String[] args) {
GridBagLayout gbl = new GridBagLayoutO;
GridBagConstraints c - new GridBagConstraints();
Frame f - new Frame(“fi11 Example");
f.setLayout(gbl);
c.weightx - 1;
c.weighty » 1;
makeLabel(f, “none”, c, GridBagConstraints.NONE);
c.gridwidth = GridBagConstraints.REMAINDER;
makeLabel(f, “horizontal”, c, GridBagConstraints.HORIZONTAL);
c.gridwidth = 1; // Restore default value.
makeLabel(f, “vertical", c, GridBagConstraints.VERTICAL);
makeLabel(f, “both", c, GridBagConstraints,BOTH);
f.setSize(200, 200);
f.show();
}
}
GridBagConstraintsf)
purpose Constructs a new CridBagConstraints instance.
syntax public GridBagConstraints ()
description This constructor creates a new GridBagConstraints instance using the
defaults given in fable 14.
anchor CENTER
fill NONF
gridx RELATIVE
gridy RELATIVE
gridwidth 1
gridheight 1
ipadx 0
ipady 0
insets new lnsets(0, 0, 0, 0)
weightx 0
weighty 0
TABLE 14: GridBagConstraints Defaults.
example See the class example.
(GridBagConstraints
gridheight
jax a.aw l
grid height
Pl RPOSI This field holds the component's height in cells.
sx xrxx public int gridheight
A DESCRIPI l()\ 'The component's height is mcasiiicd in cells and must be non-ncgatixe. Foi
В example, a grid height of 2 means the component will be 2 cells high. II the
C grid height is REMAINDER, the component will occupx all ol the cells below n. A grid height of 0 is the same as REMAINDER. If the grid height is RELATIVE.
1) E the component will occupx all of the cells below it. except lor ihc last cell. Also, the grid height of the component that follows must be REMAINDER.
E SI 1. \l SO gridwidth, RELATIVE, REMAINDER.
1 X XX1PEE See gri dwidth.
H I gridwidth
.1 К Pl RPOSI SX X 1 \x 'This field holds the component's width in cells, public int gridwidth
L DI S( RIPI l()\ Ehe component's width is measuied in cells and must be non negalixe. For
M
example, a grid width of 2 means the component will be 2 cells wide.
N
()
P
Q
R
S
I
I'
V'
w
X
Y
Z
SEE ALSO
IX XX1PI I.
If the grid width is
REMAINDER, the compo-
nent w ill occupx all of the
cells below it. A grid w idth
of 0 is the same as
RIMAINDER.
If the grid width is RELA-
TIVE. the component will
occtipx all of the cells
below it. except for the last
cell. Also, the grid w idth of
the component that follows
must be REMAINDER.
RELATIVE. REMAINDER.
FIGI RE 186:
GridBagConstraints's Width and Height.
This example creates a b-x-3
gridbag with IS buttons. See Figure I <S6 The button at the end of each row has
the grid width constraint of REMAINDER. This means it will consume all
remaining cells in that row. Each of the non-REMAINDER buttons. when
746
java.awt
uriunagvoiiMtaiiii*
gridwidih
pushed, will increase its grid width by 1 (up to 4). Using this program, you can
experiment with the effects of nonuniform grid widths in a gridbag.
import java.awt."';
import java.awt.event.4;
public class Main extends frame implements ActionListener {
GridBagLayout gbl = new GridBagLayoutO;
Main О {
super(”gridwidth Example”);
setLayout(gbl);
for (int i=0; i<18; i++) {
if (i % 6 == 5) {
makeButton(“REMAINDER", Gri dBagConstrai nts.REMAINDER);
} else {
makeButtond”, 1);
}
}
setSize(300, 300);
show();
}
void makeButton(Strinq label, int w) {
GridBagConstraints c = new GridBagConstraintsO ;
Button b •== new Button(label) ;
c.gridwidth = w;
c.gridheight - 1;
c.fill GridBagConstraints.BOTH;
c.weightx - 1;
c.weighty - 1;
gbl.setConstraints(b, c);
add(b);
b.addActionLi stener(thi s) ;
}
public void actionPerformedfActionEvent evt) {
Button b = (Button)evt.getSourceO;
GridBagConstraints gbc - gbl.getConstraints(b);
if (gbc.gridwidth !- GridBagConstraints.REMAINDER) {
if (++gbc.gridwidth > 4) {
gbc.gridwidth - 1;
}
gbl.setConstraints(b, gbc);
b.set!abel(““ + gbc.gridwidth);
inval idateO:
validateC);
}
}
static public void main(String[J args) {
new MainO ;
1
(J ridBagConstraints
gridx
ja\ a aw 1
gridx
pi rposl This field holds lhe t-coordinate cell location for a component. s\\ia\ public int gridx TH-scRipriox The cell locations are /ero-based.This means the local ion of lhe cell at (he gridbag’s northwest corner is (0. 0). sf i. also gridy. I a am pi f- This example creates a 3-x-3 gridbag w ith eight buttons and one empls cell. See Figure 187. Pressing a button adja cent to the empix cell mutes that button into the empty cell. । < import java.awt."; import java.awt.event.'; |^ДД* cample H HI в
4 3 6
2 f 1 1 1
7 5 8
•ка KU 1X7: 'nurd mates. GridBagConstraints
public class Main extends Frame implements Actionlistener •{
GridBaglayout gbl = now Gri dBagl.ayout Q :
Point free - new Point(2, 2);
Main() {
superC’gridx Example’):
Component c null;
set 1ayout(gbl):
for (int i-0; i<J; i*+) [
For (int j -0; j<3; j1*) {
c • nakeButton(String.valueOf((char)(* 1**i♦3”;)). i):
E
remove(c); // remove the last button
setSize(20O, 200);
show О :
1
// Returns the new button.
Component rrakeBut ton(Stri ng label, int x, nnt y) {
GridBagConstraints c - now GridBagConstraints();
Button h = new Button(’abel);
c.gridx x;
c . g r i dy - у;
c.fill - GridBagConstraints.BOTH:
c.weightx 1;
c.weightу - 1:
gb1.setConstraints(b, c);
add(b);
b.addActionl istener(this);
return b;
}
748
Rl MAINDIJ
1 1G( RE 190: GridBagConstraints.REMAINDER.
import java.awt.'';
public class Main extends Frame {
GridBagLayout gbl = new GridBagLayoutO;
Main О {
super("remainder Example”);
setLayout(gbl);
for (int i=0; i<9; i+*) makeButton("1”, 1);
makeButton("REMAINDER”, Gri dBagConstrai nts.REMAINDER);
makeButton(“l”, 1);
makeButton("REMAINDER”, GridBagConstraints.REMAINDER);
makeButton("I”, 1);
makeButton("RELATIVE”, Gri dBagConstrai nts.RELATIVE);
makeButton("REMAINDER”, Gri dBagConstrai nts.REMAINDER);
setSize(300, 150);
show();
}
void makeButton(String label, int w) {
GridBagConstraints c = new GridBagConstraints();
Button b = new Button flabel);
c.gridwidth = w;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
gbl.setConstraints(b, c):
add(b);
}
static public void main(String J args; {
new MainO:
GridBagConstraints
java.awt
SOUTH
SOUTH
purpose Anchor type that specifies south positioning.
public static final int SOUTH
description This constant field specifies that the south corner of the component is to he
anchored to the south corner of the component's display area and centered hor-
izontally. This constant is used in the anchor field.
se:e: also anchor.
example- Sec anchor.
E
| SOUTHEAST
H purpose: Anchor type that specifies southeast positioning.
J syntax public static final int SOUTHEAST
f description This constant field specifies that the southeast corner of the component is to be
К anchored to the southeast corner of the component's display area. This con-
l slant is used in the anchor field.
SEE ALSO anchor.
M
e.xampi i. See anchor.
N
SOUTHWEST
Q PURPOSE /Anchor type that specifies southwest positioning.
R SYNTAX public static final int SOUTHWEST
S OE-.SCRIPI ION This constant field specifies that the southwest corner of the component is to
1' be anchored to the southwest corner of the component's display area. This con-
t; stant is used in the anchor field.
SEE ALSO anchor.
V EXAMPLE See anchor.
x
Y
Z
756
vertical
VERTICAL_________________________________________________________________________
purpose Fill 1} pe that specifics a \ ertical-only fill.
SY.\T\x public static final int VERTICAL
descripiiox This constant field specifies that lhe component is to be stretched \erticalh to
fill its display area. The component's width is not changed. This constant is
used in the fi 11 field.
see also fill.
example See fill.
weightx
purpose: This field holds the component's column weight. syntax public double weightx description Sec lhe class description for details on gridbag weights. This non-negative. Г-V/ AKltM r TIC. .. > value must be
CArtiVU U' I 111 > VAUIlipiV ULiUL'' d IUW 1 J of five buttons, each with a different weight. See Figure 191. Pressing a button in- 0 creases its weight by 1. weightx Example BWE3I
1 2 3 4
when tne weight reaches 4. it is set back to 0. ЕКЛ RE 191 Gri dBagConstrai nts’s Weights.
import java.awt.'1;
import java.awt.event О;
public class Main extends Frame implements ActionListener {
GridBagLayout gbl = new GridBagLayoutO;
Main О {
super(“weightx Example”;;
setLayout Cgbl);
for Lint i =0; i<5; 0-0 {
makeButton Ci;;
}
setSi zeO00, 150);
show/);
}
void makeButtonCi nt w) {
GridBagConstrainis с = пел GridBagConstraintзО;
Button b = new Button(““ + w);
c.weightx = w;
GridBagConstraints
weighty
jasa.awi
(..weighty - 1;
c.fill - GridBagConstraints.BOTH;
gbl.setConstraints(b, c):
b,addActi onLi stener(thi s);
add(b);
}
public void actionPerformedfActionEvent evt) {
Button b -• (But ton)evt .getSourceQ ;
GridBagConstraints gbc = gbl.getConstraints(b);
if (+-rgbc .weightx > 4) {
gbc.weightx = 0;
}
gbl.setConstraints(b, gbc);
b.setLabe1(““ ♦ gbc.weightx);
inval idateQ ;
val idateQ ;
J
static public void main(StringLJ args) {
new Mai n();
}
}
weighty
PURPOSE This field holds the component's row weight.
SYNTAX public double weighty
DESCRIPIION See the class description for details on gridbag weights. This value must be non-negative.
EXAMPLE See wei ghtx.
WEST
— . — -
Pl RPOSI Anchor type that specifies west positioning.
SYNTAX public static final int WFST
DESCRIPl |()N This constant field specifies that the west edge of the component is io be anchored to the west edge of the c omponent's display area and centered verlb cully. T his constant is used in the anchor field.
SEE ALSO anchor.
EX AM Pl J; See anchor.
758
|<3ri<WagLayout
java.awt
GridBagLayout
Syntax
public class GridBagLayout implements LayoutManager2, Serializable
Description
A gridbag is a container with a gridbag layout manager. The gridbag layout manager imple-
ments a 2D grid of cells in which all cells in a column have the same width and all cells in a
row have the same height. Multiplying the number of columns by the number of rows in the
gridbag yields the total number of cells in the gridbag. Unlike with the grid layout manager
(see GridLayout), the columns in a gridbag can have different widths; similarly for rows.
A cell in a gridbag is addressed by lhe л- and y-coordinates. The coordinates are 0-based,
so the first cell is at location (0. 0). A gridbag is initially created with no cells. Cells are auto-
matically created as components are added. For example, if the first component was added to
location (10, 10), the grid would automatically create 1 1-x-ll cells. See getLayoutDimen-
sionsO on how to obtain the gridbag's current dimensions.
A component can be located anywhere
within the grid of cells (see Figure 192). A
component can occupy one or more contig-
uous cells, which themselves must form a
smaller but rectangular grid of cells. Not
all cells must be occupied. (The gridbag
allows more than one component to overlap
a cell. However, this is considered a pro-
gramming error.) The cell or cells that a
component occupies is called the compo-
nent i display area.
A component's location in the gridbag
is specified with what are called gridbag
constraints. Every' component in the grid-
bag has associated with it gridbag con-
straints. The gridbag layout manager uses
all the component gridbag constraints to do
the layout. See lhe GridBagConstraints class for details about available gridbag constraints
and their effects on the component.
x=2 y=0
anchor^nw
h=2
inset^9
FIGURE 192: Cells in aGridbagLayout.
GridBagLayout
java.awt
MEMBER SUMMARY
Constructor GridBagLayoutO Constructs a new GridBagLayout instance.
A Constant Fields
В MAXGRIDSIZF Specifies the maximum number of cells in the gridbag.
C 4INSIZE Layout constant specifying that calculations should use a com-
ponent's minimum size.
D PRtf-tRREDSTZr Layout constant specifying that calculations should use a com-
I- ponent's preferred size.
i; Layout Fields
columnWeights Holds the overrides to the column weights.
columnWi dths Holds the overrides to the column minimum widths.
IJ comptable This hash table maintains the association between a compo
I layoutTnfo nent and its gridbag constraints. Holds the gridbag’s layout information. ’
1 rowHeights Holds the overrides to the row minimum heights.
J rowWeights Holds the overrides to the row weights.
к 1. Constraints Methods and Field defaultConstrai nts This field holds a gridbag constraints instance containing the ►
M default values.
getConstrai ntsQ Retrieves the grid bag constraints for a component.
N 1ookupConstrai nts() Retrieves the constraints for a component.
() setConstraintsO Sets the gridbag constraints for a component.
P , Grid Bag Layout Methods
AdjustForGravi tyO Adjusts the position of a component within its display area.
Q ArrangeGridO Lays out the container's components using the components'
R constraints.
getLayoutDimensionsO Retrieves the dimensions of each row and column in the grid
s bag.
1 GetLayoutTnfoO Calculates the layout for a gridbag container.
L getLayoutOri gi n() Retrieves the gridbag's location within its container.
getLayoutweights О Retrieves the gridbag's row and column weights.
V GetMinSizeO Retrieves the minimum dimension of the gridbag.
W location О Retrieves the cell location using a pixel location.
X Layout Manager Methods
Y addl ayoutComponentO Adds a component to this layout.
getLayoutAlignmentXO Retrieves the gridbag's д-alignment.
Z getLayoutAl ighmentYO Retrieves the gridbag's y-alignment.
inval idateLayoutO Invalidates the gridbag's slate.
760
|u\ a.aw t
Grid Bag Lay
MEMBER SUMMARY
1ayoutContainer() maximumLayoutSi ze() mi nimumLayoutSi ze() preferredLayoutSi ze() removeLayoutcomponent 0 Lays out the container's components using the components' constraints. Calculates the maximum dimensions for laying out the com- ponents. Calculates the minimum dimensions needed to lay out the components. Calculates the preferred dimensions needed to lay out the components. A no-op.
Debugging Method toStringO Generates a string representation of the gridbag's state.
See Also
GridBagConstraints, java.io.Serializable, LayoutManager2.
1 Bl GridBagLayout Ex... HEIDI
North
West Center East
South
HGURE 193: GridBagLayout
Simulating BorderLayout.
^GridBagLayout Ex... HWE
Name:
Address: 0
Phone: 0
UGl RE 194: GridBagLayout
Implementing a Form.
Example
This example creates three sample layouts. The
first is a simulation of the BorderLayout layout
manager (Figure 193). The second is a popular use
of the gridbag layout: implementing a form-like
layout (Figure 194). The third simply demonstrates
the kinds ot layouts that are possible (Figure 195).
import java.awt.
public class ^ai n (
static void makeCrazyLayout() {
Г ramp f = new
GridBagLayout Ex... BSD
I 1GI RE 195: GridBagLayout.
GridBagLayout
jaxa.au l
Fraine(“GridBaglayout Example Iм);
f.setLayout(new GridBagLayout());
irakeButton(f, 0.0); makeButton(f, “A”, “B”, 0. 1, 0, 0. 1, 4, 2, 1, 0.0, 2.0,
Л 0.0);
makeBut ton(f, “C”, 1, 1, 2, 1. 0.0,
в 0.0);
makeBut ton(f, “D”, 3, 1, 2, 2, 0.0,
c 2.0);
makeButton(f, “L’ , 0, 2, 2. 2, 0.0, 0.0);
0 makeButton(f, *T“, 1, 4, 1, 1 , 0.5, 0.0);
makeButton(f, “G”, 2. 2, 1. 3, 0.0, 0.0);
E makeButton(f, “H”, 3, 4, 1, 1, 0.0, 0.0);
makeButtonff, “I”, 4, 3, 1, 1, 1.0, 0.5);
Г f.packO;
f. showQ ;
H static void makeBorderLayout() {
Frame f = new Frarre(“GridBagLayout Example 2”);
1
f.set Layout(new Gri dBagLayout());
J makeButtontf, “North”, 0, 0, 3, 1, 0.0, 0.0); makeButton(f, “South”, 0, 2, 3, 1, 0.0, 0.0);
К I, makeButton(f, “West”, 0, 1, 1, 1» 0.0. 1.0); makeButton(f, “East”, 2, 1. 1, 1, 0.0, 1.0); makeButton(f, “Center”, 1, 1, 1, 1, 1.0, 1.0);
f.packO;
M f.showO;
1
N
static void makefabl eLayoutO {
О Frame f new Frame(“GridBaglayout Example 3”);
P f.setLayout(new GridBagLayoutO );
makeButton(f, new Label("Name:"), 0, 0, 1, 1, 0.0, 0.0);
Q makeButton(f, new Label(“Address:”), 0. 1, 1, 1, 0.0, 0.0);
makeButton(ft new Label(“Phone;”), 0, 2, 1, 1, 0.0, 0.0);
R makeButton(f, new TextField(“0”, 5), 1, 0, 1, 1, 1-0, 0.0);
makeButton(f, new TextField(“0”, 5), 1, 1, 1, 1, 1.0. 0.0);
S makeButton(f, new Text Field(“0'', 5). 1, 2, 1, 1, 1-0, 0.0);
f.packO;
T f.showO;
}
i:
static void makeButton(Container cont, Object arg,
V int x, int y, int w, int h, double weightx, double weigh
GridBagLayout gbl = (GridBagLayout)cont.getl ayout();
W GridBagConstraints c - new GridBagConstraintsO ;
Component comp;
X
c.fill = GridBagConstraints.BOTH;
Y c.gridx - x;
c.gridy = y;
7. c.gridwidth - w;
c.gridheight = h;
c.weightx weightx;
c.weighty = weighty;
762
java.awt
t т na nagbay о i
addLayoutComponent
if (arg instanceof String) {
comp - new Button((String)arg);
} else {
comp - (Component)arg;
}
cont.add(comp);
gbl.setConstraints(comp, c):
}
static public void "iai n(St ri ng[] args) {
makeCrazyLayoutO;
makeBorderl ayoutO:
makeTableLayout();
}
}
addLayoutComponent)
purpose: Adds a component to this layout.
syntax public void addLayoutComponent(String name, Component comp)
public void addLayoutComponent(Component comp, Object constraints)
description This method is called by a container when the component comp is added to it.
The first form of this method accepts a string name to be associated with comp.
However, component names are ignored by lhe gridbag layout manager so this
method does nothing. Il needs to be defined in order to satisfy the LayoutMan-
ager interface.
This second form of this method accepts a constraints argument that specifies
how the component is to be laid out.
PARAMETERS
comp The non-null named component that has just been added to the container.
constraints The constraint to use for this component. Must be an instance of Gri dBagCon-
strai nts.
name The name of the component. Ignored.
EXCEPTIONS
IllegalArgumentException
If constraints is not an instance of GridBagConstraints.
SEE also LayoutManager?, setConstraints().
example See LayoutManager.
java.awt
GridBagLayout
AdjustI;orGravity(}
Adjust For (i ravityQ
Pl R POSF Adjusts the position of a component within its display area.
SYNTAX protected void AdjustForCravity(CridBagConstraints constraints,
A Rectangle displayArea)
В DLSCR1PI ION The gridbag constraints constraints are used to adjust the component’s
c bounds within its display area, which is represented by displayArea. In par- ticular. the insets, fill, size, and anchor gridbag constraints are used to deter-
D mine the component’s bounds. After this method call, displayArea will
I: contain the component's new bounds.
f- PAR AM LI I.RS
constraints The non-null component gridbag constraints.
H di splayArea Л non-null rectangle representing a component's display area.
I J К ArrangeGridf)
PURPOSE: Lays out the container's components using the components' constraints.
L SYNTAX protected void ArrangeGrid(Container container)
M DLSCR1FIION This method is equivalent to 1 ayoutContai ner 0
N PARAMETLRS
o contai ner The non-null container using this layout instance.
P LXAMPLL See 1ayoutContainer().
У
R columnWeights
S PCRPOSL This field holds the overrides to the column weights.
T SYNTAX public doublet] columnweights
и DESCRIP 1 ION If this field is non-null. the values in the field are applied to the gridbag after
V w all of the column weights have been calculated. If columnWeights[i] is greater than the weight for column i. then column i is assigned the weight in columnWeights[п]. If columnWeights has more elements than the num-
X ber of columns, the excess elements in col umnWeights are ignored. In partic-
Y ular. they do not cause more columns to be created.
764
java.awl
ипсшацьауош
eolumnWeighr
ample This example creates а З-х-З
gridbag with nine buttons. The
gridbag is set with some row /col-
umn weight and si/e oxerrides.
See Figure 196.
import java.awt.-';
public class Main extends Frame {
GridBagLayout gbl =
new GridBagLayoutO;
FIGURE 196: GridBagLayout Weights/Sizes.
Main() {
super(
“Weight/Size Override Example”);
GridBagConstraints c =
new GridBagConstraints() ;
double rowWeights□ = {0, 0, 1.0};
double colweights[j = {0, 0, 1.0};
int rowHeights[] = {20, 50};
int colWidthsf] = {20, 50};
gbl.rowWeights = rowWeights;
gbl.columnWeights = colWeights;
gbl.rowHeights = rowHeights;
gbl.columnWidths = colWidths;
setLayout(gbl);
c.fill = GridBagConstraints.BOTH;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
Button b = new Button(““+i+”,”+j);
c.gridx = i ;
c . gri dy = j;
add(b);
gbl.setConstraints(b, c);
}
}
setSize(250, 150);
show();
static public void main(String[] argsj {
new Main();
1
GndBagLayout
columnWidths
java.aw 1
A
В
C
D
E
columnWidths
purpose This field holds the overrides to the column minimum widths.
syntax public int[] columnwidths
description If this field is non-null, the values in the field are applied to the gridbag after
all of lhe minimum column widths have been calculated. If col umnWidths has
more elements than the number of columns, columns are added to the gridbag
to match the number of elements in columnwidths.
example See columnweights.
comptable
purpose This hash table maintains the association between a component and its gridbag
constraints.
syntax protected Hashtable comptable
dlscripi ion l he keys in comptabl e are the components, and the values are the instances of
GridBagConstrai nts.
О
P
Q
R
S
T
U
V
w
X
Y
z
defaultconstraints
purpose This field holds a gridbag constraints instance containing the default values.
symax protected GridBagConstraints defaultconstraints
description If a component is found not to have a gridbag constraints instance associated
with it, the component is assigned a copy of defaultconstraints.
getConstraints()
purpose Retrieves the gridbag constraints for a component.
syntax public GridBagConstraints getConstraints(Component comp)
description This method retrieves a clone of gridbag constraints for the component comp.
PAR/\ METERS
comp The non-nul 1 component to be queried.
Ri n rns Л non-nul 1 copy of the component's gridbag constraints.
EXAMPiF. See getLayoutWeightsf).
766
javu.ciwi ул luwa^uaj vu
geiLayoutAlignmentXt
getLayoutAlignmentX()
PURPOSE Retrieves the gridbag's v-alignment.
SYNTAX public float getLayoutA11gnmentX(Container cont)
description This method returns Component.CENTER ALIGNMENT. See 1ayoutManager2 for more information about alignments.
parameters cont The non null container using this gridbag.
RETURNS This gridbag's л-alignment, which must be in the range 0.0f to 1.0f.
SEE ALSO Component.getAl ignmentXO, Container.getAl ignmentXQ , getLayoutAlignmentYQ , 1 ayoutManager?.
EXAMPLE See the LayoutManager2 class example.
getLayoutAlignmentY()
PURPOSE Retrieves the gridbag's v alignment.
SYNTAX public float getLayoutAlignmentY(Container cont)
DESCRIPTION This method returns Component.CENTER .AlIGNMENT. See LayoutManager? for more information about alignments.
PARAMETERS cont The non-null container using this gridbag.
RETURNS This gridbag's y alignment, which must be in the range 0.0f to 1.0f.
SEE ALSO Component.getAlignmentYO, Container.getAl1gnmentY(), getLayoutAlignmentXO , LayoutManager?.
. EXAMPLE See the LayoutManager2 class example.
getLayoutDimensionsf)
PURPOSE Retrieves the dimensions of each row and column in the gridbag.
SYNTAX public int[] [J getLayoutDimensions ()
description If w = getLayoutDimensionsO, then w[0] .length contains the number of columns and w[0] [0] .. .w[0] [w[0]. length-1] are lhe column widths. w[l].length contains the number of rows and w[l] [0] - -w[l] [w[l] .length-1] are the row heights. The resulting infer mation is based on the most recent validation. So if the container is invalid or a
GridBagLayout
jas a.awl
Get Layout I nfo( )
constraint has been modified, the gridbag should be salidated he foie this
method is called.
ri.ii r\s A non-null 2D arras containing the row and column weights.
i \ \\ipi i. See getLayoutWeights().
В
( GetLayoutInfo()
I) Pl RPOSI Calculates the layout for a gridbag container.
E SS M AX protected GridBagLayoutlnfo Get Iayoutlnfo(Container container.
E int sizeflag)
DESCRIP 11ОХ If sizeflag is MINSIZE, then the las out is based on the component's mini-
H mum size. If sizeflag is PREFERREDSIZE, then the las out is based, on the
component's preferred si/c.
i PARAMETERS
.1 contai ner The non-null container to query.
К si zeflag Can be cither MINSIZE or PREFERREDSIZE.
retirxs /\ non-null GridBagLayoutlnfo instance containing the lasout informal ion.
M
N
()
P
Q
R
S
T
и
V
sv
X
Y
z
getLayoutOrigin()
pi Rposi- Retrieses the gridbag's location w ithin its container.
public Point getLayoutOriginQ
di s< Riprios The gridbag's origin is the position of the gridbag's northwest cornet in rela-
tion to its container. The resulting information is based on the most recent sal-
idation. So if Ihc container is insalid or a constraint has been modified, the
gridbag should be salidated before this method is called.
RI it R\S
I X AMPLE
A new non-null Point
instance containing the
gridbag's origin.
This example creates a
gridbag svilh tsvo check-
boxes svhose default
weights arc 0. This means
that the extra space is dis-
tributed around the grid-
bag rather than to some
FUJI RE P>7: GridBagLayout. getLayoutOriginQ •
768
getLayoutOrigini)
gridbag column or row. See Figure 197. A red dot is painted centered at the
gridbag's origin witbin the container. Clicking a checkbox, and thereby chang-
ing its weight, changes the gridbag size as well as its origin.
import java.awt.*;
import java.awt.event;
public class Main extends Frame implements ItemListener {
GridBagLayout gbl - new GridBagLayout():
MainO {
super(“getlayoutOrigin Example’'):
GridBagConstraints c =• new GridBagConstraintsQ;
Checkbox cb;
c.fill - GridBagConstraints.BOTH;
setLayout(gbl);
add(cb = new Checkbox(”weightx = 0.0”));
gbl.setConstraints(cb, c) ;
cb.addltemListenerCthi s);
add(cb - new CheckboxC'weighty - 0.0”));
gbl.setConstraints(cb, c);
cb.addltemLi stener(th i s);
setSize(300, 100);
show();
}
public void paint(Graphics g) {
Insets insets = this.getlnsetsO;
int x = insets.left, у - insets.top;
int dotSize = 20;
Point p = gbl.getLayoutOrigin();
g.setColor(Color.black);
g.fi1lRect(x, y, getSize().width x-insets.right,
getSize().hei ght-y-i nsets.bottom);
g.setColor(Col or.red);
g.fi1lOval(p.x-dotSize/2, p.у-dotSize/2, dotSize, dotSize);
}
public void itemStateChanged(ItemEvent evt) {
Checkbox cb - (Checkbox)evt .getSourceO ;
GridBagConstraints c = gbl.getConstraints(cb);
String label = cb.getLabel().substring(0, 7);
int val = cb.getStateO ? 1 : 0;
if (labe 1 .equalsC'weightx”)) {
c.wei ghtx = val;
} else {
c.weighty = val;
}
cb.setLabel(1abe1 + “ - “ + val * u.0”);
gbl.setConstraints(cb, c);
inval idateO ;
vali dateO ;
repaintO ;
}
static public void mai n(St ri ng[] args) {
GridBagLayout
java.aw l
get Layout Wei ght st )
new Mai n();
}
}
A
getLayoutWeightsf)
c PI RPOSt. Retrieves the gridbag's row and column weights.
1) X 1 w public doubleOH getLayoutWeights()
i: IMSCRIPHOX If w = getLayoutWeights(). then w[0].length contains the numbei ot
columns and w[0] [0J . . .w[0] [w[0] . length-1] are lhe column weights.
i • w[l] . length contains the number of rows and
w[l] [0] . . .w[l] [w[l] . 1 ength-1] are the row weights. The resulting in lor-
H mation is based on the most recent validation. So if the container is in\alid or a
constraint has been modified, the gridbag should be validated before this
i method is called.
j Rl. 1 I R\S A non-null 2D arrav containing the row and column weights.
к 1. l\ \MPLL This example creates a gridbag that —ГгТ1—1 has four buttons. See figure 198.
Pressing a button changes either its 1 ........ ...... j
M weightx or weighty gridbag con-
N straints. I'he gridbag is then laid
() out again. After the constraints are (W) (0Д)
changed, all the new row and col-
P umn weights and dimensions are - --- 1 J
Q printed to Sy stem. out. i'Igtri-: IQS:
R GridBagLayout.getLayoutWeightsO •
c i mport java, awt. •• ;
. > i mport java. awt. event. ••;
T publi c class Main extends Frame implements ActionListener {
u GridBagLayout gbl = new GridBagLayoutO;
MainQ i
super(“getLayoutWeights Fxample”);
setLayout(gbl);
pri ntLayoutData(gbl);
makeButton(0, 0);
makeButton(0, 1) ;
makeButton(1, 0);
makeButton(l, 1);
setSize(200, 200);
show();
}
770
gelLayoutWcighls()
void printLayoutData(GridBagl ayout gbl) {
System.out . printl n(‘' =-—=—----=t^=-^-^-=^-=s=======~-'') ;
// print layout weights
System,out.print 1n(“layout Weights”);
System.out.print 1n(“--------- ----”);
doublet][jweights = gbl.getLayoutWeights();
System.out.print(“ “^weights[01.length*” columns: “);
for (int i-0; i<weights[_0] .length; i* + ) {
System.out.print(weights[0][iJ+M “);
}
Systern.out.pri ntln();
System.out.print(“ “^weights[1].length*” rows: “);
for (int i=0; i<weights[1].1ength; i*+) {
System.out.print(weights[l][iJ +” “);
}
// print layout dimensions
Systern.out.pr i ntln();
System.out.printIn(“Layout Dimensions”);
System.out.println(“---------------- ”);
int[][ldims = gbl .getl ayoutDimensionsQ ;
System,out.print(“ ”^dims[0].1ength+" columns: “);
for (int i=0; i<dims[0].1ength; i++) {
System.out.print(dims[0][i]+ ” “);
}
System.out.println();
System.out.print(“ “*dims[1].length*” rows:
for (int i-0; i<dims[1].length; i*+) {
System.out.print(dims[11[i]+” “);
}
System.out.println();
}
void makeButton(int x, int y) {
GridBagConstraints c - new GridBagConstraints();
Button b - new Button(“(0,0)”);
add(b);
c.fill = GridBagConstraints.BOTH;
c.gridx - x;
c.gridy = y;
gbl.setConstraints(b, c);
b.addActionli stener(this);
}
public void actionPerformed(ActionEvent evt) {
Button b - (Button)evt.getSourceO:
GridBagConstraints c - gbl.getConstraints(b);
if (c.weightx 0 && c.weighty 0) {
c .weighty - 1;
} else if (c.weightx -= 0 && c.weighty == 1) {
c.weiqhtx - 1;
} else if (c.weightx — 1 && c.weighty 1) {
c.weighty - 0;
} else {
c.weightx = 0;
}
b.setLabel(“(”+c.weightxt”,”+c.weighty+")”);
GridBagLayout
GelMinSizet)
java.awt
gbl.setConstraints(b, c);
irivalidateQ ;
vali dateO ;
printlayoutData(gbl):
A static public void mai n(St ri ng[l args) {
new *4ai n();
В J
}
c
D
E
F
H
1
J
К
L
M
N
О
GetMinSize()
perpose Retrieves the minimum dimension of the gridbag.
syntax protected Dimension GetMinSizeCContainer container,
CridBagLayoutlnfo info)
desc ription Fhe minimum dimension of the gridbag is based on the layout information in
info. Also, the insets of the container container are included in the result.
PARAMETERS
contai ner The non-nul 1 gridbag's container.
info The non-nul 1 layout information.
returns A new non-null Dimension instance containing the minimum dimensions of
the gridbag.
P
Q G ridBagLay out()
R Pl RPOSE Constructs a new GridBagLayout instance.
S SYNTAX public GridBaglayoutO
T DESCRIPTION By default, the gridbag has no cells.
U EXAMPLE See the class example.
invalidateLayout()
x ” “
purpose Invalidates the gridbag's state.
syntax public void invalidatelayout(Container cont)
772
layoutContainerf
DESCRIPTION This method is called by the layout manager's container to discard any cached information associated with this gridbag for the container cont. for GridBag- Layout, this method, by default, does nothing.
parameters cont The non-null container using this gridbag.
SEE Al-SO LayoutManager2.
example See the LayoutManager^ class example.
layoutContainer()
PURPOSE Lays out the container's components using the components' constraints.
SYNTAX public void 1ayoutContainer(Container container)
DESCRIPTION This method is called by container when the layout is invalidated and needs to be redone. The gridbag layout manager uses the component's preferred size when calculating the layout.
PARAMETE-RS container The non-null container using this layout instance.
EXAMPLE See LayoutManager.
layoutinfo
PURPOSE This field holds the gridbag's layout information.
SYNTAX protected GridBagl ayoutlnfo layoutinfo
DESCRIPTION The data in this field is based on the most recent validation of the gridbag. A value of null means either there are no components in the gridbag or the grid- bag has not yet been validated.
EXAMPLE See GetLayoutlnfoQ.
location()
PURPOSE Retrieves the cell location using a pixel location.
syntax public Point location(int x, int y)
DESCRIPTION This method retrieves the cell location at pixel location (x, y). The cell loca- tions are 0-based, so the top-left cell is at (0, 0). The cell at the bottom-right
GridBagLayout
locations )
ja\ a.aw t
corner is at (number of column-1, number of rows-1). If x is to (lie left of the
gridbag. it is set to 0; similarly for y. If x is to the right of the gridbag. it is set
to the number of columns; similar ly for y.
'This calculation uses the data from the gridbag's most recent уalidation.
Therefore, if the container is incalid or a constraint has been modified, the
gridbag should be у alidated before calling this method.
C
I)
i:
f
P \R УУ11- I I RS
x l he л-coordinate rclatiyc to the gridbag container's inset area,
у l he v-coordinate rclatiyc to the gridbag container's inset area.
Ri 11 r\s A new non-nul 1 Poi nt instance containing the coordinates of lhe cell.
i \ WIPI I
II
1
.1
К
I.
M
N
This example creates a frame
that has four custom canvases.
Sec Figure 199. The canvas dis-
plays its cell position and for-
wards mouse motion events to its
parent, which is the panel con-
taining the canyascs. The panel
receives those eyents and uses
them to locate a cell in the grid-
bag. The cell location is dis-
played at the bottom of the frame.
location Example ВВП
ko)p.o)
(0,
(1,1)
HGl R!< 199: GridBagLayout. locationO •
G
import java.awt.';
import java. awt. event.;
public class Main extends Frame {
GridBagLayout gbl = new GridBagl ayout ();
l.abel 1 = new Label(““);
Main О {
super(‘‘locati on Example”);
Panel p - new Panel(gbl);
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
makeCanvas(p. “(“ + i+”,”+j+”)". i, j);
}
setBackground(Col or.1i ghtGray);
add(p, BorderLayout.CENTER);
add(l , BorderLayout.SOUTH);
p.addMouseMot!onListener(new MouseMot ionEventHandler О 1;
pack();
show();
774
Irl iUDtt^LdVUUl
location!
java.awt
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
int x - evt.getXO, у evt.getYO;
Point p = gbl.locationfx, y);
1.setText(“(“+P-x+”, “+p.y+”)”);
}
}
void makeCanvas(Container cont, String label, int xT int y) {
GridBagConstraints c = new GridBagConstraints():
MainCanvas cv -= new MainCanvas(label);
cont.add(cv);
cv.setSize(30, 30);
c.gridx -= x;
c.gridy = y;
gbl.setConstraints(cv, c) ;
}
static public void main(StringL args) {
new MainО;
}
class MainCanvas extends Canvas {
String label;
MainCanvas(String label) {
thi s.1abel = label;
addMouseMotionl istener(new MouseMotionEventHandler());
}
public void paint(Graphics g) {
int w - getSize().width;
int h = getSizeO .height;
FontMetrics fm - g.getFontvetricsO ;
g.drawString(label, (w-fm.stringWidth(label))/2,
(h-fm.getHeight())/2+fm.getAscentO) ;
g.setColor(getBackgroundO);
g.draw3DRect(0, 0, w-1, h-1, false);
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
evt. transl atePoi nt (getLocationO _x, getLocationO • y);
getParent().di spatchEvent(evt);
}
}
GridBagLayout jaxa.awt
lookupConstraintsf)
lookupConst raints()
Pl RPOSI Retrieves rhe constraints for a component.
SYNTAX protected GridBagConstraints lookupConstraints(Component comp)
Л DESCRIPTION This method retrieves the constraints for the component comp. The return
в value is not a copy: it is the actual constraints instance used bv the layout
С' mechanism.
D К F PARAMETERS comp RETURNS SEE ALSO The non-null component to he queried. The non-null constraints for the component. getConstrai nts().
1
н
1 MAXGRIDSIZE _
J Pl RPOSE This constant specifies the maximum number of cells in the gridbag.
к SYNTAX protected static final int MAXGRTDSIZF
L DLSCRIPI ION Its value is 512.
м
N maximumL ayoutSize()
О
р PURPOSE Calculates the maximum dimensions for laying out the components.
j / SYNTAX public Dimension maximumLayoutSize(Container c.ont)
V DESCRIPTION For gridbag layout* the maximum layout is* by default, the largest dimension
R available (Integer .MAX„VALUE by Integer,MAX_VALUF).
S PARAMETERS
Г cont The non-null container using this layout instance.
и RETURNS A new non-null Dimension instance containing the maximum size of the
V gridbag layout.
W SEP ALSO Component.getMaximumSizeO, Container, minimumLayoutSize(), LayoutManager2, preferredLayoutSizeO.
X EXAMPLE See the LayoutManager2 class example.
776
minimumLayoutSizef)
minimum Lay outSizef) ____________________________
PURPOSE Calculates the minimum dimensions needed to lay out the components.
SYNTAX public Dimension minimum!ayoutSize(Container container)
DESCRIPTION This method lays out the gridbag using the components' minimum sizes and returns the dimensions of the resulting gridbag.
parameters container The non-null container using this layout instance.
RETURNS A new non-null Dimension instance containing the minimum size of the gridbag.
SEE ALSO Component.mini mumSi ze().
example: See LayoutManager.
MINSIZE
PURPOSE Layout constant specifying that calculations should use a component's mini- mum size.
SYNTAX protected static final int MINSIZL
DESCRIPTION This constant is used in various layout methods. When a component's dimen- sions are needed, this constant specifies that the dimensions should be retrieved using Component .getMinimumSizeO rather than Compo- nent .getPreferredSi ze().
SEE ALSO PREFERREDSIZE.
EXAMPLE: See GetLayoutlnfoO.
preferredLayoutSize()
purpose Calculates the preferred dimensions needed to lay out the components.
SYNTAX public Dimension preferredLayoutSize(Container container)
DESCRIPTION This method lays out the gridbag using the components' preferred sizes and returns the dimensions of the resulting gridbag.
PARAMETERS container The non-null container using this layout instance.
Returns A new non-null Dimension instance containing the preferred size of the grid- bag.
Grid Bag La у out PREFERREDSIZE java.awt
SHE ALSO Component.preferredSize().
E X AMPLE. Sec LayoutManager.
PREFERREDSIZE
PERPC ISE Layout constant specifying that calculations should use a component^ pre- ferred si/e.
SV XI \x protected static final int PRFFERRFDSIZL
DESCRIPTION This constant is used in various layout methods. When a component’s dimen- sions are needed, this constant specifies that the dimensions should he retrieved using Component.preferredSize() rather than Component.min- imums ize().
SLL Al,SO MINSTZE.
1 ХАМИ E See GetLayoutlnfoC).
removeLayoutComponentt)
Pl R EXISE. This method is a no-op.
SYNTAX public void removeLayoutComponent(Component comp)
DLSCRIPHON This method is called by lhe layout manager's container whenever a compo- nent is removed from the container. This method does nothing. It needs to be defined in order to satisfy the Lay- outManager interface.
PAR AML 11 RS
comp The non-null component about to be removed from the container. Ignored.
EX АМН 1: See LayoutManager.
rowHeights — —
Pt RPOSL This field holds the overrides to the row minimum heights.
SYNIAX public int rowHeights[]
DESCRIPTION If this field is non-null. the values in the field are applied to the gridbag after all the minimum row heights have been calculated. If rowHeights has more
778
java.awt GridBagLayout
rowWeight?
elements than the number of rows, rows are added to the gridbag to match the number of elements in rowHeights.
example See rowWeights.
rowWeights
PURPOSE This field holds the overrides to the row weights.
SYNTAX public doublet] rowWeights
DESCRIPTION If this field is non-null, the values in the field are applied to (he gridbag after al) of the row weights have been calculated. If rowWeights[i] is greater (han the weight for row i, then row i is assigned the weight in rowWeights [i ]. If rowWeights has more elements than the number of rows, the excess elements in rowWeights are ignored: they do not cause more rows to be created.
ЕХАМР1.Е See columnWeights.
setConstraints()
PURPOSE Sets the gridbag constraints for a component.
SYNTAX public void setConstraints(Component comp, GridBagConstraints constraints)
DESCRIPTION This method associates the gridbag constraints constraints to the compo nent comp, lhe caller is free to modify constraints, since this method cre- ates and uses a clone of constraints.
PARAMETERS comp The non-null component to associate with constraints.
constraints The non-null gridbag constraints to associate with comp. The values in
constrai nts are copied.
SEE ALSO GridBagConstraints.clone О
EX AMP! I. See the class example.
java.awt
GridBagLayout
toStri ng()
toString()
PURPOSE Generates the string representation of the gridbag's state.
SYNTAX public String toStringO
A DESCRIPTION This method generates the string representation of this gridbag. The result
В string contains the gridbag's class name.
C D RETURN’S This method is typically used for debugging. A non-null string containing the gridbag's class name.
К OVERRIDES Object.toStri ng().
h EXAMPLE See Obj ect. toSt ri ng О.
H
I
J
К
I.
M
N
()
P
Q
R
S
T
t:
v
x
Y
z
780
java.awt
GridLayout
Syntax
public class GridLayout implements LayoutManager, Serializable
Description
The grid layout manager places components in a grid
of rows and columns. The components arc laid out in
left-to-right. top-lo-bottom order. F igure 200 shows a
container with a grid layout manager set to display a
grid of three rows and three columns. The cells in the
grid are exactly the same size and are as large as possi-
ble such that all ceils are completely visible. Any
remaining space is distributed to the right and bottom
of the container. Every component is allocated a cell,
regardless of whether the component is visible. An
invisible component simply shows as an empty cell.
GridLayout Example BOB
FIGI'RE 200: GridLayout.
The grid layout manager does not use the names of the components, so any name that is
supplied with the addLayoutComponent() method call is ignored.
Rows and Columns
When creating a grid layout manager, you specify the number of row s and columns of the grid.
The number of rows and columns can be changed at any time. Either of the dimensions can be
set to “any" (value 0). meaning the number of rows юг columns) in that dimension depends on
the other dimension. Eor example, if the number of rows is “any" and the number of columns
is 2. then the number of rows will be (number-of-components+l)/2. An exception is thiown
if both dimensions are set to “any." If both the rows and column is not “any." then the number
of specified columns is treated as if it were “any."
Gaps
The grid layout manager allows you to separate the cells by gaps, lhe vertical gap specifies
the space between rows, while the horizontal gap specifies the space between columns. The
gaps can be changed at any time.
See Also
java.iо.Seri al izable.
Grid Layout
java.awt
MEMBER SUMMARY
Constructor CridLayout0 Constructs a grid layout with the specified rows and columns.
A Layout Manager Methods
R addLayoutComponent() Adds a component to this layout. ।
layoutContai ner() Lays out the container's components according to the settings
C of the layout manager.
D minimuml ayoutSizeO Calculates the minimum dimensions needed to layout the
components.
li preferredLayoutSizeO Calculates the preferred dimensions needed to layout the
F components.
removeLayoutComponent() Removes a component from the layout.
LI Gap Methods
ri getHgapQ Retrieves the horizontal gap between components.
1 getVgapQ Retrieves the vertical gap between components.
1 setHgapO Sets the horizontal gap between components.
J setVgapO Sets the vertical gap between components.
к Grid Methods
L getColumnsQ Retrieves the number of columns in this grid layout.
M getRowsQ Retrieves the number of rows in this grid layout.
setCol umnsQ Sets the number of columns in this grid layout.
N 1 setRowsO Sets the number of rows in this grid layout.
О Debugging Method
P toStringO Generates a string representation of the grid layout's values.
Q
R
S
Г
L
V
W
X
Y
Z
Example
This example creates а З-х-З grid layout with 5 pixels between columns and 10 pixels between
rows (see Figure 200). Notice that button “5" is not visible, but it still occupies a cell.
import java.awt,*;
class Main {
static public void main(String[] args) {
Frame f - new FrameC’GridLayout Example”);
Button b;
f.setLayout(new GridLayoutC3, 4, 5, 10));
f.add(new Button(“l”));
f.add(new Li st());
f-addfnew Button(“3”));
f,add(new Button(“4”));
f-add(b = new Button(“5’'));
f.add(new Button(“6”));
782
Jil V d.it W I
f.add(new ButtonC'7”)) ; f.раскQ: f. showQ ;
} } b.setVisible(false);
addLayoutComponent()
PURPOSE Adds a component to (he layout.
SYNTAX public void addlayoutComponentfString name. Component comp)
DESCRIPTION This method is called by (he container when a component is added with a name. However, component names are ignored by the grid layout manager, so (his method does nothing. This method needs to be defined in order to satisfy the LayoutManager interface.
parameters comp name The named component that has just been added to the container. Ignored. The name of the component. Ignored.
EXAMPIE See LayoutManager.
getColumnsf)
PURPOSE Retrieves the number of columns in this grid layout.
SYNTAX public int getColumnsO
description The number of columns in this layout is initialized by the GridLayout con- structor and changed using setColumnsO- See the class description for details on rows and columns.
Returns A non-negative integer specifying the number of columns. 0 means any num- ber of columns.
SEEALSO getRowsQ, setColumns().
exampi e See setColumnsO.
GridLayout
getHgapf)
java.awt
getHgapO
purpose Retrieves the horizontal gap between components.
A
В
C
D
E
I
SYNTAX
DLSURIPl ION
RETURNS
SEE Al,SO
EXAMPLE
public int getHgapO
The horizontal gap is initialized by the GridLayout constructor and changed
using setHgapO. See the class description for details on horizontal gaps.
A non-negative integer specifying the horizontal gap in pixels.
getVgapO, setHgapO.
H
I
J
К
I.
M
N
()
P
Q
R
S
1
u
V
This example ere- । ates a frame that । has а З-х-З grid layout manager with vertical and horizontal gups initialized to 0. Four buttons labeled V+, V . - GridLayout Gaps Example
V*
H+ vpp=W, Hgap=q I I
V-
H+, and И- con- trol the vertical FIGURE 201: Horizontal and Vertical Gaps in a GridLayout.
and horizontal
gaps of the grid layout. Л status button in the center is used to display the cur-
rent vertical and horizontal gaps in effect. See Figure 201.
X
Y
Z
import java.awt .»’ ;
import java. awt. event .;
class Main extends Frame implements ActionListener {
GridLayout layout - new GridLayout(3. 3);
Button status;
Main О {
superC'GridLayout Gaps Example”);
setLayout(layout);
Button b;
add(b = new ButtonO); // 1
b.setVi sible(false);
add(b - new Button("V+”)); // 2
b.addActionLi stener(this) ;
addfb = new ButtonO); // 3
b.setVi sible(false);
add(b = new ButtonC'H+”)); // 4
b.addActionListener(this) ;
status r- new Button(“Vgap=”-<-l ayout.getVgapO +
Hgap^ ’+layout .getHgapO) ;
add(status);
add(b - new Button(“H-”)); // 6
784
java.awt
огни .ayon
getRowst
b.addActionListener(this);
add(b - new ButtonO); // 7
b.setVi sible(false);
add(b = new Button("V ")); // 8
b.addActionLi stener(thi s);
setSize(100, 200);
showO ;
}
public void actionPerformed(ActionLvent evt) {
String what = evt.getActionCommandO;
if (“H+".equals(what)) {
layout.setHgap(layout.getHgapO *5);
} else if (UH-”.equals(what)) {
layout.setHgap(Math.max(0, layout.getHgapO-5));
} else if OV*1’.equals(what)) {
layout.setVgap(layout.getVgapO+5);
} else if (“V-".equals(what)) {
layout.setVgap(Math.max(0, layout.getVgapO- 5));
}
// Update status button
status. setLabel (“Vgap=’'+1 ayout. getVgapO +
", Hgap-” + l ayout .getHgapO);
inval idateO;
vali date();
}
public static void main(String[] args) {
new Mai n();
}
}
getRowsf)
PURPOSE Retrieves (he number of rows in this grid layout.
SYNTAX public int getRowsO
DESCRIPTION The number of rows in this layout is initialized by the GridLayout constructor and changed using setRows(). See the class description for details on rows and columns.
RETURNS A non-negative integer specifying the number of rows. 0 means any number of rows.
SEE Al SO getColumnsO, setRowsO.
EXAMPLE See setColumnsO.
Grid Lay out
gctVgapf)
ja\ a.awl
get Vgap() _
pi rpost. Retrieves the vertical gap between components.
SYM XX public int getVgapQ
DESCRIPTION The vertical gap is initialized by the GridLayout constructor and changed using setVgapQ. See the class description for details on vertical gaps.
RIJTRXS A non-negative integer specifying the xertical gap in pixels.
SI 1: Al SO getHgapQ , setVgapQ.
1 XAMPI F See getHgapQ.
GridLayout()
Pl rposi Constructs a new GridLayout instance.
SYN FAX public GridLayoutQ public GridLayout(int rows, int cols) public GridLayout(int rows, int cols, int hgap, int vgap)
DI SCRIPTION The first form of this constructor creates a new grid layout manager instance with 1 row and 0 columns. The second and third forms of this constructor cre- ate a new grid layout manager instance with the specified rows and columns. If rows is greater than 0. the value of cols is set but ignored and is treated like 0. that is. any number of columns (see the class description for more details), rows and cols cannot both he 0. If hgap and vgap are not specified, they default to 0. An instance of the grid layout manager can be shared by more than one con- tainer. Also, the grid layout manager can be set on a container at any lime, regardless of the number of the components already in the container.
PAR/XMI.I'ERS cols A non-negative integer specifying the number of columns in the grid: 0 means “any number" of columns.
hgap rows A non-negatixe integer specifying the space between columns in pixels. A non-negative integer specifying the number of rows in ihc grid: 0 means “any number."
vgap A non-negative integer specifying the space between rows in pixels.
liXCl'HIOSS
Il legal ArgumentException
If rows and col s are both 0.
EXAMPLE See the class example.
786
java.awt ипшлпмщ lay<nitContainer()
layoutContainer()
PURPOSE Lays out the container's components according to the settings of the layout manager.
SYNTAX public void layoutContainer(Container cont)
DESCRIPTION This method is called by the container when the layout is invalidated and needs to be redone. The number of cells is determined by the number of specified rows and col- umns and the number of components in the container. The cell height is lhe largest integer such that rows ж celllleight + (rows-1) * (the vertical gap) does not exceed the current height of the container, likewise for the cell width. Nei- ther the minimum nor preferred sizes of the components are used in the calcu- lations. All of the components are resized to the cell size and then placed in order from left-to-right and top-to-bottom. Any remaining space is distributed to the right and bottom of the container.
PARAMETERS cont The non-null container using this layout instance.
SEE ALSO Contai ner.
EXAMPLE See LayoutManager.
minimumLayoutSize()
PURPOSE Calculates the minimum dimensions needed to lay out the components.
SYNTAX public Dimension minimumLayoutSize(Container cont)
DESCRIPTION The minimum dimension is calculated by determining each component's mini- mum size. The maximum of these minimum dimensions determines the size of a cell. The minimum dimensions of the entire layout is based on this cell size and all of the gaps between them.
PARAMETERS cont The non null container using this layout instance.
Returns /X non-null Dimension object containing the minimum size of the grid lay- out.
sell also Component.mi nimumSi ze().
example See LayoutManager.
java.awt
GridLayout
preferredLuyoutSizet )
preferredLayoutSizet)
Pl RFC3SI Calculates the preferred dimensions needed to lay out the components.
SX M‘A\ public: Dimension preferredLayoutSize(Container cont)
A DiSCRIPHON The preferred dimension is calculated by determining each component's pre-
в ferred size. The maximum of these preferred dimensions determines the si/c ol
(' a cell. The preferred dimensions of the entire layout is based on iliis cell si/e
I) and all of the gaps between them.
PVR VMt П RS
E cont The non-null container using this layout instance.
1 Ri ll R\S A non-null Dimension object containing the preferred si/c ot the grid .ayout.
SLE ALSO Component.preferredSi ze()•
11 EXAMPLE See LayoutManager.
.1 remove Layout Component)
К 1. Pl’RPOSE Remines a component from the layout.
M sV X 1 XX public void removed ayoutComponont(Component comp)
N DE.M'RIPTIOX This method is called by the las out manager's container whenever a eompo nent is removed from the container. Since the grid layout does not use named
() components. this method does nothing. Il needs to be defined in order to sat-
P isfy the LayoutManager interface.
(,) PVR \MI II RS
R comp The component about to be removed from the container. Ignored.
S l\ AM PI 1 Sec LayoutManager.
i
1 setColumnsf)
V pi rposi Sets the number of columns in this grid knout.
w X syxfa.x public void setColumnsfint columns) di st ripiiox This method sets the number columns in this layout to be columns. When die
Y components are laid out. if the number of rows is nonzero, the nttmbci ol col- umns is ignored. See the class description for details.
788
!<1V <l.dW I
setC'oiumns( )
PAR.AMF П Ks
columns A non-negative integer specifying the number of columns. 0 means any num-
ber of columns. The number of rows and the number of columns cannot both
be 0 at the same time.
exceptions
Il legal ArgumentExcept!on
If col umns is 0 when the layout’s number of row s is already 0.
seealso getCol umns() , setRowsQ.
example This example cre- ates a frame with a 2-х-З grid layout manager. Ten but- tons arc added to the grid to illus- trate how the com- ponents are laid out. Four control buttons labeled row+. row-, column-»-. and
’ GridLayout Ro ws and Columns Example |МрП E31
Button 0 Button 1 Button 2
Button 3 Button 4 Button 5
Button 6 Button 7 Button 8
Button 9 row+ row- I
column* column- rows=0, cols=3
I IGCRi: 202: Rows and Columns in a GridLayout.
column- are added to change the number of rows and columns in the grid lay-
out. A status button (last button in the layout) is used to display the current
rows and columns specified. See Figure 202.
The fifteen buttons are initially laid out in two row s (the number of columns is
ignored because rows is nonzero). As you manipulate the number of rows and
columns, notice that the number of columns is effective only when the number
о I" rows is set to 0.
import java.awt.*-*;
import java.awt.event:
class Main extends Frame implements Act!onListener f
GridLayout layout = new GridLayout(2, 3);
Button status;
Main О {
super (’“Gri dLayout Rows and Columns Example”);
setLayout(1ayout);
// Create 10 buttons for layout
for (int i =0; i <10; i ) {
add( new Button^'Button " + ijJ;
}
// Add control buttons
Button b;
add('b = new Button(**row+”j) ; // 1
GridLawut
setlfgapt)
ja\ a.aw l
A
В
(
h.addActionl istenor(this);
add(b new Button(“row-")); / •' 2
b.addAct i on! i stener(thi s);
add(b • new But ton(“cо ,iurrn+”)); // 3
b.addAc t ionl i stoner(thi s);
add(b new Button(“column ")): // 4
b.addA< t ionLi stener(thi s);
status - new But ton(“rows-”41ayout.getRowsO +
'*. col s-”+layout. get Co lumnsO);
add(status);
setSi zo(100, 200);
show();
E
G
H
1
.1
К
L
M
X
0
p
Q
R
public void actionPerformed(AttionEvent evt} {
String what = evt. getActionCorrmandO ;
if (“row+”.equa’s(what)) {
layout,setRows(layout.get Rows 0*1);
} else if (“row ”.equa1s(what)) {
int min (1ayout.qet(olumns() 1- 0) ? 0 ; 1;
1 ayout. set Rows (Math .max (rri n, layout. qot RowsO-1)) ;
} else if (“colurrnequals(what) ) {
1 ayout . setCol urr ns (1 ayout .getCol umns()+l) ;
} else if (“column ".equals(what)) {
int min (layout. getRowsO !- 0) ? 0 : 1;
1 ayout. setCol umns(^ath.max(0, layout. get( ol urrns() • 1));
}
// Update status button
stat us. set 1 abe 1 (“rows--" * layout.get RowsO +
“, col s=”*l ayout . get Col umnsO) ;
i nval idateO ;
vali date();
1
public static void rra i n(St ri ng J args) {
new i^ain();
}
S
setHgap()
pi rposi Sets the horizontal gap between components.
swiw public void setHgap(int hgap)
di sc riptio\ This method sets the horizontal gap ot this lax out to be hgap.
description for details.
parxxn H.Rs
hgap ,\ non negative integer specifying the horizontal gap in pixels.
siiaisu qetHgapO, setVgapQ.
I:\ampi I See getHgapQ.
790
javii.awi
setRowst)
setRows()
— —
PURPOSE Sets the number of rows in this grid layout.
SYNTAX public void setRows(int rows)
description This method sets the number rows in this layout to be rows. When the compo- nents are laid out» if the number of rows is nonzero, the number of columns is ignored. See the class description for details.
parameters rows A non negative integer specifying the number of rows. 0 means any number of row s. The number of rows and the number of columns cannot both be 0 at the same time.
EXCEPTIONS
IllegalArgumenttxception
If rows is 0 when the layout's number of columns is already 0.
SEEALSO getRowsO, setColumnsO.
example: See setColumnsO.
setVgapf)
PURPOSE Sets the vertical gap between components.
SYNTAX public void setVgap(int vgap)
DESCRIPTION This method sets the vertical gap of this layout to be vgap. See the class description for details.
PARAMETERS vgap A non-negative integer specifying the vertical gap in pixels.
SEE ALSO getVgapO , setHgapO.
example See getHgapO.
java.awt
GridLayout
toString()
toString()
rpose Generates a string representation of the layout manager's state.
syntax public String toStringO
DiiSCRrmoN This method generates the string that contains the layout manager's clas
name, the size of the two gaps, and the number of rows and columns.
This method is typically used for debugging.
returns A non-nul 1 string representing the layout manager’s state.
overrides j ava.1ang.Obj ec t.toSt ri ng О.
example See java.lang.Object.toStringO.
J
К
L
M
N
О
P
Q
R
S
T
X
Y
Z
792
java, awl
IllegalComponentStateException
Syntax
class IllegalComponentStateException extends IllegalStateException
Description
IllegalComponentStateException is thrown when the program attempts to perform an
operation on an AWT component while the component is not in an appropriate state to perform
the operation.
IllegalComponentStateException should not be caught or declared in the throws
clause of a method.
SUMMARY ~
Constructor
Il1egalComponentStateException О
Constructs an
IllegalComponentStateException instance.
See Also
Component.getLocal e(), Component.getLocationOnScreenО,
java.lang.Il legalStateException, TextComponent.setCaretPosition().
Example
The following code will throw an IllegalComponentStateException when it executes
getLocationOnScreenО on the frame because the frame has not been made visible yet.
import java.awt.*:
class Main {
static public void main(String[] args) {
ja\ a.awt
IllegalComponentStateException
IllegalComponentStaleEixeeptionf)
Frame fl = new FrameC'Frame Example");
fl.$etSize(200. 100);
System,out.println("location on screen: “ + f 1.get LocationOnScreenQ) ;
В
c IllegalComponentStateExceptionO
D Pl RPC )SF. Constructs an IllegalComponentStateException instance.
E F SYMAX public Ill egalComponentStateFxcepti on() public TllegalComponentStateFxception(Srring msg)
Cl DESCRIP 11<>.\ This constructor creates a new instance of IllegalComponentStateExcep-
H PARAMETERS tion. ?\n optional string msg can be supplied that describes this particular instance of the exception.
J к msg A possibly nul 1 string that gives details about this exception.
L
M
N
О
P
Q
R
S
T
I’
V
W
X
Y
7.
794
java.awt
Image
Syntax
public abstract class Image
Description
An image is a repository of pixel values. Images are typically
created by way of an image stream that involves an image pro-
ducer—the object that supplies pixel values and an image
consumer—the object that takes the pixel values and places
them in an image object. See Figure 203. In this architecture,
an image can be created without having all of the pixels in it.
Typically methods that return images actually return an image
object immediately and then 1111 in the pixels later. The image
object can then be painted regardless of whether all of the pix-
els are available. If it is necessary to determine if all of the
pixels are loaded, use Component .checkimage (). An object
can register for updates as new pixels become available (see
the “Image Observer” section later in this item) or it can wait
until all of the pixels are loaded (see MediaTracker).
If an error occurs during the delivery of the pixels, none
of the methods that operate on the image (e.g., Graph-
El (JURE 203: I mage Producer.
Consumers, and Filter.
ics.d rawimage О ) will fail, although the image will not appear correctly on the screen. The
. program must explicitly check for errors to determine if an error occurred (see Compo-
nent . checkimage О )•
One or more image filters can be inserted between an image producer and the image con-
sumer to modify the pixel values as they pass through the fillers. See the ImageFi 1 ter class
for more details.
It is not possible to directly retrieve the pixels in an image. It must be done indirectly by
retrieving the image's producer (using getSourceO) and then reading the pixels as the pro-
ducer delivers them. The PixelGrabber class makes this process more convenient. See the
PixelGrabber class for more details.
Image Observer
An image observer is an object that is interested in some information about an image
that is not yet available. Two methods in this interface take an image observer as a
Image
java.awt
parameter—getWidthO and getHeightO. If an image s dimensions are not >et available,
these methods return -1. If an image observer is registered (that is, the image observer is not
null), the image observer will immediately be notified via the ImageObserver.imagellp-
dateO method as soon as the dimension information is available. See ImageObserver class
A tor more details.
All components arc image observers. This means that whenever you paint an image that
hasn't been completely loaded and register the component as an image observer, the compo-
nent will be automatically notified whenever the image gets new pixels. This makes it
P extremely easy to render images progressively.
K Multiframe Images
P Not only can the pixels of an image not all be present, but also the set of pixels in an image can
change with time. This can happen if the image is a mult iframe image. An example of a multi-
frame image is an animated GIF. An image observer will be notified whenever the frame of an
H image changes. If the image observer is a component painting an animated GIF. the notifica-
M tion will cause the component to repaint itself.
J Produced and Off-screen Images
K There are two kinds of images: produced and off-screen. Produced images are generated v ia an
image producer. Off-screen images are created with the method Component .creat elmage ().
L l he main difference between the two is that graphics contexts can be created only for an off-
M screen image. If it is necessary to paint on a produced image, you must first copy the produced
N image to an off-screen image.
o Image Properties
p An image property is an arbitrary value that an image producer associates with an image. For
example, an image producer that decodes GIF images might make the comments embedded in
Q the image available as a property. Another example is image filters that set the “filters'' prop-
r erty so that the final image consumer can determine how the image has been filtered. There
no predefined set of image properties that an image might have. So you need to consult the
image producer’s documentation to discover what image properties it might set. Note that any
1 image filters used in creating an image may also add their own image properties to the image
U as the image flows through the filter.
By convention, the property name “comment’* is used to store an optional comment that
V can be presented to the user as a description of the image, its source, or its author.
W
x
Y
Z
796
java.awi
Ulli
Kato StJMMAMV
K-—---------
Property Field and Method getPropertyO UndefinedProperty Retrieves an image property. This object is returned by getPropertyO if the property is not defined.
Dimensions Methods getHeightO getWidth0 Retrieves the height of this image. Retrieves the width of this image.
painting Method getGraphicsO Retrieves a graphics context for this image.
Scaling Method and Constants
getScaledlnstancef) SCALE_^AREA-AVE RAGING SCALE-DEFAULT SCALE^FAST Generates a scaled version of this image. Use AreaAveragingScaleFilter as the scaling algorithm. Use a default image scaling algorithm. Use an image scaling algorithm that emphasizes speed over smoothness. |
SCALE_REPLICATE SCALE^SMOOTH Use Repl i cateScal eFi 1 ter as the scaling algorithm. Use a scaling algorithm that emphasizes image smoothness over speed.
Image Producer Method getSource() Retrieves the image’s producer.
Clean-up Method flush() Destroys all resources used by this image.
See Also
java.awt.1mage.AreaAveragingScaleFilter, java.awt.image.ImageConsumer,
java.awt.image.ImageFiIter, java.awt.image.ImageObserver,
java.awt.i mage.Repli cateScaleFilter.
Image
ц|\ a.awt
Example
This example implements a
thumbnail image viewer. You can
run this program hx supplying it
ч\ ilh the name of a graphics tile
or the name of a directory II' the
former. the image in the file is
displaced: if the latter all of the
images (.gif and .jpg) in the
director} are displaced. Sec Pig
ure 204.
Ihe images are displaced in
an area consisting of 125 x 125
cells. If an image is larger than
this area, it is scaled down to fil
I КД RE 204: Thumbnail hnagr \’ivuvr.
its aspect ratio is retained. If xou click a thumbnail, die
thumbnail creates a window that's large enough to hold the image in its entirely
This program can be enhanced to show an expanded image within (he same fiame lather
than another w indow 4 being created to hold it.
i nport java.awt. •;
’riport java.awt.event:
irrpo-t java .io.';
class Mair extends Franc {
i rt cet1 Sizp - 1?5;
Vai n(r i 1 e d; -) {
St r i ng J fil enaires ;
if (dir. isDi rectoryO) {
it If directory, get f’les.
f i1enanes di r.1i st();
f e’se {
/' Otherwise, only show one Jniage.
filenames = now St ringfil;
f i lena’nes'0] * dir.get NameО:
// Set dir to be the directory rathe^ thar the t’le.
air new F- i 1 e(d i r. getParent ()) ;
}
ftr (int i-0; i<f-'enames.length: od {
if (f; lenarres4 J . t oLowerCaseO . ends’w i t h(“ . gi f ”)
f i 1 enamesf i 1 . toLowerCase().ends’wi t h(" . ’pg’") ) {
'/ Create ard add tne : hunbnai ’ cormonert .
/' Also need to translate the relative filenare to an
// absolute filename in o^der to fetch the ’mage.
Corponent c = new Thurbnail(
get Tool k4' t () . get Irrago(di r.getAbso" ut ePath О
* F i 1 e. separator ♦ f i 1 ena-nos ' i 1 ) . f i lenanes | :
aod(< ):
798
J<1 v a.nw I
c.setSize(cel1 Size, cellSize);
}
}
// Listen for events and layout.
addWi ndowLi stener(new WindowEventHandler()) ;
setLayout(new FlowLayoutO);
pack();
show О ;
}
public Dimension getPreferredSizeO {
Insets insets - getlnsetsO;
int count = getComponentCount0;
int hgap - ((Flowtayout)getLayoutO).getHgapO ;
int vgap = ((FlowLayout)getLayout()).getVgapO;
// Maximum of 4 columns,
int cols = Math.max(l, Math.min(count, 4));
// The following code exactly determines the size
// necessary to show all the thumbnails.
Dimension d - new Dimension(
col s'* (cel 1 Si ze+hgap) * hgap,
((count-l)/cols*l)*(celISize+vgap) + vgap);
// Don’t forge the frame’s insets,
d.width +- insets.left Onsets, right;
d.height *- insets.top+insets.bottom;
// Make sure it’s not larger than the screen.
Dimension screenDim = getToolkit().getScreenSize()
d.width = Math.min(d.width, screenDim.width);
d.height = Math.min(d.heightr screenDim.height);
return d;
}
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
// Destroy the window.
di sposeO;
}
}
public static void main(String[] args) {
File dir;
if (args.length -- 1) {
dir - new File(args[0]):
} else {
di r = new File(".");
}
new *ain(dir);
}
}
class Thumbnail extends Canvas {
Image image;
String name;
Image
java.awt
1humbnai1(Image image, String name) {
this.image - image;
this*name - name;
A
В
I)
F
F
G
H
J
К
L
M
О
P
Q
R
S
1'
u
V
w
X
Y
z
// Start loading the image.
preparelmage(image, this);
// Listen for mouse events.
addMouseListener(new MouseEventHandler());
}
public void paintCGraphics g) {
update(g);
}
public void update(Graphics g) {
FontMetrics fm - g.getFontMetrics();
int w - getSize().width;
int h = getSize().height - fm.getHeight();
int iw - image.getWidth(this);
int ih = image.getHeight(this):
if(iw>0&&ih>0) {
// Scale down if necessary.
if (iw > h) {
ih = ih * w / iw:
iw = w;
}
if (ih > h && ih > 0) {
iw - iw л h / ih;
ih - h;
}
// Clear background.
g.setColor(Col or.1ightGray);
g.fillRect(0, 0, w, h);
// Center the image.
g.drawlmage(image, (w-iw)/2, (h-ih)/2, iw, ih, this);
}
// Draw the name.
h - getSizeO . height;
g.setCol or(Col or.bl ack);
g.clearRect(0, h, w, fm.getHeight());
g.drawStri ng(name,
(w-fm.st ringwidth(name))/2, h-fm.getHeight()+fm.getAsc
g.drawRect(0, 0, w-1, h-1);
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
new ImageViewer(image, name);
}
public void mouseFntered(MouseEvent evt) {
// Set the frame’s title.
fi ndFrame().setTi tle(name);
}
public void mouseExited(MouseEvent evt) {
// Clear the frame’s title.
fi ndFrame().setTitle(nul1);
}
800
flush(
// Returns this component’s frame.
public Frame findFrameO {
Component c - getParent();
while (c !- null && ! (c instanceof Frame)) {
с = c.getParent();
)
return (Frame)c;
}
}
}
class Imageviewer extends Frame {
Image image;
ImageViewer(Image image, String name) {
super(name);
this.image = image;
// Listen for events and show frame.
addW'indowListenerfnew WindowEventHandler());
рас к О;
show();
}
// Determine the size of the frame that will show the image.
public Dimension getPreferredSize() {
Insets insets getlnsetsO:
return new Di mens ion(image.getWidth(null) + insets.left * insets.right,
image.getHeight(nul1) + insets.top + insets.bottom);
}
public void paint(Graphics g) {
g.drawlmagefimage, getlnsetsO.1 eft. getlnsetsO.top, this);
}
class WindowFventHandler extends WindowAdapter {
public void windowClosing(Windowtvent evt) {
// Destroy the window.
di spose();
}
}
}
flush()
PURPOSE Destroys all resources used by this image.
SYNIAX public abstract void flush()
description 'This method is used to explicitly tree any resources that may be used by the image. This includes any cached information and any system resources used to store the image. All of the image data is automatically regenerated if the image is used again.
Image
geiGraphics()
ja\a.awt
Explicitly calling flushf) is not necessary; since the Object.finalizef)
method calls this method when the Image object is reclaimed. Houe\er. in
some cases it may be desirable to free up some memory quick!} if it is certain
lhe image will not be used again or is unlikely to be used for a while.
getGraphics()
pi’rposl Retrieves a graphics context for this image.
syntax public abstract Graphics getGraphicsO
descrip i ion This method succeeds onl} for off screen images (see Component. ere at elm-
ageQ) Attempting to call getGraphicsO for an image that is not an off-
screen image results in a ClassCastException being thrown.
returns /X non-nul 1 Graphi cs object that can be used to paint on lhe image.
see also Component. createlmagef). Graphics.
example This example allows you to draw over an image read from the file s}stem. See
Figure 205. Since you cannot draw on a produced image, the program first
copies the produced image to an off-screen image and then makes all drawing
operations to the off-screen image.
import java.awt.-;
import java.awt.image.*;
import java.awt.eventw;
class Main extends Frame {
Main(String filename) {
super(”getGraphics Example”);
// Retrieve the image.
add(new ImageCanvasC
get Toolki t О.getImage(f i1 ename)),
BorderLayout.CFNTER);
setSiz?(200, 200);
show();
}
1
static public void mai n(St ri ng^J args) {
if (args.length == 1) {
new Main(args[0]);
} else {
System.err.println(“usage: java Main
J
}
FIG I RE 205: Drawing Over an
I mage.
<image f ile>”);
class ImageCanvas extends Component {
Image image;
Image backBuffer;
Graphics backBufferG;
802
getlleighu)
ImageCanvas(Image image) {
this.image - image;
preparelmageCimage, this);
addMouseMotionLi stener(new MouseMotionHand1 er());
}
public void paint(Graphics g) {
update(g);
}
public void update(Craphics g) {
if (backBuffer == null) {
if (g.drawTmage(image, 0, 0, this) && backBuffer null) {
int w = image.getwidthfthis);
int h - image,getHeight(this);
backBuffer = createlmage(w, h);
backBufferG - backBuffer.getGraphicsO;
backBuff erG. setColor(getBackgroundO) I
backBufferG.fillRect(0, 0, wt h);
backBufferG.drawlmage(image, 0, 0, this);
}
return;
}
g.drawImage(backBuffer, 0, 0. this);
class MouseMotionHandler extends Mouse^otionAdapter {
public void mouseDragged(MouseEvent evt) {
backBufferG.setColor(Color.red);
backBufferG.fillOval(evt.getX(), evt.getY(), 5, 5);
repaintO ;
}
}
getHeightO
PURPOSE Retrieves lhe height of (he image.
SYNTAX public abstract int getHeightflmageObserver observer)
DESCRIPTION The height of the image may not yet be available. In this case. -1 is returned and if observer is non null, observer will be notified when the height becomes available.
PARAME-1 ERS observer The image observer to register for image updates; if null, no updates are desired.
RETURNS The height of the image or -1 if the height is not yet available.
seealso getWidthQ- ImageObserver.
EXAM Pl 1 See the class example and getScaledlnstanceQ.
java.awt
image
getPropertyt)
getProperty()
purpose Retrieves an image property.
syntax public abstract Object getProperty(String name, TmageObserver
A
observer)
description This method retrieves the image property called name. The image properties
that are available depend on the image producer. If name refers to an image
propertv that is not defined by an image producer, the Undef i nedProperty
object is returned. If name refers to an image property whose value is not vet
available, null is returned.
If the name image property is not yet available and observer is not null,
observer will be notified when the property does become available.
PAR AMI: KERS
name The non-null image property name.
observer The possibly null image observer.
returns The value of the property called name. Undefi nedProperty is returned if the
property is not defined, null is returned if the value of the property is not vet
available.
see also Imageobserver. imagellpdateO, Undefi nedProperty.
example This code fragment displays any comments associated with an image.
Image image;
if (image.getProperty(“comment", this) ! = Image.UndefinedProperty) {
System.out.println(image,getProperty(“comment", this);
}
Q
R
S
T
u
V
w
X
Y
Z
getScaledInstance()
purpose Generates a scaled version of this image.
symax public Image getScaledlnstance(int width, int height, int hints)
description This method generates and returns a scaled version of this image. The dimen-
sions of the new image are specified by width and height. If width or
height is negative, that dimension is derived from the other. In particular, the
derived number is such that the aspect ratio of the original unsealed image is
retained. For example, if the original image is 10 wide and 20 high and width
is -1 while height is 60. width will be set to 30. All of the pixels in the new
image may not be completely loaded.
804
Jd'ul.dVH
g et S c al ed I n ч tan се (
If hints includes either SCALE..SMOOTH or SCALE^REA.AVERAGING.
AreaAveragingScaleFilter is used: otherwise. Repl i cateScal eFi 1 ter is
used. See lhe class descriptions of these filter classes for more details.
parameters
height The possibly negative height of the scaled version.
hints A mask or*d from one or more of SCALE_AREA_AVERAGING. SCALE_DF FAULT.
SCALE-FAST. SCALE.REPLICAIE. or SCALE-SMOOTH.
width The possibly negative width of the scaled version.
returns
A scaled version of this image.
SEE ALSO
java.awt.image.AreaAveragingScaleF11 ter,
java.awt.image.ReplicateScaleFi 1 ter.
example This example reads in an image
and then displays the image
along with a scaled-up version
of the image. See Figure 206.
To scale the image, it uses
getScaledlnstanceO to gel
a scaled version of the image.
’ getScaledlnstance Example BEEj
import java.awt.*;
import java.awt.image.*;
EIGl'RE 206: Scaling an Image,
class Main extends Frame {
Main(String filename) {
superC'getScaledlnstance Example");
// Retrieve the image.
add(new ImageCanvas(getToolkit().getlmage(fi1 ename)),
Borderlayout.CFNTFR);
setSi2e(300, 300);
show();
}
Static public void mainfString[1 args) {
if (args.length == 1) {
new Main(argsL0]);
} else {
System.err.println(“usage: java Main <image file>"):
}
}
class ImageCanvas extends Component {
Image
getSourcet)
java.awt
A
R
C
D
E:
I-
G
H
J
К
L
M
int scale = 3;
Image image;
Image scaledlmage;
ImageCanvas(Image image) {
this.image = image;
preparelmage(image, this);
}
public void paint(Graphics g) {
update(g) ;
}
public void update(Craphics g) {
int w =- 'mage,getWidth(this);
int h = image.getHeight(this);
if (w >= 0 .| h >= 0) {
if (g.drawlmage(image, 0, 0, this) && scaledlmage «=- null) {
// The original image has completed loading
,'/ Get its dimensions and get scaled version
scaledlmage - image.getScaledInstance(w*scale, h*scale,
Image.SCAl E_SMOOTH);
}
}
if (scaledlmage !- null) {
g.drawlmage(sea 1edlmage, w, 0, this);
}
}
}
()
P
Q
R
S
T
L
V
W
X
Y
Z
getSource()
14 rposi Retrieves the image s producer.
s>xiv\ public abstract Imageproducer getSourceO
DESCRIPTION
SEE Al SO
EX XME’L E.
The image producer is used to regenerate lhe image's pixels and is typically
used in conjunction with image filters.
ImageFilter, ImageProducer.
This example reads in an image and scram-
bles it by swapping the left and right sides
of the image. See Figure 207. A subimage
of the original image is created with the
help of the CropImageFi 1 ter class. The
image producer of the original image is
retrieved and used to create an image
stream that passes through the crop image
filter. An off-screen image holds lhe new
scrambled image.
FIGURE 2071
Image. getSourceO.
806
jUVtl.HWt
Im a:
gel Source
import java.awt.*;
import java.awt.image.w;
class Main extends Frame {
Main(String filename) {
super(“getSource Example");
add(new ImageCanvas(getIool ki t().getImage(filename)),
BorderLayout.CENTER);
setSize(100, 100);
show();
}
static public void Tain(String[] args) {
if (args.length == 1) {
new Main(args[02);
} else {
System.err.println(“usage: java Main <image file>");
}
}
}
class ImageCanvas extends Component {
Image oldimage;
Image image;
TmageCanvas(Image image) {
oldlmage image;
waitForImage(image);
}
void waitForTmage(Image image) {
try {
// Use a media tracker object to wait until all the pixels
// have been retrieved.
MediaTracker tracker = new Medialracker(this);
tracker.addimage(image, 0);
tracker.wai tForID(0);
} catch (Exception e) {
e. pri ntStackTraceO ;
}
}
Image getSubImage(Image image, Rectangle r) {
// Create crop image using a CropImageFilter.
CropImageFilter imgf = new CropImageFilter(
r.x, r.y, r.width, r,height);
ImageProducer ip - image.getSourceO;
ip - new Fi1teredImageSource(ip, imgf);
Image result = getToolkit().createlmage(ip);
waitForImage(result);
return result;
}
public void paint(Graphics g) {
int w - oldimage.getWidth(this);
int h = oldlmage.getHeight(this);
if (image == null) {
image = createlmaqe(w, h);
Image
getWidthf)
ja\ a.awt
Graphics g2 = image.getGraphics();
g2.drawImage(getSubImage(oldimage, new Rectangle(0. 0, w/2, h)).
w/2, 0, this);
g2.drawImage(getSubTmage(oidImage, new Rectangle(w/2, 0, w/2. h)),
0, 0, this);
g2 .disposeO ;
}
g.drawTmage(iriage, (getSi ze() .width-w)/2, (getSize().height h)/2.
thi s);
1
getWidth()
PURPOSE Retrieves the width of the image.
SYNTAX public abstract int getWidth(ImageObserver observer)
DESCRIPTION This method retrieves the width of the image. If the width is not available. 1 is returned. If observer is non null, observer will be notified when the width becomes available.
PARAMETERS observer The image observer to register for image updates: if null, no updates are desired.
RETURNS The width of the image: -1 if the width is not yet available.
SFE ALSO getHeightQ. ImageObserver.
EXAMPLE See the class example and getScaledlnstanceQ.
SCALE AREA_AVERAGING
PURPOSE Use AreaAveragingScal eFI Iter as the scaling algorithm.
SV MAX public static final int SCALE AREAvAVERAGING
DESCRirriON This constant is used as a parameter to getScaledlnstanceQ The image object is free to substitute a different filter that performs the same algorithm as AreaAveragi ngScaleFi 1 ter. See AreaAveragingScaleFi 1 ter for derails of the algorithm. The value of this constant is 16.
SLl ALSO getScaledlnstanceQ , java.awt. image.AreaAveragingScaleFiIter.
EXAMPLE See a similar usage of SCALE__SMOOTH in getScaledlnstanceQ.
80S
java.awt
image
SCALE_DHFAL’LT
SCALE_DEFAULT
PURPOSE Use the default scaling algorithm.
SYNTAX public static final int SCALE-DEFAULT
description This constant is used as a parameter to getScaledlnstanceQ. The default scaling algorithm uses ReplicateScaleFilter. The value of this constant is 1.
SEE ALSO getScaledlnstanceQ , java.awt.image.Repl 1 cateScaleF i Iter,
example See a similar usage of SCALE-SMOOTH in getScaledlnstanceQ.
SCALE_FAST_______________________________________________
purpose Use (he scaling algorithm that emphasizes speed over smoothness.
SYNTAX public static final int SCAlF.FAST
description This constant is used as a parameter to getScaledlnstanceQ. The value of
this constant is 2.
see also getScaledlnstanceО •
example See a similar usage of SCALE-SMOOTH in getScaledlnstanceQ.
SCALE REPLICATE
purpose Use ReplicateScaleFilter as the scaling algorithm.
syntax public static final int SCALE_RE₽LICAEL
description This constant is used as a parameter to getScaledlnstanceQ. The image
object is free to substitute a different filter that performs the same algorithm as
ReplicateScaleFilter. See ReplicateScaleFilter for the details of the
algorithm. T he value of this constant is 8.
see also getScaledlnstanceQ , java.awt, image. Rep И cateScaleFil ter.
example Seen similar usage of SCA1 F_SMOOTH in getScaledlnstanceQ.
Image java.awt
SCALE SMOOTH
SCALE-SMOOTH
PLRPOS1 Use the scaling algorithm that emphasizes smoothness over speed.
SYNTAX public static final int S€ALF_SMOOTH
DI SCRIPTION This constant is used as a parameter to getSealedInstance(). When SCALE_SMOOTH is specified as a parameter to getScaledlnstanceQ. it uses the AreaAveragingScaleFiIter. See AreaAveragingScalel ilter for the details of the algorithm. The value of this constant is 4.
SEEALSO getScaledTnstanceO . java.awt. i mage .AreaAve rag i ngSc al eFi Iter.
EX AMPLE See getScaledlnstanceO.
PCRPOSF This object is returned by getProperty О if the propertv is not defined.
SYNTAX public static final Object UndefinedProperty
Si l: Al SO getProperty0.
1 ХДМР1 1 See getPropertyО.
810
java.awl. image
ImageConsumer
Syntax
public interface ImageConsumer
Description
Images are painted on a surface using a streaming architec-
ture that involves an image producer which is responsible for
supplying a stream of pixel data, and an image consumer,
which is responsible for displaying that stream. See Figure
208. This architecture allows the progressive rendering of
images as the pixels are delivered from a remote source.
The ImageConsumer interface defines all of the methods
that are necessary for a class to receive pixels from an image
producer. See the ImageProducer interface for details on
how to register an image consumer to receive pixels from an
image producer.
• ImageProducer |
TmageFi 1 ter
ImageFiIter j
j ImageConsurrer
Hints
A hint is a bit of information about pixel delivery that the
image producer gives to the image consumer prior to deliver-
ing the pixels. Using these hints, the image consumer might
be able to implement some optimizations that would speed up the processing time.
FIGI RE 208: Image Producer,
Consumers, and Filter.
Multiframe Images
The innage can contain multiple frames, as in the case of a video source. This is the default, in
the absence of the SINCLEFRAME hint from the image producer.
MEMBER SUMMARY
Image Completion Status Bits
IMAGEABORTED Specifics that the image production was aborted.
IMAGEERROR Specifics an error occurred.
SINGLEFRAMEDONE Specifies that one frame of a multifrarne image is complete
STATICIMAGEDONE Specifies that the image is complete.
('on tinned
IreageCоns шт er
ImageConsumer
java.awt .image
MEMBER SUMMARY j
Pixel Delivery Hints COMPLETFSCANLINES Specifies that pixels will be delivered in complete scanlines.
RANDOMPIXELORDER STNG1FFRAME STNGL EPASS TOPDOWNLEI TRIGHT Specifies that pixels u ill be delivered in an arbitrary order. Specifies that the image contains only one frame. Specifies that pixels will be delivered in a single pass. Specifies that pixels will be delivered in left right, top-down order.
Methods Called by the Image Producer imageCompleteO Called to deliver completion status to the image consumer. setCol о rMode 1 () Cailed to de 1 i\ er the color model for the source image. ; setDimensionsO (’ailed to deliver the dimensions of the source image. setHints() Called to specify how the pixels will be delivered. setPixels() Called to dclixer pixels to the image consumer. 1 setPropert ies() (’ailed to deli\er the properties for the source image.
(
J
К
[ See Also
ColorModel, ImageFilter, ImageObserver, Imageproducer, java.awt.Image.
M
N Example
0 This example implements the ImagelnfoGrabber class. This class is used to retrieve all of
the attributes of an image width, height, color model, hints, properties, and pixels. The pixels
P that are retrieved using ImagelnfoGrabber are the original pixels.
q Note: Much of the functionality provided by the ImagelnfoGrabber class is nm\ u\ail-
able in the Java 1.1.2 version of PixelGrabber. The main difference is that PixelGrabber
does not make the hints and properties of the image available.
S The example also reads an image and prints the available information about the image. If
T the image's color model is an index color model (see ColorModel). then the colors in the
image's color model are displayed, including the number of times each color is referenced in
the image.
V
import java.awt.
\V import java.awtJ mage.*;
import java.uti I .•••;
X
class Main {
Y Image image;
7 Main(String filename) {
ImagelnfoGrabber iig = new ImagelnfoGrabberO;
image - Toolkit.getDefaultToolkit().getlmage(filename);
812
jli v a.<i w 1.1 tllilgC
if (! i ig. grabinfo (image. getSourceO)) {
System.err.println(“Error fetching image “ + filename);
System.exi t(l);
}
System.out.println(“size - “ * iig.width “x” + iig.height);
System.out.print(“hints = ,k);
if ((iig.hints & ImageConsumer.COMPLETESCANLINES) !- 0)
System.out.print(“COwPLETESCANLINES -);
if ((iig.hints & ImageConsumer.RAND0MPTXF1 ORDER) ’= 0)
System.out.printО RANDOMPIXELORDER “);
if ((iig.hints & ImageConsumer.SINGLEPASS) > 0)
System.out.printC'SINGLEPASS “);
if ((iig.hints & ImageConsumer.TOPDOWNLEFTRIGHT) U 0)
System. out.pri nt("TOPDOWNLEFI RIGHT “);
System.out.println();
System.out.printingig.properties.size() - “ properties");
// Only deal with index color model images
if (iig.ColorModel instanceof IndexColorModel) {
IndexColorModel cm - (IndexColorModel)iig.colorMode1;
int'] pixelValueCount = new intri<<cm.getPixelSizeOl;
System.out.println(“transparent pixel - “
+ cm.getTransparentPixel ());
// Count number of times pixel values are used.
for (int i=0; i<iig.bytePixels.length; i++) {
pi xelValueCount[ii g.bytePixels[i]&0xff]+*;
}
// Print colors in color model and their reference count,
for (int i=0; i<pixelValueCount.length; i*+) {
System.out.pri ntln(i
+ t (cm.getRed(i)&0xff)
+ “ ,k + (cm.getGreen(i)&0xff)
♦ “ “ + (cm.getBlue(i)&0xff)
+ “/” ♦ (cm.getAlpha(i)&0xff)
* “ count:" + pixelValueCountTil):
}
}
System.exi t(0);
}
static public void main(String[] args) {
if (args.length != 1) {
System.err.printin(,kusage: java Main cimage f i le>”);
System.exi t(l);
}
new Main(args[0]);
}
}
class ImagelnfoGrabber implements ImageConsumer {
// These are the public fields which the client can
// use to retrieve the image info.
public int width;
public int height;
publ ic int hints;
public Hashtable properties;
public ColorModel ColorModel;
ImageConsumer
java.awt.image
public Vector additionalColorModeis = new Vector();
// One of the following fields is null and the other is not.
public int[] intPixels;
public byte[] bytePixels;
Л // Private fields
private int status;
В private ImageProducer producer;
C // Returns true if the image was fetched successfully; false othe
public synchronized boolean grabTnfo(ImageProducer ip) {
D status г- 0;
(producer - ip).startProduction(this);
E try {
while (status — 0) {
F wait();
}
G } catch (InterruptedException e) {
return false;
H }
return status > 0;
И
J public void setDimensions(int w, int h) {
width w;
К height h;
}
1,
public void setHints(int h) {
M hints = h;
}
S
public void setProperties(Hashtable props) {
О properties = props;
}
P
public void setColorModel(ColorModei cm) {
Q colorModel = cm;
}
R
public void setPixels(int srcX, int srcY, int srcW, int srcH,
S ColorModel cm, byte pixelsL], int srcOff, int
{
T if (cm != colorModel) {
if (’additionalColorModels.contains(cm)) {
I’ addi tionalColorModel s.addElement (cm);
}
V }
if (bytePixels == null) {
W bytePixels = new byte[width * height];
}
X for (int x=srcX; x<srcX * srcW; x++) {
for (int y=srcY; y<srcY + srcH; y+>) {
Y bytePixels[y * width + x] =
pixels[(y-srcY) * srcScan t- (х-srcX) + srcOff];
Z }
}
1
814
jit v «1. it w 1.1 mage
public void setPixels(int srcX, int srcY, int srcW, int srcH,
ColorModel cm, int pixels[], int srcOff, int
if (cm !* colorModel) {
if (!additionalColorModels.contains(cm)) {
addi tionalColorModels.addElement(cm);
}
}
if (intPixels null) {
intPixels -- new intfwidth •• height!;
}
for (int x=srcX; x<srcX + srcW; x+*) {
for (int y^srcY; y<srcY - srcH; y+>) {
intPixels[y * width * x' =
pi хе 1s[(y-srcY) v srcScan + (x-srcX) + srcOff];
}
}
}
public synchronized void imageComplete(int s) {
switch (s) {
case STAUCIMAGEDONE:
case SINGLEFRAMFDONE:
status = 1;
break;
default:
case IMAGEFRROR:
case IMAGEABORTED:
status -1;
break;
}
producer.removeConsumer(this);
noti fyAl1();
}
Output
size = 55x68
hints = COMPLEI ESCANLINES SINGlFPASS TOPDOW’N LEFTRIGHT
0 properties
transparent pixel = 58
0: 216 216 224/255 count:0
1: 152 144 136/255 count:l
2: 160 40 68/255 count:2
3: 128 32 48/255 count:2
4: 200 208 208/255 count:0
5: 184 40 84/255 count:0
6: 192 184 184/255 count:0
7: 40 32 40/255 count:3
8: 96 88 80/255 count:2
9: 216 32 56/255 count:l
(lines deleted)
250: 240 232 216/255 count:2
251: 208 64 180/255 count:2
252: 248 248 240/255 count:223
253: 248 240 248/255 count:0
254: 240 248 248/255 count:0
255: 248 248 248/255 count:17
java.awt.image
ImageConsumer
COMPl.ETESC AN LINES
COMPLETESCANLINES
PERPOSE Hint specifying that pixels will be delivered in complete scanlines.
SYNTAX int COMPLETESCANLINES
DESCRIPTION This hint specifies that pixels delivered via setPixel s() will he delivered in complete scanlines. More than one scanline may possibly be delivered in a setPixel s() call. This constant is delivered as a hint using the setHintsQ method.
.Sil ALSO setHi nts().
EXAMPI I: See the class example.
IMAGEABORTED
Pl RPOSE Status bit specifying that the image production was aborted.
SYNTAX int IMAGEABORTED
DESCRIPTION This status bit is used in the imageCompleteO method call to indicate that the image production process was aborted.
SEE ALSO imageCompleteO.
EXAMPLE See the class example.
imageCompletef)
t’IRPt )SI Called by the image producer to deliver the completion status to lhe image consumer.
SYMAX void imageCompletefint status)
DESCRIPTION The imageCompleteO method is called when the image producer has fin- ished delivering all of the pixels that the source image contains or when a sin- gle frame of a multiframe sequence has been completed or when an error in loading or producing the image has occurred. The status bits in status indi- cate which of these preceding cases occurred. (See ImageConsumer for details.) Unless the image consumer is interested in subsequent frames, it should call ImageProducer. removeConsumerO to remove itself from the producer's list of registered consumers.
PARAMET ERS status /X combination of the status bits as defined in the ImageConsumer class.
816
jti Vii.il w i. linage 1MAGFFRROB
SEE ALSO ImageProducer.removeConsumerO.
EXAMPLE: See the class example.
IMAGEERROR
PURPOSE: Status bit specifying that an error occurred.
SYNTAX int IMAGLERROR
DESCRIPTION This status bit is used in the imageCompl ete() method call to indicate that an error occurred while the image was being produced.
SEE ALSO imageCompleteQ -
EXAMPLE See the class example.
RANDOMPIXELORDER
PURPOSE: Hint specifying that pixels will be delivered in an arbitrary order.
SYNTAX int RANDOMPIXELORDLR
DESCRIPTION This hint is set via the setHintsQ method and specifies that pixels in setPixels() calls will be delivered in an arbitrary order. This informs the consumer not to use any optimizations that depend on the order of pixel deliv- ery. If neither the RANDOMPIXELORDER nor I OPDOWN LEFTRIGHT hints are spec itied, then RANDOMPTXELORDER is assumed. An example of an image that has the RANDOMPIXELORDER hint is an interlaced GIF image.
SliE ALSO setHintsO, I0PD0WNI FFTRIGHT.
EXAMPLE. See the class example.
setColorModelf)
purpose: Called by the image producer to deliver the color model for the source image.
SYNTAX void setColorModel(ColorModel model)
DESCRIPTION This method is called hy the image producer to inform the image consumer that model will be used by the majority of pixels in subsequent setPi xel s() calls. Note that each set of pixels delivered using setPixelsQ contains its own color model, so no assumption should be made that this model will be the only one used in delivering pixel values. An example of when the color model
java.awt. image
ImageConsumer
setDimensionsf )
set by setColorModel О might differ from (he model used in setPixels() calls is an image filter that changes colors by modifying the color model rather than the pixel values.
PAR AML IL RS model A non-null color model.
SH-. Al SO ColorModel.
1 ХЛМР1 1 See the class example.
st‘tl)iinensions()
Pl RPOSL Called by the image producer to deliver the dimensions of lhe source image.
S'» M AX void setDimensions(int width, int height)
DESCRIPTION This method is called b) an image producer to inform the image consumer that lhe image is width pixels wide and height pixels high. This method must be called before setPixels() so that the image consumer can preallocate anj necessary storage beforehand.
PVR Wil l T-RS height width The height of the image in pixels. The width of the image in pixels.
LX AM Pi ,F See the class example.
setHints()
PURPOSE Called by the image producer to specify how the pixels will be delivered.
SYXT AX void setHints(int hintFlags)
DESCRIPTION B> default, the image producer can deliver pixels in any order it chooses, and the image consumer must be able to handle them. However, in some case'* an image producer may produce pixels in a particular order that an image con- sumer can lake advantage of. Tor example, the image consumer may process the pixels more quickly if il knows that pixels will be delivered in top down fashion. See lhe ImageConsumer interface for the possible set of hints and what they mean.
PARAMETERS hintFlags A set of bits that specify how pixels will be delivered.
SI T Al so COMPLETESCANLINES. RANDOMP1XELORDFR. STNGLEPASS. SINGLEFRAMF. TOPDOWNLEFTRIGHT.
EXAMPLE See lhe class example.
818
setPi xels(
setPixels()
PURPOSE Called by the image producer to deliver pixels to the image consumer.
SYNTAX void setPixels(int x, int y, int w, int h, ColorModel model, byte[] pixels, int offset, int scansize); void setPixels( int x, int y, int w, int h, ColorModel model, i nt [ ] pixels, int offset, int scansize);
DESCRIPTION The image producer delivers the pixels of the image to the image consumer in one or more calls to the setPixel$() method. The parameters x. y, w. and h specify the destination location of the pixels. In particular, the pixel x, у (the top-left corner pixel of the destination rectangle) is stored in the pixels array at [x + у * scansize -t- offset]. The pixel data is located in the pixels array. If the pixel values are 8 bits, the First form of the setPi xel s() method is called: otherwise, the second form is called. Only one of the two forms will be called. The specified color model model should be used to convert the pixel values into colors and alpha components. The color model is not necessarily the same as the one supplied by the setColorModel () method call.
PARA MET ERS h model offset pixels scansize w X У The height of the rectangle in which the pixels are destined. The non-null color model used to translate the pixel values. The index of the first pixel in the pixel array. The non-nul 1 array of pixel values. The width to use when extracting pixels from pi xel s. The width of the rectangle in which the pixels are destined. The v-coordinate of the rectangle in which the pixels are destined. The у-coordinate of the rectangle in which the pixels are destined.
SEE ALSO ColorModel.
example See the class example.
setProperties()
pl rposf: Called by the image producer to deliver (he properties for the source image.
syntax void setProperties(Hashtable props)
description An image property is an arbitrary value that an image producer associates with
an image. For example, an image producer that decodes GIF images might
make the comments embedded in the image available as a property. Another
java.awt j mage
ImageConsumer
SINGLETRAME
A
В
example is an image filter that sets the ‘'filters” property so that the final image
consumer can determine how (he image has been filtered.
Different image producers will set different image properties. Sec the docu-
mentation of a particular image producer to determine the property names and
types that that producer will set.
D
E
I
PARAMETERS
props A non-nul 1 hashtable of properties.
example See the class example.
SINGLEFRAME
purpose Hint specifying that the image contains only one frame.
SYNTAX int SINGLEFRAME
description This hint is set via the setHintsQ method and specifies that the image con-
tains only one frame. When all of the pixels in the image have been delivered,
the imageCompl eteQ method is called with the status STATICIMAGEDONE.
If the SINGLEFRAME hint is not specified, the image consists of many frames.
An example of an image type that does not have the SINGLEFRAME hint is an
MPEG image. In this case, after all of the pixels of a frame have been delivered
the imageCompl eteQ method will be called with the status SINGLEFRAMED-
ONE.
see ALSO i mageComp 1 ete(), setHintsQ, STATIC IMAGF DONE.
example See the class example.
SINGLEFRAMEDONE
purpose Status bit specifying that one frame of a multiframe image is complete.
SYNTAX int SINGLFFRAMFDONE
description This status bit is used in the imageComplete() method call to indicate that
one frame of the image is complete but that there are more frames to be deliv-
ered.
.si i also imageComp1eteО.
example. See the class example.
820
java.awt.image
agcv.iiHMiinci
SINGLEPASS
SINGLEPASS
PURPOSE Hint specifying that pixels will be delivered in a single pass.
SYNTAX int SINGLEPASS
description This hint is set via the setHintsO method and specifies that pixels in setPi xelsQ calls will be delivered in a single pass. TTiat is. each pixel will appear in only one call to any of the setPi xel s О methods. An example of an image format that does not have this hint is a progressive JPEG image that defines pixels in multiple passes, each more refined than the previous.
SEE ALSO setHintsO.
EXAMPLE See the class example.
STATICIMAGEDONE
PURPOSE Status bit specifying that the image is complete.
SYNTAX int STATICIMAGFDONE
DESCRIPTION This status bit is used in the imageCompleteO method call to indicate that the image is complete and that there are no more pixels or frames to be delivered.
SEE ALSO imageCompleteO-
EXAMPLE See the class example.
TOPDOWNLEHRIGHT
PURPOSE Hint specifying that pixels will be delivered in left-right, top-down order.
SYNTAX int TOPDOWNLEFTRIGHT
DESCRIP1JON This hint is set via the setHintsO method and specifies that pixels in setPixelsO method calls will be delivered left-to-right and then top-to-bot- tom. That is, each row of pixels is filled left-to-right and when the row is com- plete, the next row of pixels is filled left-to-right. If the hint COMPLETESCANLINES is not also specified and not all of the pixels in a scan- line are delivered in a call to setPixels(), then the delivered pixels can be only a single pixel high. If TOPDOWNLEFTRIGHT is not specified, the RAN- DOMPIXELORDER hint is assumed, that is, pixels can be delivered in any order. An example of an image that would have the TOPDOWNLEFTRIGHT hint is a noninterlaced GIF image. An interlaced GIF image would not have this hint.
SEE ALSO RANDOMPIXEL ORDER. setHintsO.
EXAMPLE See the class example.
java.awt.image
ImageFilter
w
X
ImageProducer
rz
ImageFi1 ter
I
I
ImageF i1 ter
ImageConsumer
Syntax
public class ImageFilter implements ImageConsumer, Cloneable
Description
[mages arc pain(ctl on a surface using a streaming architecture
that involves an image prodiu ei\ which is responsible for sup-
plying a stream of pixel data, and an image consumer which
is responsible for displaying that stream. See Figure 209. This
architecture allows the progressive rendering of images as the
pixels are delivered from a remote source.
In this architecture, one or more image fillers can be
inserted between the image producer and the image con-
sumer. An image filter is used to transform an image. For
example, the crop image filter (see CropImageFilter) is
used to extract a smaller image from an image, while the
RGB image filter (see RGBImageFi 1 ter) is used to change
the colors in an image.
You can build your own image filter by implementing the
ImageConsumer interface. Alternatively, you can subclass
the ImageFilter class, which provides default implementa-
tions for all the methods in the ImageConsumer interface. After subclassing the image filter,
you can override only lhe necessary ImageConsumer methods. The other methods will pro-
vide the default behavior.
An instance of the Image Fi Iter class itself can be constructed and used in a pixel stream.
Howexer, it will ha\e no effect on lhe pixels that pass through.
HGVRE 209: Image Producer.
Consumers, and Filter.
Y
822
juvci.ci wi. irriage
:mber summary
Creation Methods
cloneO
getFi 1 terlnstanceQ
Constructs a clone of this image filter.
Cremes a new ImageFi 1 ter instance.
Subclass Overrides Called by the Image Producer
imageCompleteO ('ailed to deliver the completion status to the image con- sumer.
setColorModel() setDimensionsO setHintsO setPixelsO setPropertiesQ ('ailed to set lhe color model for the source image. Called lo sei lhe dimension of lhe source image. Called to specify hov. the pixels will be delivered. Called to deliver pixels. Called to set the properties for the source image.
Pixel Retransmit Method
resendTopDownl eftRightO Retransmits lhe pixels in top-doun, left right order.
Consumer Field
consumer
Contains lhe image consumer of the pixel data.
See Also
ImageConsumer, TmageObserver, Imageproducer, java.awt.Image.
Example
This example implements a type of image filter that flips
the image horizontally or vertically. See Figure 210.
Note: Flipping images is very easy to do using Graph-
ics.drawlmage(). However, this example is still useful
for demonstrating how to implement an image filter.
The image is displayed in the ImageCanvas class. If
you click the canvas, it flips the image either horizontally
or vertically. The overridden setDi mensionsQ method
FIGI RE 210: ImageFilter.
records the width and height of the image. These arc used
in moving the pixels to the new location as they pass through the filter. The setHi nts() over-
ride sets the ImageConsumer.RANDOMPIXELORDER bit and clears the ImageConsumer .TOP-
DOWNLEFTRIGHT because as the pixels pass through the image filter, they are translated in an
order different from what lhe filter's producer intended.
In the setPi xel s() override, notice that a temporary buffer must be allocated to store the
displaced pixels. In other words, the image filler subclass cannot modify lhe pixel array sup-
plied by setPixels().
Imager liter
java.awt.image
In (he setProperti esQ override, the flip filter adds the flipH and flipV properties
using the current flip values. If there is more than one flip filter in the pixel stream, the final
values of the fl ipH and flipV properties will reflect the resulting transformation. That is, if
there are two filters that flip the image vertically, they will cancel out each other and the result -
A ing fli pV property value will be fal se.
D
I-
P
H
J
К
I.
M
X
()
p
Q
R
S
1
u
V
w
X
Y
L
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.uti1.*;
class Main extends Frame {
Main(String filename) {
super(“ImageFi1 ter Example");
add(new ImageCanvas(getToolkit().getImage(fi1 ename)),
BorderLayout.CENTER);
setSize(50. 100);
show();
1
static public void mai n(St ring[] args) {
if (args.length 1) {
new Main(args[0]);
} else {
System.err.println(“usage; java Main <image file>");
}
1
}
class ImageCanvas extends Component {
Image flipimage;
Image image;
boolean flipH - true, flipV = true;
FlipFil ter imgf = new FlipFi1ter();
ImageCanvasflmage image) {
this.image = image;
processlmage();
// Add mouse listener
addMouseLi stener(new MouseFventHandlerO) ;
}
public void paint(Graphics g) {
g.drawlmage(fliplmage, 0, 0, this);
}
void processImageQ {
ImageProducer ip = image.getSourceQ ;
imgf.set Flip(flipH, flipV);
ip - new Fi1teredImageSource(ip, imgf);
flipimage = getToolkit().createlmage(ip);
repai nt();
}
class MousetventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
824
ja v L.llllii£tr
if (fl 1 pH & flipV) {
flipH flipV - false;
} else if (flipV) {
flipH r- true;
flipV = false;
} else {
flipV -- true;
}
processImageO ;
J
}
class FlipFilter extends ImageFilter {
int width, height;
boolean flipH, flipV;
public void setFlip(boolean flipH, boolean flipV) {
this.flipH =- flipH;
this.flipV = flipV;
}
public void setDimensionsfint w, int h) {
super.setDimensionsfwidth * w, height = h) ;
}
public void setPropertiesCHashtable props) {
boolean h = false;
boolean v = false;
Object bh props.get(“flipH”);
Object bv -= props.get(“flipV”);
if (bh null) {
h = ((Boolean)bh). bool eanValueO ;
}
if (bv ! = null) {
v = ((Boolean)bv). bool eanValueO ;
}
h flipH;
v a= fl ipV;
props .putC'fl i pHM , new Boolean(h));
props.put(“flipV", new Boolean(v));
consumer.setProperties(props);
}
public void setHints(int h) {
h |= ImageConsumer.RANDOMPIXELORDFR;
h &= -ImageConsumer.TOPDOWNLEFTRIGHT;
super.setHints(h);
public void setColorModel(ColorModel model) {
super.setColorModel(model);
1
public void setPixels(int srcX, int srcY, int srcW, int srcH,
ColorModel model, byte pixelsf], int srcOff, int srcScan) {
int s - srcOff;
byte[j tempBuff = new byte[srcW * srcH];
ImageFilter
java.awt .image
Л
В
c
D
E
F
G
H
J
К
L
M
N
О
P
Q
R
S
T
и
v
w
x
Y
z
for (int y=0; y<srcH; y*+) {
for (int x-0; x<srcW; x++) {
int d - 0;
if (flipV) {
d *= (srcH-у l)*srcW;
} else {
d -»= y^srcW;
}
if (flipH) {
d +- (srcW-x-1);
} else {
d *- x;
1
tempBuff[d] = pixels[sj;
si-*;
}
1
if (flipH) {
srcX - width - (srcX+srcw);
}
if (flipV) {
srcY height (srcY+srcH);
}
super.setPixels(srcX, srcY, srcw’, srcH, model, tenpBuff, 0, srcScan);
J
public void setPixels(int srcX, int srcY, int srcW, int srcH,
ColorModel model, int pixels[], int srcOff, int srcScan) {
int s « srcOff;
int[] tempBuff - new int[srcw •' srcH];
for (int y=0; y<srcH; y + + ) {
for (int x-0; x<srcW; x+*) {
int d = 0;
if (flipV) {
d += (srcH-y-1) “'stcW;
} else {
d += yAsrcW;
}
if (flipH) {
d += (srtW-x-l);
} else {
d +- x;
}
tempBuff[d] = pixels^]:
}
1
if (flipH) {
srcX = width - (srcX+srcw);
}
if (flipV) {
srcY = height - (srcY+srcH);
}
super.setPixels(srcX, srcY, srcW, srcH, model, tempBuff, 0, srcScan);
public synchronized void imageComplete(int status) {
super.imageComplete(status);
826
java.awt.image imager liter clone()
}
}
clone()
PURPOSE Constructs a clone of this image filter.
SYNTAX publ ic Object cloneO
description The default implementation calls Object.clonef). which creates a new instance of this image filter that has a shallow copy of the variables. If the image filter refers to other objects or arrays that are modified during the filter- ing, this method must be overridden in order io clone these objects or arrays.
RETURNS A copy of this image filter.
OVERRIDES java. lang.Object .c loneO
EXAMPLE See java.1ang.Object.c1one 0.
consumer . . . . ..
PURPOSE Contains the image consumer of the pixel data.
SYNTAX protected ImageConsumer consumer
DESCRIPTION The image filter delivers pixel data to the image consumer referred to by this field. This field is initialized by a getFi 1 terlnstanceQ method call, typi- cally by lhe FilteredlmageSource class during the construction of a pixel stream.
SEE ALSO getF i1terlnstance(), ImageConsumer.
getFilterInstance()
PURPOSE Creates an instance of this filter.
SYNTAX public ImageFilter getTi1terlnstanceflmageConsumer ic)
DESCRIPWN This method returns a unique instance of this image filler that will deliver pixels to the image consumer ic. It is typically used by Fil- teredlmageSource during the construction of an image stream. By default, it calls c lone() and returns the result.
PARAMETERS ic The non-nul 1 image consumer of the new image filter instance.
returns A non-null instance of this image filter.
ImageFilter
imageCompletef)
java.awt.image
imageComplete()
PURPOSE Called by the image producer to deliver the completion status to the image consumer.
SYNTAX public void imageComplete(int status)
DESCRIPTION By default, this method calls the consumer's imageCompleteO method by using status. See ImageConsumer .imageCompleteO for details on how to override this method and how to interpret status. An image filter need not remove itself from the image producer's registered list of consumers, since the image consumer at the end of the stream will remove it.
PARAM E1 ERS status A combination of the status bits as defined in the ImageConsumer class.
SEE ALSO ImageConsumer, imageCompleteO.
resendTopDownLeftRight()
PURPOSE Retransmits the pixels in top-down, left-right order.
SYNIAX public void resendTopDownLeftRight(ImageProducer ip)
DESCRIPTION This method is called by the image consumer of this filter if the image con- sumer wants the pixels to be retransmitted in top down, left-right order, ip should be the image producer that is sending pixels to this filter. The image filter can respond to this request in one of three ways; • If the filter does not move around the pixels, it can forw ard the request to the image producer by calling requestTopDownLeftRi ghtResendQ. using itself as the image consumer. This is the default behavior. • If the filler has the pixels and can retransmit them in lhe right order, it should override this method and do so. See the ImageProducer. requestTop- DownLeftRi ghtResendQ method for details on how it should dcli\ei lhe pixels to the image consumer. • The filter can ignore this call and no retransmission will occur
PARAMETERS ip The non-null image producer that supplies this image filter with pixels.
SEE ALSO Imageproducer.requestTopDownL eftRightResendQ .
setCoIorModel()
purpose Called by the image producer to set the color model for the source image.
828
java.awLiniage imagvriurr set Dimensions!)
SYNTAX public void setColorModel(ColorModel model)
description This method should be overridden to process setColorModel () calls from the image producer. The default implementation simply passes model to the image consumer.
PARAMETERS model The non-null color model of the source image.
SEE ALSO Imag eCon s ume r.setColorModel().
example See the class example.
setDimensionsO
PURPOSE Called by the image producer to set the dimension of the source image.
SYNTAX public void setDimensions(int width, int height)
DESCRIPTION This method should be overridden to intercept setDimensionsO calls from the image producer. The default implementation simply passes the dimensions width and height to the image consumer.
PARAMETERS height wi dth The height of the source image in pixels. The width of the source image in pixels.
SEE ALSO ImageConsumer.setDi mensi ons().
example: See the class example.
setHints()
purpose: Called by the image producer to specify how the pixels will be delivered.
SYNTAX public void setHintsfint hintFlags)
description By default, the image filter simply passes the hints hintFlags to the image consumer. However, if the image filter moves pixels around, it must override this method and adjust the hints appropriately before sending them to the image consumer. See the ImageConsumer interface for the possible set of hints and what they mean.
parameters hi ntFlags SEE ALSO Л set of bits that specify how pixels will be delivered. ImageConsumer.setHints().
example See the class example.
java.awt. image
ImageFilter
setPi xels( )
setPixels()
Pl RPOSE Called by the image producer to deliver pixels.
SYNTAX public void setPixels(int x, int y, int w, int h, ColorVodel model, byteLJ pixels, int offset, int scansize) public void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int offset, int scansize)
DESCRIPT ION By default, the image filter simply passes off the pixels, unchanged, to the image consumer. If the image filter needs to modify the pixels, it must oxerride both setPixels() methods. See ImageConsumer.setPixels() for details on how the parameters are used.
parameters h model offset pixels scansize fhe height of the rectangle in which the pixels are destined. The non-null color model used to translate the pixel values. The index of the first pixel in the pixel array pixels. The non-null array of pixel a allies. I’he width to use when extracting pixels from lhe pixel array pixels.
w l he width of the rectangle in which the pixels arc destined.
X The А-coordinate of the rectangle in which the pixels are destined.
У l he v-coordinatc of the rectangle in which the pixels are destined.
SEE ALSO ImageConsumer.setPixe1s().
EXAMPLL Sec the class example.
setProperties()
Pl RPOSE Called by the image producer to set the properties for the source image.
SANE XX public void setPropertiesfHashtable props)
IH SCRIPTION By default, the image filler passes on the properties after adding its name to the 'filters'* property. The filter should override this method if it wants to add or query a property.
PAR XXlETf RS
props I’he non-null properties of the source image.
SEE: ALSO ImageConsumer. setPropertiesQ.
EXAMPL L See the class example.
830
java.awt. image
ImageObserver
Syntax
public interface ImageObserver
Description
An object that implements the ImageObserver interface can register itself lor progress infor-
mation as an image is loaded. For example» an AWT canvas might want to progressively dis-
play the image as il is being loaded. Methods such as Image. drawImageO and
Image.getWidthО accept image observers and automatically register them with the image
producer.
When an image observer is registered, it receives all progress information via the image
Update() method c^ll. However, only progress information that the image observer asks for is
delivered to the imageUpdateO method. For example, if the image observer were to call
Image.getWidthО and the Image.getWidthО width information was not yet available
(that is, -1 was returned). imageUpdateO would be called as soon as the width became
available. Otherwise if Image.getWidth() was not called or if Image .getWidth() returned
the width, the imageUpdateO method would not be called.
SUMMARY
Image Update Method
imageUpdateO Called by an image consumer lo deliver status information about the
loading of an image.
Image Update Status Bits
ABORT ALLBITS ERROR Indicates that the image loading process was aborted. Indicates that the entire image has been successfully loaded. Indicates that an error was encountered while the image was being loaded.
FRAMEBITS Indicates that a frame of a multiframe image has been successfully 1 loaded.
HEIGHT properties SOMEBITS WIDTH Indicates that the height of lhe image is now available. Indicates that lhe image properties are now available. Indicates that additional pixels are now available. Indicates that the width of the image is now available.
ImageObserver
java.awt .i mage
See Also
ImageConsumer, ImageFiIter, ImageProducer, java.awt.Image.
A
В
C
П
E
F
J
К
L
M
N
О
P
Q
R
S
T
и
V
w
X
Y
Z
Example
I bis example creates an image observer that can be
wrapped around another image observer in order to
“spy" on the calls to the i mageUpdate О method. The
information is printed on standard output. See Figure
211.
ImageObserver Ex..
H
HGl'RE 211: ImageObserver.
import java.awt.•;
import java.awt.image.*;
import java.net.";
Import java.uti1.A;
class Main extends Frame {
Main(String filename) {
super(“ImageObserver Example");
try {
// Retrieve the image.
Image image = getToolkit().getlmage(filename);
add(“Center", new ImageCanvas(image));
} catch (Exception e) {
e.pri ntStacklrace();
}
setSize(50, 100);
show() ;
}
static public void main(String[] args) {
if (args.length 1) {
new Mai n(args[0J);
} else {
System.err.println(“usage: java Main cimage file>”);
}
J
}
class ImageCanvas extends Component {
Image image;
ImageObserverSpy spy = new ImageObserverSpy(this);
ImageCanvas(Image image) {
this.image - image;
image.getWidth(spy);
image.getHeight(spy);
image.getProperty(“test", spy);
}
public void paint(Graphics g) {
g.drawlmage(image, 0, 0, spy);
}
}
832
J« Wl.llIHlgU
class ImageObserverSpy implements ImageObserver {
ImageObserver obs;
ImageObserverSpy(ImageObserver obs) {
this.obs = obs;
}
public boolean imagellpdate(Image imq. int infoflaqs,
int x, int y, int width, int height) {
System.out. pr intC'x-"tx + ” “) ;
System.out. pri nt(“y=”+y*'’ “) ;
System .out. pri nt (“width-“+wi dth t” “);
System.out.print(“height=M-»-height+” “);
System.out.pri nt(“ i nfof lags-”);
if ((infoflags & ABORT) 0) System.out.print(“ABORT “);
if ((infoflags & ALLBITS) 0) System.out. print(“AU BITS “);
if ((infoflags <& ERROR) !- 0) System, out .pri nt (“ERROR “);
if ((infoflags & FRAMEBITS) '= 0) System.out.print(“FRAMFBITS “);
if ((infoflags & HEIGHT) > 0) System.out.print(“HEIGHT “);
if ((infoflags & PROPERTIES) != 0) System.out-print(“PROPERTTFS “);
if ((infoflags & SOMEBITS) ’ -= 0) System.out.print(“SOMFBITS “) ;
if ((infoflags & WIDTH)!- 0) System.out.print(“WTDTH “);
System.out.pri ntln();
return obs. imagellpdate(irg, infoflags, x, y, width, height);
}
}
Output
x=0 y=0 width=55 height=68
x=0 y=0 width-0 height=0
x=0 y=0 width=55 height=l
x—0 y=l width-55 height=l
x-0 y=2 width-55 height=l
x=0 y=3 width=55 height-1
x=0 y=4 width=55 height-1
infoflags-HEIGHT WIDTH
infoflags-PROPERTIES
i nfoflags=SOMEBITS
infoflags-SOMEBTTS
i nfoflags-SOMEBI1S
infoflags=SOMEBITS
i nfof1ags-SOMEBITS
<many similar lines deleted>
x=0 y-59 width=55 height-1
x-0 y=60 width-55 height=l
x-0 y=61 width=55 height^l
x-0 y=62 width=55 height-1
x=0 y=63 width-55 heiqht-1
x-0 y-64 width=55 height=l
x=0 y-65 width=55 height-1
x=0 y=66 width=55 height-1
x=0 y=67 width=55 height=l
X—0 y=0 width=55 height=68
infoflags-SOMFBITS
i nfof!ags-SOMFBIT S
infoflags-SOMEBITS
infoflags-SOMEBITS
infoflags=SOMEBITS
i nfoflags=SOMEBITS
infoflags-SOMEBITS
infoflags-SOMEBITS
i nfoflags^SOMFBTTS
i nfoflags=AllBITS
ImageObserver ABORT java. awt. image
ABORT
14 RP(\SE Indi calcs that (he image loading process was aborted.
SY VI AX public static final int ABORT
A DESCRIPTION It the ABORT status bit is present in the status Hags passed to the imageUp-
в date() method, no further status will be delivered via the imageUpdateO
с method. Unless the ERROR status bit is also present, the loading of the image can be restarted.
I) In the absence of any other status bits, the x. y. wi dth. and hei ght parameters
E passed to the imageUpdateO method should be ignored.
F SEE ALSO ERROR. imageUpdateO.
G 11 EXAMPLL See the class example.
ALLBITS
J Pl RPOSF Indicates that the entire image has been successfully loaded.
К
[ S\XTAX public static final int ALLBITS
DESCRIPTION If the ALLBITS status bit is present in the status Hags passed to the imageUp-
M dateO method, no further status will be delivered via lhe imageUpdateO
N method. If the image has only one frame, the ALLBITS status bit is used (see
0 the ImageConsumer interface for more information about mu hi frame images). If lhe image is multiframe, lhe FRAMEBITS status bit is used instead.
P This status bit is delivered onl} if Image. drawlmage О was culled and
Q returned false. In the absence of any other status bits, the x. y. width, and
R height parameters passed to the imageUpdateO method should be ignored.
S SEE ALSO java.awt. Image. drawlmage О. imageUpdateO.
T I’ EXAMPLL Sec the class example.
V ERROR
W 14’RPOSE. Indicates that an error was encountered while lhe image was being loaded.
X S'! X 1 AX public static final int ERROR
Y DESCRIPTION If the ERROR status bit is present in the status flags passed to the imageUp-
Z dateO method, no further status will be delivered via the imageUpdateO method. As a convenience, the ABORT flag is also set in the status Hags when-
834
java.awt.image
imageonservei
FRAMEB1T5
ever the ERROR flag is set. So if there is no need to distinguish between ABORT and ERROR, it is safe to lest only for the ABORT flag.
SEE ALSO imagellpdateO.
example See the class example.
framebits_______________
PURPOSE Indicates that a frame of a multiframe image has been successfully loaded.
SYNTAX public static final int FRAMFBITS
description If the image consists of only one frame, then the ALLBITS status bit is used instead to indicate that the image is complete. This status bit is delivered only if Image.drawImageO was called and returned false. In the absence of any other status bits, the x, y, width, and height parameters passed to the imagellpdateO method should be ignored.
SEE ALSO java.awt. Image.drawlmage(). imageUpdate().
EXAMPLE See the class example.
HEIGHT
PURPOSE Indicates that the height of the image is now available.
SYNTAX public static final int HEIGHT
DESCRIPTION If the HEIGHT status bit is present in the status flags passed to the imageUp- date () method, the height parameter contains the height of the image. This height can be retrieved also by using the Image .getHeightО method. This status bit is delivered only if Image.getHeight() was called and returned -1.
SEE ALSO java.awt.Image.getHeight().imageUpdate().
EXAMPLE See the class example.
ImageObserver
innageUpdate()
java.awl.linage
imageUpdate()
pi’rpose ('ailed by an image consumer lo deliver status information about the loading ol
an image.
A SYNTAX public boolean imageUpdate(Image imgT int infoflags, int x, int
В y, int width, int height)
C D E F G H J К L DESCRIPTION This method is called when the image observer asks for a particular piece of information and the information is not yet available. For example, if the image observer called Image.getWidthO and the width information was not yet available (that is. Image.getWidth() returned -1), the imageUpdateO method would be called as soon as the width became available. i nfofl ags contains a combination of status bits that indicate the 1\ pe of status information being provided. For example, the WIDTH status bit indicates that the width of the image is now available, infoflags may contain more than one status bit. To test for the presence of a bit, use the bitwise and' operator: for example: if ((infoflags & WIDTH) 0) { System, out. pri ntl n(“width information is now available"); }
M rhe values (hat are supplied in x. y. width, and height depend on status bib
present in infoflags. For example, if infoflags contains WIDTH, only the
N width parameter contains any information. See the other status bits in this
О interface for details on how the parameters should be interpreted.
PARAMETERS
height
img
infoflags
width
x
У
P
Q
R
S
T
u
V
w
This value depends on the status bits enabled in i nfof 1 ags.
The non-null image being updated.
A set of status bits.
This value depends on the status bits enabled in infoflags.
T his value depends on the status bits enabled in i nfof 1 ags.
This value depends on the status bits enabled in infoflags.
returns true if no further calls to the imageUpdate() are needed.
example See the class example.
X
Y
Z
836
jdvii.iiwi.image
IlUdgl'VU»CI УСГ
PROPERTIES
properties
PURPOSE Indicates that the image properties are now available.
SYNTAX public static final int PROPERTIES
description This status bit indicates that the properties of the image are now available. In the absence of any other status bits, the x. y. width, and height parameters passed lo the imageUpdateO method should be ignored.
SEE ALSO java.awt.Image.getProperty(). imageUpdateO.
example See the class example.
SOMEBITS
PURPOSE Indicates that additional pixels are now available.
SYNTAX public static final int SOMEBITS
DESCRIPTION The x, y. width, and height parameters to the imageUpdateO method indi- cate which pixels of the image are available.
SEE ALSO imageUpdateO.
EXAMPLE See the class example.
WIDTH
PURPOSE Indicates that the width of the image is now available.
SYNTAX public static final int WIDTH
DESCRIPTION If the WIDTH status bit is present in the status flags passed to the imageUp- dateO method, the width parameter contains the width of the image. This width can be retrieved also by using the Image .getWidthО method. This status bit is delivered only if Image. getWidth() was called and returned -1.
SEE ALSO java.awt.Image.getWidth(), imageUpdateO.
example See the class example.
java.awt. image
ImageProducer
A Men огу1ггаде^'<ьг .h
В
c Syntax
p public interface ImageProducer
Г
F
G
I!
J
К
I.
M
Description
Images are painted on a surface using a streaming architecture
that involves an image producer, which is responsible for sup-
plying a stream of pixel data, and an image consumer, which is
responsible for displaying that stream. See Figure 212. This
architecture allows the progressive rendering of images as the
pixels are delivered from a remote source.
The ImageProducer interface defines all of the methods
that are necessary' for a class to generate pixels as an image
producer. See the ImageConsumer interlace for details on
what an image consumer expects from an image producer.
ImageConsumer
N
()
P
FIGURE 212: Image Producer,
Consumers, and Filter.
1 R MEMBER SUMMARY
S T Image Consumer Registration Methods addConsumerO Registers an image consumer with this image producer. I
и i sConsumer() Determines if an image consumer is registered 1 with this image producer.
V w Y 1 removeConsumerО Pixel Delivery Methods requestTopDownLeftRi ghtResendO Removes a registered image consumer from this J image producer. Requests that pixel data be retransmitted in left- right, top down order.
7 I startProductionO Triggers the delivery' of image data.
__________________________i
838
jav a.aw 1.image
imagerroni
See Also
ImageConsumer, ImageFilter, ImageObserver, java.awt.Image.
Example
This example demonstrates how
one might build a new kind of
image decoder. See Figure 213.
The image producer reads infor-
mation from a file and then inter-
prets the data to build an image.
The format and sample image
file follow the example code.
The image producer decodes the
image file at lhe first request for
the pixel data. Once the image is
decoded, lhe image producer
delivers the pixel data in an
FIGI RE 213: ImageProducer.
incremental fashion so that the image can be rendered incrementally. After all of lhe pixels arc
delivered to an image consumer, that consumer is automatical!} removed from the list of con-
sumers.
An image consumer that makes a request for pixels while lhe image producer is producing
pixels is added to the list of consumers and is given the pixel data as soon as possible. The
example creates three images using the image producer to test the code that supports multiple
consumers.
In response to lhe requestTopDownLeftRi ghtResend () method, all of the pixel data is
sent in a single call to setPixelsf).
import java.awt.-';
import java, awt. image.;
import java.awt.event. ';
i mport j ava. i о . ‘;
import java.util. ‘;
class Main extends Fraire {
BlocklmageDecoder ip;
vainfString filename; {
superC’IrrageProducer Example"; ;
Panel p = new Panel() ;
ip - new BlocklmageDecodertnew Fi 1 elnputStreamffi1 ename;; ;
} catch riOException e; {
e.pmntStackTracef; :
System.e*i t(Ij;
p.setLayoutfnew GridLayout(1, 0;;;
ImageProducer
java.a v\ (.image
p.add(new ImageCanvas(ip));
p.add(new ImageCanvas(ip));
p.add(new JmageCanvas(ip));
add(p, Borderlayout.CENTtR);
setSize(325, 220);
A show();
}
В
public static void main(St ring[] args) {
C if (args.length -= 1) {
new Mai n(args[0j);
D } else {
System.err.print In("usage: java Main <input file>”);
F }
}
F }
Ci class ImageCanvas extends Component {
ImageProducer ip;
H Image image;
ImageCanvas(ImageProducer ip) {
this.ip = ip;
j image = createlmage(ip);
addMouseL i stener(new MouseEventHandler());
К }
L public void paint(Graphics g) {
g,drawlmage(image, 0t 0, this);
M }
XI class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
() image -- createlmage(ip) ;
repaint() ;
P }
}
Q }
R class BlocklmageDecoder implements ImageProducer {
StreamTokenizer st;
S ColorModel model;
Vector consumers - new Vector();
] Hashtable properties - new HashtableO;
byte[] pixels;
t; int width - -1, height - -1;
Rectangle [] rects;
V byte[] rectColors;
W
BlocklmageDecoderflnputStream is) {
X Reader r = new BufferedReader(new Input StreamReader(is));
st - new StreamTokenizer(r);
Y }
Z public synchronized void addConsumer(ImagoConsumer ic) {
if (rects 1= null) {
produce(ic);
} else if (1 consumers.contains(ic)) {
840
java. awi. image
iniagerr
consumers.addElement(i c);
}
public synchronized boolean isCon$umer(ImageConsumer ic) {
return consumers.contains(ic);
}
public synchronized void removeconsumer(ImageConsumer ic) {
consumers.removeElement(ic);
}
private int getlntQ throws IdException {
if (st. nextTokenQ '= StreamTokenizer.TT^NUMBER) {
throw (new TOException(“format error”));
}
return (int)st.nval;
}
// Convert the contents of the input file to image data.
private synchronized void processImageO {
try {
// Read width and height
width = getlnt();
height = getlntO ;
// Read colors
int numColors = getlntQ;
byte cmap[] = new byte[numColors * 3];
for (int i-0; i<cmap.length; i*+) {
cmap[i] = (byte)getlntQ;
}
// Create color model.
int n = numColors-1;
int nbits = 0;
while (n > 0) {
n »>= 1;
nbi ts+*;
}
model = new IndexColorModel(nbits, numColors, стар, 0, false, 0);
// Read rectangles and their colors
rects = new Rectangle[getIntO];
rectColors = new bytefrects.length];
for (int i=0; icrects.length; i++) {
rectsLi] - new Rectangle(getlnt(), getlntQ,
getlntQ, getlntQ);
rectColorsfi] - (byte)getlnt();
}
} catch (Exception e) {
e.printStackTraceQ ;
}
}
public void startProduction(ImageConsumer ic) {
if (ic 1= null) {
addConsumer(i c);
if (rects == null) {
ImageProducer
java.au i.image
processImageO ;
for (int i^consumers.size() 1; i>~0; i- -) {
ic - (ImageConsumer)consumers.elementAt(i);
produce(ic);
consumers.removeElement(ic);
}
}
}
private void produceQrrageConsumer ic) {
if (width < 0) {
ic.imageComplete(ImageConsumer.IMAGEERROR);
return;
}
ic.setDimensions(width, height);
i c.set Properti es(properties);
i c . setCo'1 orModel (model) ;
i c. setHi nts(Im.ageConsumer. SING! FPASS
ImageConsumer.SINGLEFRAVE);
pixels = new byteEwidth * height];
ic.setPixels(0, 0, width, height, model, pixels, 0, width);
for (int i=0; i<rects.length; i++) {
Rectangle r ~ rectsfij;
for (int y=r.y; y<r.y+r.height; y*+) {
for (int x=r.x; x<r.x*r.width; x*+) {
pixels[y*width-xj = rectColors[i1;
}
}
ic.set Pixels(г.xT r.y, r.width, r.height, model,
pixels, r. x+r. у-'wi dth, width);
}
ic .imageCompletedmageConsurrer.STA1ICIMACEDONE) ;
}
public void requestTopDownl eftRightResend(Image(’onsumer ic) {
if (pixels 1- null) {
ic.setDimensions(width, height);
i c.setPropert i es(properties);
i c.setColorModel(model);
i c.setHi nts(ImageConsumer.SINGLEPASS
ImageConsumer. TOPDOWNLEITRIGHT I
ImageConsumer.SINGlFFRAME);
ic.setPixels(0, 0, width, height, model, pixels, 0, wid'
}
}
}
Input File
100 180 // image si ze
8 // number of colors
0 0 255 // color 0 transparent
0 255 0 // color 1
0 255 255 // color 2
255 0 0 // color 3
255 0 255 // color 4
255 255 0 // color 5
255 255 255 // color 6
842
java. awt.image
ImageProducer
addConsuinerf)
0 0 0 // color 7
9 // number of rectangles
0 0 20 20 1 // rectangle 0
20 20 20 20 2 // rectangle 1
40 40 20 20 3 // rectangle 2
60 60 20 20 4 // rectangle 3
80 80 20 20 5 // rectangle 4
60 100 20 20 6 // rectangle 5
40 120 20 20 7 // rectangle 6
20 140 20 20 1 // rectangle 7
0 160 20 20 2 // rectangle 0
addConsumer()
PURPOSE Registers an image consumer with this image producer.
SYNTAX public void addConsumer(ImageConsumer ic)
DESCRIPTION This method registers the image consumer ic with this image producer. The image producer may or may not start delivering the image data to the image consumer immediately. The delivery of the image data can be triggered by a call to the startProduction() method.
PARAMETERS' ic The non-null image consumer to register.
SEE ALSO startProductionf).
EXAMPLE See the class example.
isConsumerf)
PURPOSE Determines if an image consumer is registered with this image producer.
SYNTAX public boolean isConsumer(ImageConsumer ic)
PARAMETERS ic The possibly null image consumer to check if registered.
RETURNS true if ic has been registered; false otherwise.
EXAMPLE: See lhe class example.
removeConsumer()
PlRPCtSB Removes a registered image consumer from this image producer
synfax public void removeConsumer(ImageConsumer ic)
ImageProducer
request TopDown I .cftRightResendi)
java.awt л mage
description This method removes the given ImageConsumer object from lhe image pro-
ducer's registered list of image consumers. The image producer will stop send-
ing pixel data to ic as soon as it is feasible. This method call is ignored it ic
has not been registered with this image producer.
PARAMIOTS
i c l he non-nul 1 image consumer to be removed.
example See the class example.
requestTopDownLeftRightResend()
pi’rpose: Requests that pixel data be retransmitted in left-right, top-down order.
syntax public void requestTopDownLeftRi ghtResendCImageConsumer ic)
description This method is used by an image consumer to request that lhe pixels be
retransmitted in top-down, left-right order. Some algorithms can produce
higher-quality output more efficiently if the pixels are received in this order.
In response to this request and if the image producer can retransmit the data in
the requested order, the producer should call setHintsO again, this time
including the TOPDOWN LEFTRIGHT hint.
The image producer can ignore this call if it cannot retransmit the data in the
requested order.
PARAMETERS
ic The non-nul 1 image consumer requesting the retransmission.
see. also ImageConsumer.imageCompleteO , ImageConsumer.setHints() ,
ImageConsumer.setPi xels().
example Sec the class example.
startProduction()
I’ Pl'RPOSE Triggers the delivery of image data.
V SYNTAX public void startProduction(ImageConsumer ic)
w DESCRIPTION This method registers the image consumer ic. if not already registered, and
X starts the delivery of image data to the list of registered consumers.
Y PARAMETERS
i C The non-nul 1 image consumer awaiting image data.
z SEE- ALSO addConsumert).
EXAMPI b See the class example.
844
java. awt. image
IndexColorModel
.......
j IndexColorModel|
________J
Syntax
public class IndexColorModel extends ColorModel
Description
An index color model maintains a particular
palette of colors. Pixel values using the
index color model arc simply indexes into
the palette of colors (see Figure 214). The
number of colors in lhe palette is called the
color map size. For more information about
color models, see the ColorModel class.
Image
Й Pixel
Value
Color Table
0
1
2
ARGB
ARGB
> ARGB
FIGI RK 214: Index Color Model Pixel Values.
^Member summary
Constructor IndexColorModelО Constructsan IndexColorModel instance.
Component Access Methods getAlpha() getAl phasQ Retrieves the alpha component of a pixel value. Retrieves the alpha component of all of the colors in this index । color model.
getBlueQ getBluesQ Retrieves the blue component of a pixel value. Retrieves the blue component of ail of the colors in this index color model.
getGreenO getGreens() Retrieves the green component of a pixel value. Retrieves the green component of all of the colors in this index color model.
getRedQ getRGBO Retrieves the red component of a pixel value. (’onverts a pixel value to a pixel value in the default color model.
getTransparentPi xel() Retrieves the index of the transparent pixel in this index color model. 1 Continued
IndcxColor Model
ja\ a.aw I.image
MEMBER SUMMARY
Color Map Size Method
getMapSi ze()
Retriexes (he color map м/с ol (his index color model
A
В
C
I)
I
I
c;
H
.1
к
I.
M
X
()
P
Q
R
S
T
r
V
w
X
Y
Example
This example implements an image filter (hat can
adjust the alpha component of the colors in an index
color model. Sec Figure 215. The program creates a
frame with an image canxas and a text field. The
image canvas displays the image after it passes
through the image filter. In the text field, you can type
in a number in the range 0.0 to 1.0. The alpha com-
ponents in an index color model are multiplied by this
\ alue. therebx increasing the transparency of the col-
ors. A value of 0.0 forces all the colors to be trans-
^||lndexColof Model Ex... BEB
6
I IGl RI' 215: TndexColorModel .
parent.
The setColorModel () method checks to sec if the color model is an index color model.
If it is. a copy of the color model is made that combines (he old colors with (he new alpha
xalue. The new color model is forwarded to the image consumer. Ihc setPixelsQ method
substitutes the new color model and (hen forwards the pixels to the image consumer (For
brevity's sake, the setPixelsQ method does not properly handle (he case in which (he color
model is not the same as the one supplied lo setColorModel ().)
1 mport java. awt. ' ;
import java.awt.image.л;
import java. awt. event .;
import java.net.-;
import java.uti1.“;
class Main extends Frame implements ActionListener {
TextField textField = new TextField();
ImageCanvas icv;
Main(String filename) {
super(“IndexColorModel Example");
try {
,// Retrieve the image.
URL url = new URL("fi1e;///" + System.get Property("user.dir")
+ "/’’ f filename);
Image urllmage = getToolkit().get 1mage(ur1);
add(icv = new ImageCanvas(urlImage), BorderLayout.CEN1FR);
add(textField, BorderLayout.SOUTH);
} catch (Exception e) {
e.pr~ ntStackTrace();
846
java, awt л mage
}
// Add listener for text field
textField.addActionlistener(thi s);
setSize(50, 100);
show();
}
public void actionPerformed(ActionEvent evt) {
icv. setAlphaFactor(Double, valueOf(textField.getTextO) .doubleValueO) ;
}
static public void mai n(St ring[] args) {
if (args,length =- 1) {
new Main(args[0]);
} else {
System.err.println(“usage: java Main <image file>”);
}
}
}
class ImageCanvas extends Component {
Image newlmage;
Image image;
AlphaFilter imgf = new AlphaFi1ter();
ImageCanvas(Image image) {
this.image = image;
processImageO ;
}
void setAlphaFactor(double afactor) {
imgf,setAlphaFactor(afactor);
processImageO;
public void paint(Graphics g) {
g.drawlmage(newlmage, 0, 0, this);
}
void processImageO {
ImageProducer ip = image.getSourceO ;
ip = new FilteredImageSource(ip, imgf);
newlmage = getToolkitO . createlmage(ip) ;
repaintO;
1
}
class AlphaFilter extends ImageFiIter {
double afactor;
ColorModel transColorModel;
void setAlphaFactor(double afactor) {
this.afactor = afactor;
}
public void setColorModel(ColorModel model) {
if (model instanceof IndexColorModel) {
IndexColorModel
java.awt .image
getAlpha( I
IndexColorModel icm - (IndexColorModel)model;
byte[] reds - new byteficm.getMapSizeOJ;
byte[j greens = new byte[icm.getMapSizeO];
bytefl blues ~ new byte[1 cm.getMapSize()l;
byte[] alphas - new byte[icm.getMapSizeO];
bytef] стар = new byte [i cm. getMapSizeO * 4];
icm.getReds(reds);
i cm.getGreens(greens);
i cm.getB1ues(blues);
i cm,getAlphas(alphas);
int j =0;
for (int i=0; i<icm.getMapSizeO ; i++) {
cmap[j++] - redsfi];
cmap[j+i] - greensfi];
cmap[j*+l - blues[i];
cmap[j4+] = (byte)((alphasfi]&0xff)*afactor);
}
transColorModel = new IndexColorModel(icm.getPixelSizeO,
icm.getMapSizeO, стар, 0, true, icm.getTransparentPixel());
} else {
transColorModel - model;
}
consumer.setColorModel(transColorModel);
}
public void setPixels(int x, int y, int w, int h,
ColorModel model, byte pixelsL], int off, int scansize) {
consumer.setPixels(x, y, w. h, transColorModel, pixels, off. scarsize);
}
public void setPixels(int x, int y, int w, int h,
ColorModel model, int pixelsfl. int off, int scansize) {
consumer.setPixels(x, y, w, h, transColorModel, pixels, off, scansize);
}
}
getAlphaf)
PURPOSE Retrieves the alpha component of a pixel value.
SYNTAX final public int getAlpha(int pixelValue)
DE-SCRIPTION This method retrieves the alpha component of the pixel value pixelValue. The return value must be in the range 0-255. where 0 means completely trans- parent and 255 means completely opaque.
PARAME’I ERS pi xelValue The pixel value specifying a color in the color model.
RETURNS The alpha transparency component in the range 0-255.
EXAMPLE See the class example.
848
java.awt. image
inuexv оюгликк
getAlphas(
getAlphas(J ___
purposed Retrieves the alpha component of all of the colors in this index color model.
SYNTAX final public void getAlphas(byte[] a)
description This method retrieves the alpha component of all of the colors in this index
color model and places the values in a. The number of values placed in a is
determined by the color map size (see getMapSi ze()). a can be larger than
the color map size: the unused array elements are not modified.
PARAMETERS
a A non-nul 1 array that is at least as large as the color map size.
SEE ALSO getMapSi ze О -
example See lhe class example.
getBlue()
purpose Retrieves the blue component of a pixel value.
SYNTAX final public int getBlue(int pixelValue)
DESCRIPTION This method retrieves the blue component of the pixel value pi xelValue. The return value must be in the range 0- 255. where 0 means no blue and 255 means maximum blue.
PARAMETERS pi xelValue The pixel value specifying a color in lhe color model.
RETURNS The blue color component in the range 0 255.
example See the class example.
getBl ues()
purpose Retrieves the blue component of all of the colors in this index color model.
syntax final public void getBIues(byte[] b)
description This method retrieves lhe blue color component of all of the colors in this
index color model and places the values in b. l he number of values placed in b
is determined by the color map size (see getMapSi ze()). b can be larger than
the color map size; the unused array elements are not modified.
parameters
b A non-null array that is at least as large as the color map size.
java.aw (.image
IndexColorModel
getGreen()
seh also getMapSizeQ.
example: See the class example.
/X getGreenf)
в Pl RPOSE- Retrieves the green component of a pixel value.
c S'! X I AX final public int getGreen(int pixelvalue)
D I-: DESCRIPTION This method retrieves the green component of the pixel value The return value must be in the range 0 255. where 0 means no :
i- means maximum green.
G PARAM E- T E-RS
H pi xelValue I he pixel value specifying a color in the color model.
RE.Tl RNS The green color component in the range 0 25 5.
J example-: See the class example.
pixelvalue.
erecn and 255
К
1. getGreens() . ... - - - V
M Pl RP( )SE Retrieves the green component of all of the colors in this index color model.
N SV MAX final public void getGreens(byte[] g)
() DEiSf RIPTIDN This method retrieves the green color component of all of the colors in this
P Q R PAR XME.TE.RS index color model and places the values in g. The number of values placed in g is determined by the color map size (see getMapSizeO ). g can be larger than the color map size: the unused array elements are not modified.
S 9 A non null array that is at least as large as the color map size.
T SEE Al SO getMapSizeO
i: example See the class example.
getMapSize()
purpose Retrieves the color map size of this index color model.
syntax final public int getMapSizeQ
returns The color map size.
example See the class example.
850
java.awt.image
П1игл\дни| 1UUUCI
getRedf
getRcd()
PURPOSE Retrieves the red component of a pixel value.
SYNTAX final public int getRed(int pixelValue)
DESCRIPTION This method retrieves the red component of the pixel value pixelValue. The return value must be in the range 0 255, where 0 means no red and 255 means maximum red.
PARAMEI LRS pixelValue The pixel value specifying a color in the color model.
RETURNS The red color component in the range from 0-255.
EXAMPLE See the class example.
getRedsf)
PURPOSE Retrieves the red component of all of the colors in this index color model.
SYNTAX final public void getReds(byte[] r)
DESCRIPTION This method retrieves the red color component of all of the colors in this index color model and places the values in r. The number of values placed in r is determined by the color map size (see getMapSi ze() >. r can be larger than the color map size; the unused array elements are not modified.
PARAMETERS Г A non*nul 1 array that is at least as large as the color map size.
SEE ALS( J getMapSize().
EXAMPLE See the class example.
getRGB()
purpose Converts a pixel value to a pixel value in the default color model.
SYNTAX final public int getRGB(int pixelValue)
description The pixel value pixelValue is converted to an equivalent pixel value that must be interpreted using the default color model. The color of the new pixel value might not be identical to the color of pixelValue; there may be some loss of color information.
PAR A MUI ERS pi xelValue The pixel value specifying a color in the index color model.
IndexColorModel
java.au t. image
getTran sparent Pi хе I ( )
Rli’I l RNS A pixel value that specifies a color in the default color model.
OS ERR IDES ColorModel ,getRGB().
SLL .ALSO ColorModel.getRGBdefault().
EXAMPLE See the ColorModel class example.
getTransparentPixel()
Pt RPOSE Retrieves the index of the transparent pixel in this index color model.
SYNTAX final public int getTransparentPixel()
RI П RNS l he index of the transparent pixel. A return value of-1 indicates that there no transparent pixel in the color model.
E-XAMPI E See the class example.
IndexColorModelf)
к --------------
L Pl RPOSE Constructs an IndexColorModel instance.
M N () P Q R SYNIAX public IndexColorModel(int nbits, int size, byteLJ reds, byte’] greens, bytef] blues) public IndexColorModel(int nbits, int size, bytef] reds, byteLJ greens, byte[] blues, int trans) public IndexColorModel(int nbits. int size, byte[] reds, bytell greens, byte[] blues, byte[] alphas) public IndexColorModel(int nbits, int size, byte[] стар, int start, boolean hasAlpha) public IndexColorModel(int nbits, int size, bytef] стар, int start, boolean hasAlpha, int trans)
s 1 U V w X Y Z DESCRIPTION l he forms of this constructor construct an IndexColorModel from a list of size colors, nbits specifies the number of bits needed to represent size col- ors. fhe number of colors can be smaller than the maximum value that nbits bits can represent. The list of colors can be specified in one of two ways: as four arras s or as a single array. In the case of four arrays, reds contains all of the reds, greens contains all of the greens, blues contains all of the blues, and alphas contains all of the alpha transparency values. The arrays must have at least size ele- ments. redsfi], greens [i]. bluesfi]. and al phas fi] would hold the com- ponents for the i th color.
If alphas is not specified, then all of the colors, except for the transparent
color, are considered opaque (i.e.. the value 2 55).
852
java.awi.image
inutAvniui muuri
IndexColorModel)
If trans is specified, it specifies which color should be treated as transparent, regardless of its alpha value. If trans is not specified or is -1. none of the col- ors will be treated as transparent. In the case of specifying the colors with a single array стар, the colors are encoded so that cmap[i*4+start] contains the red component for color i. стар[i*4+l+start] contains the green component for color i, cmap[i*4+2+start] contains the blue component for color 1. and стар[i*4+3+start] contains the alpha component for color i. However, if hasAlpha is false, стар is packed as follows: • стар [i * 3-hStart] contains the red component for color i. • стар [1 * B+l+start] contains the green component for color 1. • cmapfi *3+2-bStart] contains the blue component for color i.
PARAMETERS alphas blues стар greens hasAlpha The non-null array containing the alpha component of all of the colors. The non-null array containing the blue component of all of the colors. The non-null array of packed color components. The non-null array containing (he green component of all of the colors. If true, стар contains alpha values: otherwise, стар does not contain alpha values.
nbits reds size start trans The number of bits required to hold all of the components of a color. The non-null array containing the red component of all of the colors. The color map size. The starting offset of the first color component in стар. The index of the fully transparent color.
example: See the class example.
java.beans
IndexedPropertyDescriptor
A
R
('
D
Indexed Prop^rt yDeec: ipt oi
1 Syntax
h public class IndexedPropertyDescriptor extends PropertyDescriptor
(i
Description
An indexed property is a special kind of bean property whose type is an integer-indexed array
of values. An example of an indexed propertv could be a list ol recipient v mail addresses in a
j ‘’mail message bean.** In this case* the indexed property \ at rax' tvpe is an array of String ano
the indexed property's element type is a String. The indexed property's array type is always
K an indexed array of the property’s element type. (Note that the element type can itself be an
I. array.)
M An indexed property is the same as any other bean property except for iwo diffciuncev
1. The property type is an array.
2. In addition to the read and write accessor methods (the nonindexed accessoi methods}.
() which read and write an array, an indexed property prov ides two indexed accessor meth-
P ods. These methods read and write elements in the array. Indexed accessor methods take
an extra parameter—the integer index of the desired array element. F;or example, it you
want to retrieve the fifth element of the indexed property, you would use the indexed icad
К accessor method lather than the nonindexed read method (which would give you the
s whole array).
I An indexed propertv descriptor contains information about an indexed property, such, as :ь
localized name and whether it is bound. There is one indexed propcity descriptor lor caui
indexed property. A bean's indexed property descriptors can be retrieved through the :turns
v pector by calling Introspector.getBeanlnfoO .getPropertyDescriptorsO Since
indexed property descriptors are subclasses of property descriptors (sec PropertyDescrip-
tor). you must use the instanceof operator to discover which property descriptors ate actu-
X ally indexed property descriptors.
Y
For Fean Editors Only
The information contained in an indexed property descriptoi is meant for programs such as
bean editors (programs that help conned together beans into an application) and is not used by
the bean itself. These and other descriptors essentially help a bean editor to construct а гнели
854
java, beans
inaexearroperiyL/rscripii
ingful user interface for editing the bean. When the bean is actually running in an application,
the indexed property descriptors are never used.
Implicit and Explicit Indexed Property Descriptors
The introspector first looks for explicit indexed property descriptors in the bean’s bean-info, if
present (see Beaninfo). If explicit indexed property descriptors are not found, the introspector
creates implicit indexed property descriptors with some default values for each indexed prop-
erty attribute. Table 15 shows the attributes of an indexed property descriptor and what they
contain. Also shown are the default values for implicit indexed property descriptors.
Attribute Contents Implicit Default Value
Bound true if the property is false? bound.
Constrained t rue if the property is con- false? strained.
Property type The Class object of the The Cl ass object of die prop- property’s array type. erty's array type.
Indexed property type Read method The Cl ass object of the The C1 ass object of the prop- property’s element type. erty’s element type. The Method object of lhe The Method object of the prop- property \ read accessor erty’s read accessor method, method.
Write method The Method object of the The Method object of the prop pr<)pcrty's wri te accessor ertу ‘s wri tc acce ssor method. method.
Indexed read method 'T he Method object of the The Method object of the prop- property’s indexed read erty's indexed read accessor accessor method. method.
Indexed write method The Method object of the The Method object of the prop- property 's indexed write erty's indexed write accessor accessor method. method.
Property editor class The Cl ass object of the null, property's property editor.
Name The property’s nonlocalized The property's nonlocalized name. name.
Display name The property's localized The property's nonlocalized name. name. Continued
TABLE IS: Indexed Property Descriptor Attributes.
Indexed Property Descriptor
java.beans
Attribute Contents Implicit Default Value _
Short description A localized description of the The property's non localized
property. name.
Expert true if the property is con- sidered for use by experts only. fal se.
Hidden true if the property is meant to be used by a took fal se if meant to be used by a person. fal se.
TABLE 15: Indexed Property Descriptor Attributes.
a. If the introspevior d ixiners that the bean tires the pioperiv change event (see PropertyChangeLven th
then the bound attribute foi all bean properties (indexed and nomndtxtxli w ill he true.
b. It the mtrospeciot discuxeis that the property s indexed or non indexed write accessor methods throws
PropertyVetoExcept ion (see PropertyVetoExceptionk then the constrained attribute tor the
propertv w ill be t rue
Accessor Method Signature Conventions
The bean specification defines conventions for the signature of property accessor methods.
These conventions serve two purposes:
1. They make the bean’s API easier for a programmer to read. That is, it's easy to see which
methods are accessor methods and which are not.
2. They make it possible for the introspector to discover a bean's properties and create
implicit property descriptors. In other words, the introspector looks at the entire list of a
bean's public methods. When a method is found that matches the accessor method signa-
ture convention, the introspector assumes that it must be an accessor method. From the
signature of the accessor method, it can deduce the name and type of the property.
For the conventions for the nonindexed accessor method signature, see PropertyDe-
scriptor. The following describes the method signature conventions for an indexed prop-
erty's indexed accessor methods.
If the name of an indexed property is PropertyName and its element type is Property-
Type, the convention of an indexed read accessor method signature is
public PropertyType getCapPropertyName(int index)
where CapPropertyName is the property name with the first character capitalized and index
is the 0-based index of the desired array element. 7he convention of a w rite accessor method
signature is
public void setCapPropertyNameQint index, PropertyType value)
856
java.beans
indexed rropenyuescnpu
[f PropertyType is boolean» then the read method can be replaced or complemented by a
read accessor with the signature
public boolean isCapPropertyNamef.int index)
For example, if the property name is “roasted" and the property type is boolean, then the set
of accessor methods are
public boolean isRoasted(int index)
public boolean getRoasted(int index)
public void setRoasted(int index, boolean r)
When the read method is not explicitly specified and both “is" and “get" methods are
available, the “is" read method is used. If only a read accessor method is found, the property is
assumed to be read-only. If only a write accessor method is found, the property is assumed to
be write-only.
[jMhfBER SUMMARY
Constructor
IndexedPropertyDescri ptor() Constructs an IndexedPropertyDescri ptor instance.
Property Type Method
getlndexedPropertyTypeC) Retrieves the property's element type.
Indexed Property Accessor Methods
getlndexedReadMethodO Retrieves the property ’s indexed read accessor method.
getlndexedWriteMethodO Retrieves the property's indexed write accessor method.
See Also
PropertyDescri ptor.
Example
This example implements a bean that has a string indexed property called “names." A property
editor called NamesEdi tor is created to support the editing of this property. This property also
requires the use of a custom editor called NamesCustomEdi tor.
The custom editor displays the list of names. It allows the user to change the list by adding
or removing items. The custom editor does not update the property editor’s value immediately.
Instead, it keeps the changes to itself until the user hits the Save button, at which point it will
update the property editor’s value (which will then update the bean property; see Property-
Editor for more details). See Figure 216.
Indexed Property Descriptor
ja\a.beans
fh e® View неф
names
3 rtatms
hHmril dil o«
*
1 КД RE 216: Indexed Property Editor.
A bean-info is neccssarx to associate NamesEdi tor w ith the bean's “names" properly I
bean-info must be defined in a class with the bean's name appended with “Beaninfo." w li
in this case, is BeanBeanlnfo.
Bean.java
import java.awt.-';
import java. beans . ;
public class Bean extends Panel {
String[] names = {"Joe", "Pat", "Tim", "Ann", "Sue"};
// Use a list to display the current names.
Li st 1 = new Li st (5) ;
public Bean() {
// Initialize the list.
for (int i=0; icnames.1ength; i++) {
1.add(names Li]);
}
add(1);
}
// This method must not return null, otherwise the bean editor
// may not create a property editor for this property.
public StringL] getNamesO {
return names;
}
public String getNames(int index) {
retu rn names Гindexl;
}
public void setNames(String El names) {
this.names = names;
858
java.oeans
UiUt^VUI Jupvil
// Update the list.
1.removeAl1 О:
for (int i-0; i<names.1ength; i*+) {
1.add(namesLiJ);
}
public void setNames(int index, String name) {
names[index] - name;
setNames(names);
}
}
/*
mani fest.txt:
Name: Bean.class
Java-Bean: True
jar command:
jar cfm bean.jar manifest.txt Bean'.class Ip*.class
*/
BeanBeanlnfo.java
import java.beans.*;
public class BeanBeanlnfo extends SimpleBeaninfo {
public PropertyDescriptorJ getPropertyDescriptorsO {
PropertyDescriptor pd[] - new PropertyDescriptor [1];
try {
pd[0] = new TndexedPropertyDescriptor("names", Bean.class);
pd[02.setPropsrtyEdi torClass(NamesEdi tor.class);
return pd;
} catch (Exception e) {
e.printStacklraceO;
return nul1;
}
}
}
NamesEditor.java:
import java.awt.*;
import java, beans :
import java.util.*;
public class NamesFditor extends PropertyEditorSupport {
// Paint area methods.
public boolean isPaintableO {
return true;
}
public void paintValue(Graphics g, Rectangle box) {
Stringf] names = (String[])getValue();
FontMetrics fm = g.qetFontMetrics();
String message - + names, length + ” names’1:
// There’s a bug in the bean box where box width and height
// are too big by 4 pixels.
box.width -=. 4;
box.height -- 4;
I nd exed Property Descriptor
java.beans
g.setColor(Color.black);
g. drawString(message, (box.width-fm.stringWidth(message))/-
(box.height-fm,getHeight())/2 + fm.getAscent());
g.drawRect(box.x, box.y, box.width-1, box.height-1);
Л // Custom editor methods,
public boolean supportsCustomEditor() {
В return true;
}
C public java.awt.Component getCustomEditor() {
return new NamesCustomEditor(this, (String[])getValue()) ;
D }
}
E
NamesCustomEditor.java
g import java.awt.1*;
import java.awt.event.*;
]_[ import java.beans.*;
public class NamesCustomEditor extends Panel implements ActionListi
PropertyEditor pe;
j List list - new List(10);
TextField textField » new TextFi eld(5);
К
public NamesCustomEditor(PropertyEditor pe, StringH names) {
L Button saveBtn = new Button("Save”);
Button removeBtn = new Button("Remove”);
M Button addBtn = new Button(“Add”);
\ this.pe = pe;
0 // Initialize list.
for (int i=0; i<names.1ength; i++) {
p list.add(names[i]);
// Layout the components.
r setLayout(new BorderLayoutO) ;
1ist.setSize(250, 150);
add(list, BorderLayout.CENTER);
Panel p - new Panel();
T p.add(saveBtn);
p.add(removeBtn);
U p.add(addBtn);
p.add(textField);
V add(p, BorderLayout.SOUTH);
W // Listen for events
textFi eld.addActionLi stener(thi s);
X saveBtn.addActionListener(this);
removeBtn.addActionListener(this);
Y addBtn.addActionLi stener(thi s);
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommandO.equals(“Remove”)) {
int sei - list.getSelectedlndexO;
860
JO V U.UVUII')
getlndexedPropertyTypei
if (sei >- 0) {
list.remove(sel);
}
} else if (evt .getActi onCommandQ . equal s(“Save”) ) {
// Save the changes.
String[] names = new String[1 ist.getltemCountO];
for (int i^0; i<names.length; i++) {
names[i] = 1ist.getltem(i);
}
pe.setValue(names);
} else if (evt.getActionCommandQ .equals(“Add”)
| I evt .getSourceQ == textField) {
list.add(textField.getText());
}
}
}
getlndexedPropertyTy pe()
PURPOSE Retrieves the property's element type.
SYNTAX public Class getlndexedPropertyTypeQ
DESCRIPTION The indexed property’s element type is represented by a Class object of that type. For example, if the type is a String or an int, then this method returns java. lang. St ring, cl ass or int. cl ass, respectively. The property’s type is determined in the constructor. See the IndexedPropertyDescri ptor О constructor for more details on how this is done. If the property has nonindexed accessor methods, the indexed property’s array type can be retrieved by calling PropertyDescriptor.getProperty- TypeQ.
RETURNS The non-nul 1 Cl ass object of the indexed property's type.
SEE ALSO PropertyDescri ptor .getPropertyTypeQ.
EXAMPLE See getlndexedReadMethodO.
getlndexedReadMethodf)
PURPOSE Retrieves the property’s indexed read accessor method.
SYNTAX public Method getlndexedReadMethodQ
DESCRIPTION I'he property’s indexed read accessor method is used to read one element from the indexed property's array of values. It is typically called by the bean editor
I ndexed Prope rt у Desc r ipt or
get I ndexed Read Meihodf)
ju\ a. beans
as the user edits the property value through a property editor (see Property-
Editor). The indexed read accessor method takes the index as its argument
and returns an object of the same type as that returned b\ qetlndexed-
PropertyType().
The property's indexed read accessor method is determined b\ the constructor.
The method may have been specified in a bean-info or di seme red through
introspection. See the constructor for more details.
If the property does not have a public indexed read accessor method, this
method returns null.
Rt и rns I’hc possibly-nul 1 indexed read accessor method.
st-'F At.so java.lang.reflect.Method, get!ndexedPropertyType() .
getlndexedWri teMethodQ , PropertyDescri ptor.
exampli This example demonstrates how to invoke the accessor methods on a property
The program loads a bean and its bean-info, if present, and then instantiates the
bean. It then looks for string-based indexed properties. When if finds one. it
does all of the following:
• Uses the read accessor method to retriexe lhe array
• Sorts the array
• Uses the write accessor method to write the sorted timiy
• Uses the indexed read accessor method lo retrieve each arra\ clement.
• Uses the indexed write accessor method to write the sorted elements hack
w ards.
This example uses the FileClassloader class to load the hean from a file.
The source code for Fi1 eCiassloader is in the Introspector class exam-
pie.
Ma in. java
import java.awt.-;
import java.beans;
import java, io/-;
import java.1ang.reflect;
import java.util.*;
import java.net. ';
class Main {
public static void mai n(St ri ng [] args) {
if (args.length !- 1) {
System.err.printlnC’lsage: java Main cname of bean class files"):
System.exit(l);
}
try {
// load the bean and get the bean-info.
// (See the Introspector class example for I-i 1 eClassi oader
// source code.)
Class beanClass - FileClassLoader.load(args[0]);
Beaninfo beaninfo = Introspector.getBeanTnfo(beanC1 ass);
862
java.beans
indexed rropeny uesc nptor
getlndexedReadMethod()
// Instantiate the bean.
Object bean = beanClass.newlnstance();
// Now print the indexed properties and their values.
PropertyDescriptor pds[] = beaninfo.getPropertyDescriptors();
for (int i=0; i<pds.length; i++) {
if (pds[i] instanceof IndexedPropertyDescriptor) {
IndexedPropertyDescriptor ipd =
(IndexedPropertyDescri ptor)pds[i];
int arrayLength = 0;
// Get the accessor method objects.
Method reader = ipd.getReadMethod();
Method indexedReader « ipd.getlndexedReadMethodO;
Method writer = ipd.getWriteMethodQ;
Method indexedWri ter = i pd .getIndexedWriteMethodO ;
// If any of the accessor methods are missing,
// just skip the property.
if (reader -= null || indexedReader == null
II writer == null || indexedWriter == null
Il ipd.getlndexedPropertyTypeO != String.с 1 ass) {
/*
An alternative test is:
ipd.getPropertyTypeO != StringLJ .class
V
continue;
}
// Print the name of the property
System.out . println(ipd.getNameO);
// 1) Read and print the array.
// Invoke the read accessor method and print the
// contents of the array.
ObjectQ readerArgs = {};
Object array = reader.invoke(bean, readerArgs);
arrayLength Array.getLength(array);
System.out .printC non-indexed reader: ") ;
for (int j=0; j<arrayLength; j++) {
Object element - Array.get(array, j);
System.out.print(element.toStringO + " ");
}
System.out.pri ntln();
// 2) Sort the array.
array = sort((String[])array);
// 3) Write the array.
// Invoke the write accessor method on the sorted array.
Object[j writerArgs = {array};
wri ter.invoke(bean, wri terArgs);
// 4) Read and print the array elements.
// Invoke the indexed read accessor method and print the
// contents of the array.
System.out. printC indexed reader: ");
Ind exed Props rty Desc ri ptor
getlndexedReadMethodO
java.beans
Л
В
C
D
E
E
H
J
К
L
M
N
О
P
Q
R
S
T
L
V
W
X
Y
Z
for (int j=0; j<arrayLength; j*+) {
Object[j indexedReaderArqs = {new Integer(j)};
Object element -
indexedReader.invoke(bean, indexedReaderArqs);
System .out. pri nt (element - toStringO + " ”);
}
System.out.pri ntln();
// 5) Write the array elements backwards
// Invoke the indexed write accessor method and print the
// contents of the array.
array - (Stri ng[J) ((Stri ng [J )array) . cloneQ ;
for (int j=0; j<arrayLength; j++) {
Object[] indexedWriterArgs -
{new Integer(arrayLength-j-1),
Array.get(array, j)};
indexedWriter.invoke(bean, indexedWriterArgs);
}
// 6) Read and print the array again,
array ~ reader.invoke(bean♦ readerArgs);
arrayLength - Array.getLength(array);
System.out.print(" non-indexed reader: '*);
for (int j=0; j<arrayLength; j*-+) {
Object element - Array.get(array, j);
System.out.print(element*toStringO ♦ ”
}
System.out.pri ntln():
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e. printStackTraceO;
} catch (InvocationTargetException e) {
e. pri ntStackTraceO ;
} catch (InstantiationException e) {
e.printStackTrace();
}
System.exi t(0);
}
// Prints s and pads the string with Math.maxO, width-s. Iength()) spaces,
static void print(String s, int width) {
System.out.pri nt(s);
for (int i=0; i<Math.max(l, (width-s.lengthO)); i++) {
System.out.pri nt(” ”);
}
}
// Returns a sorted copy of the string array.
// Uses a simple bubble sort algorithm.
static Stringf] sort(String[] a) {
a = (String[])a.clone();
for (int i=a.length-1; i>=0; i- ) {
864
ja v<j.uuuii>
getlndexedWriteMelhod()
for (int j-0; j<i; j++) {
if (aCj].compareTo(a[j+1]) > 0) {
String s = a[jl;
a[j] = a[j*l] ;
a[j+l] = s;
}
return a;
Output Here is lhe output of the program when it is run on the bean developed in the
class example.
names non-indexed reader: Joe Pat Tim Ann Sue
indexed reader: Ann Joe Pat Sue Tim
non-indexed reader: Tim Sue Pat Joe Ann
getlndexed WriteMethod()
PURPOSE Retrieves lhe property's indexed write accessor method.
SYNTAX public Method getlndexedWriteMethodO
DESCRIPTION The indexed write accessor method is used to modify one element of the indexed property's array of values, It is typically called by the bean editor as lhe user edits lhe properly value through a property editor (see Property- Editor). The indexed write accessor method takes two arguments and does not return any value. The first argument is an integer index, and the second argument lhe actual value. The value must be of the same type as returned by getlndexedPropertyTypeQ. The property's indexed write accessor method is determined by the construc- tor. T he method may have been specified in a bean-info or discovered through introspection. See the constructor for more details. If the property does not have a public indexed write accessor method, this method returns null.
returns The possibly nul 1 write accessor method.
SEE ALSO java.lang.reflect.Method, getlndexedPropertyTypef), getlndexedReadMethodQ , PropertyDescriptor.
example See getlndexedReadMethodQ-
IndexedPropertyDescriptor
I n d e xed Propen у De sc r i p to r()
java, beans
IndexedPropertyDescriptor()
pi-RPOSL C onstructs an IndexedPropertyDescri ptor instance.
SYNTAX
DL-SCRirriON
public IndexedPropertyDescriptor(String propertyName, Class
beanClass) throws IntrospectionException
public IndexedPropertyDescriptorfString propertyName, Class
beanClass, String readerName, String writerName, String
indexedReaderName, String indexedWriterName) throws
IntrospectionException
public IndexedPropertyDescriptor(String propertyName, Method
reader, Method writer, Method indexedReader, Method
indexedWriter) throws Introspectiontxception
Indexed properly descriptors are either implicitly created by the introspector or
are explicitly created by a bean. See the class description for more information.
When an indexed property descriptor is created, eight attributes are initialized:
• Propertv name
• Class object of the bean
• Read accessor method
• Write accessor method
• I n de x c d re ad a cc e s so r n let h od
* Indexed write accessor method
• I n d e x ed p горе и у a rra у t у pe
* Indexed property element type
All other attributes are given default values that cun be changed by methods in
this class—the PropertyDescri ptor class—and in lhe FeatureDescriptor
class. The default values for an indexed property descriptor arc shown in Table
15.
Q l he indexed propertv element type is not specified. Rather, it is determined
K using reflection to examine the indexed read and write methods. Basicallv. the
tvpe returned by the indexed read method becomes the indexed property tvpe.
See the PropertyDescriptor() constructor for information regarding the
1 readerName, wri terName. reader, and wri ter parameters.
h If indexedReader and indexedWriter are specified, a check is made to
v ensure that the methods have the appropriate signatures, l he signatures are
discussed in the class description.
W
If indexedReaderName and indexedWriterName are specified, reflection is
x used to look for methods with these names. (Although they don’t have to use
Y the “is/get/set" naming conventions, it is still highly recommended that they
do.) l he method can be in either the bean or in one of its ancestors. Once these
methods are found, they are subject to the signature compatibility check as dis-
cussed in the class description.
2 -
866
uiuexeurroperiyistsL'ripiur
Index edProperty Descriptor!)
juvit.neans
If rhe accessor methods arc not specified, they are discovered using reflection
and the following rules;
• The first letter of the proper!} name is capitalized, for example, ’'roasted'*
becomes “Roasted." Roasted" is referred to as the capitalized property
name CapProper tyName.
• Reflection is used to look fora method named set CapProp er tyName that
has the appropriate signature. The method can be in either the bean class or
one of its ancestors. 11 one is found, this becomes the indexed write method
and the second parameter becomes the property element type: otherwise.
IntrospectionException is thrown.
• If the property type is boolean, reflection is used to look fora method
named i sCapPropertyName that has the appropriate signature. The
method can be in either the bean class or one of its ancestors. If one is found,
this becomes the indexed read method.
• Otherwise, reflection is used to look for a method named getCapProper
tyName that has the appropriate signature. The method can be in either the
bean class or in one of its ancestors. If one is found, this becomes the
indexed read method; otherwise. IntrospectionException is thrown.
PARAMBIERS
beanCl ass The bean's Cl ass object.
reader The possibly null Method object of the property's read accessor method,
reader Name The possibly null name of the property's read accessor method.
indexedReaderThe method used for reading an indexed property value.
i ndexedReaderName
The name of the method used for reading
indexedWriterThe method used for writing an indexed property value.
i ndexedWri terName
The name of the method used for writing.
propertyNameThe non-null nonlocalized name of the property.
writer The possibly null Method object of the property's write accessor method,
wri terName The possibly null name of the property's write accessor method.
exceptions
IntrospectionException
If the signatures of the read and write methods are incompatible. For example,
the type returned by reader does not match that accepted by wri ter.
SEE also java.1ang.reflect.vethod, java.lang.Class.
example This example simply demonstrates how to use the three different forms of the
constructor. The bean has three indexed float properties: property!,
property?, and property3. The bean info class. BeanBeanlnfo. creates
three property descriptors, one for each of the three properties, using the three
different constructors.
Indexed Property Descriptor
I ndexed Property De sc ripior()
java, beans
Beanjava
public class Bean {
int propertyl;
int property?;
int property^;
public int getPropertylO {
return propertyl;
}
public void setPropertyl(int v) {
propertyl - v;
}
public int getProperty2() {
return property?;
}
public void setProperty2(int v) {
property? - v;
}
public int getProperty3() {
return property};
public void setProperty3(int v) {
property} = v;
}
}
/*
manifest.txt:
Name: Bean.cl ass
Java-Bean: True
jar command:
jar cfm bean, jar manifest.txt '-.class
*/
BeanBeanlnfojava
import java.beans;
import java.1ang.reflect.*;
public class BeanBeanlnfo extends SimpleBeaninfo {
public PropertyDescriptorLJ getPropertyDescriptorsO {
IndexedPropertyDescriptor pd[] = new IndexedPropertyDescriptor[3];
try {
// lhe getter and setter methods are derived from the property name.
pd[0] = new IndexedPropertyDescriptorCpropertyi", Bean.class);
// The names of the getter and setter methods are supplied.
pd[l] = new IndexedPropertyDescriptor(”property2", Bean.class,
"getProperty?", ”setProperty2”, "getProperty?”, MsetProperty2");
// The Method objects of the getter and setter methods are supplied.
// The getter method must not take any parameters.
Class[] getArgs = {};
Method getter = Bean.class.getMethod("getProperty3", getArgs);
// (he indexedGetter method takes one integer parameter.
Class[] igetArgs = {Integer.TYPE};
868
ja vu. ucans
HlUtAtUri U|MU IJ lyVALl 1|JIU
I rule xedProperty Descri ptor(
Method indexedGetter =
Bean.class. getMethodC’get Property}", igetArgs);
// The setter must take one parameter and it must have the
// same type as returned by the getter method.
Class[] setArgs - {getter .getReturnTypeO};
Method setter = Bean.class.getMethod(”setProperty3", setArgs);
// The indexedSetter must take two parameters - an integer and
// an object of the same type as returned by the
// indexed getter method.
Class[] isetArgs - {Integer.TYPE, indexedGetter.getReturnTypeO};
Method indexedSetter =
Bean.class.getMethodC'setProperty}", isetArgs);
pd[2] - new IndexedPropertyDescriptor ('’property}”, getter, setter,
indexedGetter, indexedSetter);
return pd;
} catch (NoSuchMethodException e) {
e.printStackTraceO ;
} catch (IntrospectionException e) {
e.printStackTraceO;
}
return nul 1;
}
}
Output
Class: Bean
Name: Bean
Display name: Bean
Short Description: Bean
Expert: false
Hidden: false
h:hidden, e:expert, i:indexed, *:default, c:const rained, b:bound
PROPERTIES
Attr Name Type Accessor methods
i property} [F float getProperty3/setProperty} getPropertу3/setProperty}
i property? [F float getProperty2/setProperty2 getProperty2/setProperty2
ib propertyl IF float EVENT SETS getPropertyl/setPropertyl getPropertyl/setPropertyl
Attr Name Callback Registration methods methods
METHODS
Attr Signature
IndexedPropertyDescriptor
IndexedProperty Descriptor!)
java.beans
public float[] Bean.getPropertyBO
public float □ Bean.getProperty?О
public float[] Bean.getPropertylO
public float Bean.getPropertyS(int)
public float Bean.getProperty2(int)
public float Bean.getPropertylOnt)
public final void java.lang.Object.wait(long,int)
throws java.lang.InterruptedException
public final native void java.1ang.Object•notifyAl1()
public void Bean.setProperty2(float[])
public final void java.lang.Object.wait()
throws java.1ang.InterruptedException
public java.1ang.String java.lang.Object.toString()
public final native void java.1ang.Object.notify()
public void Bean.setProperty3(float[])
public void Bean.setPropertyl(float[J)
public native int java.lang.Object.hashCodeO
public final native java.lang.Class java.lang.Object.getC
public final native void java.1ang.Object.wait(long)
throws java.lang.InterruptedException
public boolean java.1ang.Object.equals(java.lang.Object)
public void Bean.setProperty3(int,float)
public void Bean.setProperty2(int,float)
public void Bean.setPropertyl(inttfloat)
870
java.awt.even!
InputEvent
Syntax
public abstract class InputEvent extends ComponentEvent
Description
Input events are typically fired by a component while the user uses the keyboard and mouse to
interact with the component (see KeyEvent and MouseEvent). Input events contain a time-
stamp of when the input event occurred and the set of modifier keys pressed at the time the
input event was fired. For more general information about events, see AWTEvent.
Listening for Input Events
To listen for either key or mouse input events, see KeyEvent and MouseEvent.
Consuming Input Events
The delivery flow of input events differs from other events. Events such as component events
are fired by a component after the operation is completed. For example, when a
COMPONENT_RESIZED component event is delivered to a listener, the component has already
been resized. Input events are delivered to the component and its listeners before it is pro-
cessed by the component peer. This allows the component and its listeners to modify or con-
sume (i.e., discard) the event before it is processed by the peer. An example of where this could
be used is by a text field that accepts only numbers. Here, when the text field receives a key
event that is not a number, it could emit a beep and then consume the event. The consumed key
events would not appear in the text field. Note that all listeners are notified of the event,
InputEvent
java.aw Levent
regardless of whether the event has been consumed. Consuming an event affects only whether
the peer gels to process the event.
When an input event is consumed, it cannot be “unconsumed."
A
В
C
Г)
E
F
Modifier Keys
An input event contains the state
of the modifier keys at the time
the input event was fired. The
modifier key state is represented
by a bit vector, where each bit
position represents the state of one
modifier key. The state of particu-
lar modifier ke\ can be retrieved
by using the mask for that modi
tier key (for example.
SHIFT_MASK).
If the input event is a mouse
event, the identity of the mouse
button is encoded in the modifier
key stale. Sec the MouseEvent
class description for more details.
Timestamp
An input event has a timestamp
that indicates when the input
ComponentPeer I InputFvent
System
FIGI RE 217: Input Ел ent Flow,
event was created. The timestamp
is in UTC formal. See Date for more details.
input Event Flow
As discussed in the previous “Consuming Input Events** section, input events differ from non-
input events in that the event is not processed by a component peer until after it has been pro-
cessed by the component and all of its listeners. Sec Figure 217. See the “Event Flow" sections
for KeyEvent and MouseEvent for more details about input event flow.
v Simulating input Events
W Input events are normally created by the AWT system when the user interacts with a compo-
nent. However, it is possible for any object to create input events in the same way. For exam-
ple, a program designed to test a dialog box can create various key and mouse events and
Y deliver them to the dialog box. The dialog box will treat the key and mouse events exactly as if
У it came from the user via the AWT system.
872
java.awt.event
1 при its v
A simulated input event can be delivered to a component in one of two ways. Either by
posting the event to the event queue (see E-ventQueue) or by calling the component’s dis-
patchEventO method directly.
SUMMARY
Consume Methods consume() isConsumedO Consumes this input event. Retrieves the consumed state of the event.
Time Method getWhenO Retrieves the input event's timestamp.
Modifier Masks ALT_MASK BUTTON1.MASK BUTT0N2_MASK BUTTON3_MASK CTRL-MASK META_MASK SHIFT-MASK Used to determine the stale of the Alt key. | Used to determine whether button 1 was pressed. j Used to determine whether button? was pressed. f Used to determine whether button? was pressed Used to determine the state of the Control key. Used to determine lhe state of the Meta key. Used to determine the state of the Shift key.
Modifier Methods getModifiers() isAltDownO isControlDown() i sMetaDownQ isShiftDownO Retrieves the state of the input event's modifier keys. Determines the state of the Alt key for this event. Determines the state of lhe Control key for this event. Determines lhe slate of the Meta key for this event. Determines the state of the Shift key for this event.
See Also
java.util.Date, KeyEvent, MouseEvent.
Example
This example demonstrates how input events can be con-
sumed. A text field is created that accepts only five digits.
Nondigit characters are consumed and so never appear in
the text field. Also, if a digit character is received and lhe
text field is full, lhe key event is consumed.
Notice that nonprintable nondigit ASCII characters are
< InputEvent Ex._ Jp7'
ZipCode: | 902 io|
I IGI RE 218: Zip Code.
not consumed so that keys such as KeyEvent.LEFT and
KeyEvent.BACK_SPACE can continue to work. See F igure 218.
import java.awt.*;
InputEvent
AI.T_MASK
jax a.awt.event
A
В
C
D
E
E
G
H
J
К
L
M
X
О
P
import java.awt.event;
class vain extends Frame {
Main() {
super(“InputLvent Example”);
TextField tf - new TextField(5);
// Listen for text events.
tf.addKeyListener(new KeyEventHandler()):
tf.setFont(new Font(“Serif”, Font.PLAIN, 14));
add(new Label(“ZipCode: Label.RIGHT), Border!ayout.WEST):
add(tf, Borderl ayout. CENTER) :
packO :
show() ;
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
char c - evt.getKeyChar();
if (c >' 0x20 && c <- 0x7F M !Character.isDigit(c)) {
/7 Only non digit printable characters are consumed,
evt. consumeO;
} else if (Character.isDigit(c)
&& ((Textcomponent)evt - get Component ()) .getTextO . 1 ength ()
>= 5) {
// lext field must not have more than 5 digits,
evt. consumeO ;
}
}
}
public static void rrain(String argsl]) {
new Vai n() ;
}
}
Q
R
e ALT.MASK
T и Pl'RPOSE SYNTAX Modifier mask used to determine the stale of lhe Ah key. public static final int ALT MASK
V DESCRIPTION This mask (value 8) should be bitwise and'd with the results of getModifi-
w ers() to determine lhe state of the Alt key at lhe time the input event was cre- ated. If lhe result is 0. lhe Alt key was not pressed; otherwise, the key was
X pressed.
Y Note that for mouse events, when the Alt key is pressed, the event is assumed
Z to be button? mouse event.
SEE Al SO CTRL _MASK, getModifiers(), isAltDownO, META-MASK, SHTFT_VASK.
EXAMPLE
874
java.uwLeveni
Bl’TTONl MASK
boolean isAltDo^n(InputFvent evt) {
return (evt.getModifiers() & Input tvent.ALT_MASK) !- 0;
}
BUTTON 1_MASK _
purpose Modifier mask used io determine whether button 1 was pressed.
SYNTAX public static final int BUTTONl.MASK
description This mask (value 16) should be bitwise and'd with the results of getModifi-
ers() to determine whether button 1 on the mouse was pressed. There are a
number of complications to be handled when determining which mouse button
was pressed; see the MouseEvent class description for details.
SEEALSO В1Л rON2_v.ASK, BUTTON3.MASK, getModifiersO.
example: For another example, see the MouseEvent class example.
boolean isButtonlDown(InputEvent evt) {
return (evt.getModifiers() & InputEvent.BUTTON1 MASK) 0;
}
BUTTON2MASK
purpose- Modifier mask used to determine whether button? was pressed.
SYNTAX public static final int BUTT0N2-MASK
description This mask (value 8) should be bitwise and'd with the results of getModifi-
ersO to determine whether the button? on the mouse was pressed. There are
a number of complications to be handled when determining which mouse but
ton was pressed; see the MouseEvent class description for details.
SEEALSO BUTTON1_MASK, BUTTON3_MASK, getModifiersO.
example For another example, see the MouseFvent class example.
boolean isButton2Down(InputEvent evt) {
return (evt.getModifiers() & Inputtvent.BlTT0N2_MASK) !- 0;
}
BUTTON3 MASK
purpose Modifier mask used to determine whether button3 was pressed.
Syntax public static final int BUIT0N3_MASK
InputEvent
consumeO
java.awt.event
л
El
C
D
E
F
J
К
L
M
N
О
P
<J
R
S
1'
u
V
w
X
Y
Z
description This mask (value 4) should be bitwise and'd with lhe results of getModifi-
ers() to determine whether the button? on the mouse was pressed. There are a
number of complications to be handled when determining which mouse button
was pressed; see lhe MouseEvent class description for details.
SEI-Al SO BUTTON1_MASK, BUTT0N2_MASK, getModi fiers().
exampiFor another example, see the MouseEvent class example.
boolean isButton3Down(InputEvent evt) {
return (evt.getModifiers() & Inputt vent.BUTT0N3_MASK) !- 0;
}
H
consumeO
purpose: Consumes this input event.
syntax public void consumeO
description Calling this method on this event prevents it from being processed by the peer
of the component that fired the event. Once consumed, an event cannot be
"unconsumed." See rhe class description for more information about consum-
ing events.
overrides java.awt. consumeO.
see: also i sConsumed()
example See the class example.
CTRL_MASK
purpose Modifier mask used to determine the state of the Control key.
Syniax public static final int CTRL-MASK
description This mask (value 2) should be bitwise and'd with the results of getModifi-
ersQ to determine the stale of the Control key at the time the input event was
created. If the result is 0, the Control key was not pressed; otherwise, lhe key
was pressed.
SEE ALSO ALT-MASK, getModifiersO , isControlDown(), META-MASK, SHIFT MASK.
EXAMPLE
boolean isCtrlDown(InputEzvent evt) {
return (evt .getModi fiersO & InputEvent.CTRL_MASK) !- 0;
}
876
Jciva.ilW(.event aiifJUiA^ * vn
get Modi fiers(
getModifiersO _______________________ __ _____________________
purpose Retrieves the state of the input event's modifier keys.
SYNTAX public int getModifiersO
description Stored with an input event is the state of the modifier keys at the time an input
event is fired. This method retrieves the state of all of the modifier keys as a hit
vector, where the state of each modifier key is represented by a particular bit in
the bit vector. To determine whether a modifier key was pressed, you must use
the appropriate modifier mask with the bit vector. See the various modifier
masks for examples.
returns A hit vector containing lhe state of the modifier keys.
SEEALSO AIT-MASK, BUTT0N1 MASK, BUTT0N2 MASK, BUTTONS,MASK, CTRL.MASK,
MLTA_MASK, SH1FT_MASK.
example See lhe class example.
getWhenf)
PURPOSE Retrieves the input event's timestamp.
SYNTAX public long gettthenO
DESCRIPTION The timestamp is a lime in LTC formal (see Date) that indicates when the input event was created.
RETURNS The lime when lhe event was created.
SEE ALSO java.uti1.Date.
EXAMPLE This example simply displays the lilUl event's timestamp as a date. The frame overrides processEventO lo catch all input events. It calls Wed Mar 26 13’38.53 PST1997 enableEventsO to enable mouse and keyboard events; otherwise. “ ,J the AWT system will not deliver nciREZW: InputEvent. getWhenO. the events to the frame. See Figure 219.
import java.awt.x;
import java.awt.event.;
import java.util.*:
class Main extends frame {
MainQ {
superC'getWhen Example");
setSize(100, 100);
InputEvent
isAltDownO
java.awt.event
showO;
// Enable mouse and keyboard events so processEventO will be called,
enabl eEvents (AWTEvent. MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASKIAWTEvent.KEY_EVENT_MASK);
}
String date =
protected void processEvent(AWTEvent evt) {
if (evt instanceof InputEvent) {
InputEvent ie = (InputEvent)evt;
date = °" + (new Date(ie.getWhenO));
repai nt();
super.processEvent(evt);
}
public void paint(Graphics g) {
Insets in = getlnsetsO;
FontMetrics fm = g.getFontMetrics();
g.drawString(date, (getSizeO.width-fm.stringWidth(date))/2,
i n.top+(getSi ze()hei ght-i n.top-i n.bottom-
fm.getHeight())/2+fm.getAscentO);
public static void main(String args[J) {
new Main();
}
}
isAltDownO
PURPOSE- Determines the state of the Alt key for this event.
SYNTAX public boolean isAltDownO
DESCRIPTION See the class description for more information about modifier keys and mouse buttons.
RETURNS true if the Alt key is down for this event; fal se otherwise.
SEE ALSO ALT_MASK, i sControlDownQ , isMetaDownO, i sShi ftDown().
EXAMPLE See the KeyEvent or MouseEvent class example.
is Consumed))
pi irpo.se Retrieves the consumed state of the event.
syntax public boolean isConsumed()
878
java.awt.event iupuib*wi isControlDown(
; DESCRIPTION L’nlike with other events, input events are delivered to a component and its lis- teners before they are processed by the peer. Any listener can prevent an input event from being processed by the peer by consuming the event. See the class description for more information about consuming events.
returns true if the event has been consumed; false otherwise.
OVERRIDES j ava.awt.AWTEvent.i sConsumed О •
SEE ALSO consume().
example See j ava,awt.AWTEvent.i sConsumed О.
isControlDownQ
PURPOSE Determines the state of the Control key for this event.
SYNTAX public boolean isControlDown()
DESCRIPTION See the class description for more information about modifier keys and mouse buttons.
RETURNS true if the Control key is down for this event; fal se otherwise.
SEE ALSO CTRL_MASK, IsAltDownO, isMetaDown()t i sShi ftDownO.
example: See the KeyEvent or MouseEvent class example.
IsMetaDownO
PURPOSE Determines the state of the Meta key for this event.
SYNTAX public boolean isMetaDownO
description See the class description for more information about modifier keys and mouse buttons.
returns true if the Meta key is down for this event; fal se otherwise.
SEE ALSO 1 sAltDownQ , isControlDownO , i sShi ftDownf) , META_MASK.
example See the KeyEvent or MouseEvent class example.
isShiftDown()
purpose Determines the state of the Shift key for this event.
SYNTAX public boolean isShi ftDownO
InputEvent
META MASK
java.awt.event
В
C
D
E
F
G
description See the class description for more information about modifier keys and mouse
buttons.
reii rns true if the Shift key is down for this event; fal se otherwise.
SEEALSO isAltDownO, i sCont rol Down О , isMetaDown(), SHIFT MASK.
example See the KeyEvent or MouseEvent class example.
.1
К
L
M
N
()
P
Q
R
S
T
u
V
w
X
Y
Z
META^MASK
pt rpose Modifier mask used to determine the slate of the Meta key.
swixx public static final int MFTA MASK
di scription This mask (value 4) should be bitwise and*d with the results of getModifi-
ersO to determine the state of the Meta key at the time the input event was
created. If the result is 0, the Meta key was not pressed: otherwise, the kev was
pressed.
Note that for mouse events, when the Meta key is pressed, the event is
assumed to be button^ mouse event.
SEEALSO AL1_MASK, CTRL_MASK, getModifiersO, isMetaDown(), SHIFT-MASK.
EXAMPLE
boolean isMetaDown(InputFvent evt) {
return (evt.getModifiersO & InputEvent.MFTA_MASK) 0;
}
SHIFT MASK ___________________ _______________________________
purpose Modifier mask used to determine the state of the Shift key.
syntax public static final int SHIFT-MASK
descripi ion getModifiersO to determine the state of the Shift key at the time the input
event was created. If the result is 0, the Shift key was not pressed; otherwise,
the kev was pressed.
SEEALSO AIT MASK, CTRL_MASK, getModifiersO, i sShi ftDownf) , MFTA .MASK.
EXAMPLE
boolean isShiftDown(InputEvent evt) {
return (evt.getModifiers() & InputEvent.SHIFT-MASK) !- 0;
}
880
java.awt
Insets
Syntax
public class Insets implements Cloneable, Serializable
Description
An inset has four inset values, each defining the amount to adjust the sides of a rectangle. The
four values are left, right, top, and bottom. The left value is added to the left edge of a rectan-
gle to yield a new location for the edge. The other values and other edges are handled simi-
larly.
Insets are typically used by layout managers in calculating the component positions. For
example, a container returns an inset, which is applied to the container's bounds to yield its
paintable area.
In general, when returning an insets instance in a method call, either return a copy, if you
need to retain the instance, or discard the instance after returning it. If you have an insets
instance passed in a method call and wish to continue using the instance, note whether lhe
method will retain the instance or copy the values.
MMBER summary
Constructor
Insetsf) Constructs a new Insets instance.
Fields
bottom Contains this inset's bottom value.
left Contains this in set's left value. ’
right Contains this inset's right value.
top Contains this inset's top value.
Object Override Methods
cloneO Creates a copy of the inset.
equals О Determines whether an object is equal to this inset.
toString() Generates the string representation of this inset.
Insets
ja\ a.aw l
See Also
Container.getlnsetsО , java.io.Serializable, java.1ang.Cloneable
Example
This example creates a frame that displays a black rect-
angle inside the frame's paintable area. See Figure 220.
The si/e and position of the rectangle depends on the
\ allies of an insets object. The \ allies of the object can be
increased b\ pressing the L (left). R (right). T (top», and/
or В (bottom) ke\s. If the Shift ke\ is held down while
one of the ke\ s is pressed, the affected inset is decreased
Each edge of lhe rectangle is labeled with a string that
names the inset at that edge.
There are actual!) two insets in\ol\ed in this exam-
ple: rectlnsets and frameinsets, rectlnsets deter-
mines the si/e and position of the rectangle inside the
1 IGl RI 220: l he Four Insets.
container. Howcter. since a frame is a container with an inset frameinsets (sec Con-
tai ner. getlnsetsO). the frame's inset also needs to be taken into account. In this case,
frameinsets is used to determine the si/e of the frame's paintablc area. Once this is done,
rectlnsets is then applied lo frameinsets, lherebx \ ielding lhe area in which lhe rectangle
is painted. This calculation would not be necessarx if lhe rectangle were painted msidc an
“inscl-less“ container, such as a canxas or a panel.
import java.awt.'-;
import java.awt.event.*;
class Main extends Frame {
Insets rectlnsets = new Insets(0, 0, 0, O') ;
Main() {
super("Insets Example");
setS i ze(l 50, 150);
addKeyLi stener(new KeyEventHandlerQ) ;
show() ;
}
public void paint(Graph)cs g) {
Insets frameinsets = getlnsetsO;
int x = frameinsets.1 eft, у framelnsets.top;
int w - getSize().width - frameinsets.right frameInsets.Iett;
int h = getSize().height - frame!nsets.bottom-framelnsets.top;
FontMetrics fm = g.getFontMetrics();
g . f i 11Rect(x + rectlnsets.left, y+r ec 11nset s.t op,
w rectInsets.right - rectInsets.1 eft.
h - rectlnsets.bottom - rectinsets.top);
g.setColor(Color.whi te);
// top
g.drawString("top", x + rectInsets.1ett
882
ja\ a.au i
Insets
+ (w-roctInsets. 1 eft-rectInsets. right - fm, stringVi/idth(“top") )/2,
у t rect Insets. top+fm.getAscentO);
// left
g.drawString(“left", x- rectlnsets.left.
у»rectlnsets.top ♦
(h-rectlnsets.top-rectlnsets.bottom-fm,getHeightО)/2);
// bottom
g.drawSt ri ng(“bottom", x+rectlnsets.1 eft
* (w-rectlnsets.left rectInsets.right
f m.stri ngwidth(“bottom"))/2,
y-t-h rectlnsets. bottom- fm .getDescent ());
// right
g.drawSt ri ng ("right ” , x+w-rectInsets. right - f ri. stri nqVvi dth (“right") .
y-rectlnsets.top +
(h-rectlnsets.top rectInsets.bottom fm.getHeight())/2);
class KeyEventHandler extends KeyAdapter {
public void keyTyped(Keytvent evt) {
char key = evt.getKeyCharO;
key - Character.tolowerCase(key);
switch (key) {
case ‘t1:
if (evt. i sShif tDownO) {
if (rectInsets.top > 0) {
rectlnsets.top--:
}
} else {
rectlnset s.topi♦;
break;
case ‘b’:
if (evt.isShiftDownO) {
if (rectlnsets.bottom > 0) {
rectInsets.bottom ;
rectlnset s.bottom+*:
}
break;
case ‘1’:
if (evt . isShi ftDownO) {
if (rectInsets.left > 0) {
rectlnsets.1 eft--;
}
} else {
rectlnsets.1 eft* 4;
}
break;
case ‘r’:
if (evt .isShi ftDownO) {
if (rectlnsets.right > 0) {
rectlnsets.right--;
} else (
rectlnsets.right++;
}
repa int();
}
}
8X3
Insets
bottom
java.awt
public static void main(String[] args) {
new Mai n();
}
A bottom
В - — — — _ - — — . — - .. —
c 14 RPOSI Contains (he inset’s bottom value.
о SWT XX public int bottom
в F EXAMPLE See the class example.
G clonef)
— ™ — . — — . — —
PI RPOSE Creates a copy of the inset.
SYNTAX public Object cloneQ
J Di SCR IP (ION Creates an insets instance with the same values as this inset.
к Ri П RNs A non null copy of the inset.
L OXLRRIDFS java.lang.Objeer.clone().
M Ni 0 LXAMPI ! equalsf) See java.lang.Object.clone().
P — ~ . — — — —. — — - — ~
Q Pl‘RPOSE Determines whether an object is equal to this insets.
к S\STAX public boolean equals(Object obj)
s DESCRIPTION This method determines whether obj is equal to this insets. It is equal it it is an
instance of Insets and has the same left, right, lop bottom values as (his
7’ insets’s values.
V PARAMim RS
V obj The object to check.
w RI H’RNS true if obj is equal to this insets; false otherwise.
X OVERRIDES java.lang.Object.equals().
Y EXAMPLE
7
first - comp.getlnsetsO ;
second = comp2. getlnsetsO;
Insets
Insets
if (first.equals(second))
Sys tem.out. pri ntln(“The insets are the same1');
S84
java.awt
lose
Insets
Insets()
PURPOSE Constructs a new Insets instance.
SYNTAX public Insets(int top, int left, int bottom, int right)
description This constructor creates a new Insets instance that has the specified insets.
PARAMETERS
bottom left right top The bottom inset. The left inset. The right inset. The top inset.
EXAMPLE See (he class example.
left
PURPOSE Contains the inset’s left value.
SYNTAX public int left
EXAMPLE See the class example.
right ...
PURPOSE Contains the inset's right value.
SYNTAX public int right
EXAMPLE See the class example.
top
PURPOSE Contains the inset's top value.
SYNTAX public int top
example See the class example.
java.awt
Insets
toString()
toStringf)
purpose Generates the string representation of this inset.
SYNTAX A DESCRIPTION В public String toString() This method generates the string representation of this inset. The rcpresenta- tion consists of the inset’s values. This method is typically used for debugging.
C RETURNS A non-null string representing the inset state.
D OVERRIDES java.lang.Object.toString().
E EXAMPLE See java.1ang.Object.toString().
886
java, beans
IntrospectionException
Cl 2" fru~ <Я h^r parogen rut 'sh-wr. • i г/н
Ex opt..n *
Syntax
public class IntrospectionException extends Exception
Description
Introspection, is lhe process of discovering a bean's properties, events, and methods by exam-
ining the bean’s public methods. The discovery process is based on looking for special patterns
in the signatures of each pattern. For example, suppose a bean has two methods with the fol-
lowing signatures.
public float getPriceO
public void setPrice(float price)
By introspection, we can deduce that the bean has a float property called "price.” For more
information about the introspection process and signature patterns, see Introspector.
IntrospectionException is rarely thrown when introspection is applied on an arbitrary
bean. This is because introspection looks for signature patterns and reports only those it finds.
IntrospectionException is most often encountered when the bean provides a bean-info
(see Beaninfo). Whenever methods are specified in lhe bean-info, a check is made to see if
the methods are compatible with each other. For example, if the bean-info claims that
public String getPriceO
public void setPrice(float price)
are the accessor methods for the "price” property, the introspection process will check the sig-
natures, discover that they are not compatible, and then throw IntrospectionException.
Int rospect ion E xcept io n
java, beans
MEMBER SUMMARY
Constructor
IntrospectionExceptionO Constructs an IntrospectionException instance.
See Also
Introspector.
Example
The following example causes an IntrospectionException to be thrown. The example
bean implements a pair of accessor methods for the "bad" property. The type returned by the
read accessor method does not match the type passed to the write accessor method.
A property descriptor (see PropertyDescriptor) specified in a bean-info (see Bean-
Info) is necessary' to force the introspector to consider the two methods as accessor methods.
If the property descriptor was not there, the introspector would notice the incompatibility of
the two methods and simply ignore them, assuming that they were not accessor methods.
Bean.java
import java.beans.*;
public class Bean {
public String getBadO {
retu rn nul1;
}
public void setBad(int bad) {
}
public static void main(String[] args) {
try {
Beaninfo bi - Introspector.getBeanlnfoCBean.class):
} catch (IntrospectionException e) {
e.printStackTraceQ;
}
}
}
Bea nBea nl nf o. ja va
import java.beans.*;
public class BeanBeanlnfo extends SimpleBeanlnfo {
public PropertyDescriptorП getPropertyDescriptorsO {
PropertyDescriptor pd[J = new PropertyDescriptor[1];
try {
pd[0] «• new PropertyDescriptor(,lbad”, Bean, cl ass.
“getBad”, “setBad");
return pd;
} catch (Exception e) {
e.printStackTrace(System.out):
888
ju v it. wans
IntrospectionExceptionf
return null;
}
}
}
Output Here is the output produced by running the example:
java.beans.IntrospectionException: type mismatch between read and write methods
at java.beans.PropertyDescriptor.findPropertyType(PropertyDe$criptor.java:252)
at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:86)
at BeanBeanInfo,qetPropertyDescriptors(BeanBeanInfo.java:8)
at java.beans.Introspector.getTargetPropertyInfo(Introspector.java:254)
at java .beans. Int rospector .getBeanlnfoQnt rospector. java: 202)
at java.beans.Tntrospector.getBeanInfo(Introspector.java:83)
at Bean.main(Bean.java:12)
IntrospectionExceptionO
PURPOSE Constructs an IntrospectionException instance.
SYNTAX public IntrospectionException(String msg)
PARAMETERS msg A possibly null string describing the reason for the exception.
EXAMPLE See the MethodDescri ptor class example.
Syntax
public class Introspector
Description
The introspector constructs a complete set of feature
descriptors (see FeatureDescriptor) for a bean.
Some feature descriptors may be explicit. which
means they were extracted from a bean-info object
(see Beaninfo), and some may be implicit, which
means they were deduced by the introspector. See
Figure 221. The process by which the introspector
deduces implicit feature descriptors is called intro
spection and is described in the next section.
When asked to return the feature descriptors for a
bean, the introspector first tries to locate a bean-info
for the bean (this process is described later in this
item). If it finds one, it looks in the bean-info for
explicit feature descriptors.
There are four categories of explicit feature
descriptors in a bean-info:
BwtMtor ix'
Introspector
Imolicit
Descriptors
Expbcit
Descriptors
Bean
-0
Bean Descriptor
Event Sot Descriptors
Method Descriptors
Parameter Descriptors
Properly Descriptors
Bean-Info
FIGURE 221: Introspector.
I. Bean
2. Event set
3. Method
4. Property
When explicit feature descriptors are available in any of these categories, the introspector uses
those feature descriptors and does not apply introspection to discover those feature descriptors.
However, if a category does not contain any explicit feature descriptors (it has the value null),
the introspector applies introspection to discover those feature descriptors. For example, if a
bean-info contains only a few explicit property descriptors, the introspector uses them and
then applies introspection to discover the feature descriptors in the other three categories.
Introspection
Introspection is the process of discovering feature descriptors b\ examining the signatures of
the bean's public methods. This also includes all of the public methods in the bean's super-
j a v a. ne an s !«» vo jp> v*>
classes. For example, if there are no explicit property descriptors available (from a bean-info),
the introspector creates a list of al! of the public methods in the bean and then searches that list
for signatures that match a particular pattern. Suppose the introspector finds a method with the
following signature:
public void setFlavor(String flavor)
It will assume that the bean has a property called “flasor" and that this method is the write
accessor method for the property.
Following are the patterns that are used to detect different types of features:
get/set Pattern
public PropertyType get Proper tyNameO
public void setPropertyName(.PropertyType v)
The presence of these signatures indicates the bean has a property called propertyName of
class PropertyType. If either of these signatures is detected, the introspector creates a prop-
erty descriptor (see PropertyDescri ptor) for a property called propertyName. which is the
decapitalized version of PropertyName (see decapi tai ize()). The detected method(s)
become the accessor methods for that property.
For example, the presence of cither of the following methods indicates that the bean has a
“flavor' property of class String:
public String getFlavor()
public void setFlavor(Strinq flavor)
is/get/set Pattern
boolean public boolean isPropertyNameО
public boolean get Prope rtyNameO
public void setPropertyName(boolean v)
If any of these signatures is detected, the introspector creates a property descriptor (see Prop-
ertyDescri ptor) for a property called propertyName, which is the decapitalized version of
PropertyName (see decapitalize()). The detected method(s) become the accessor methods
for that property. If both “is" and “get" methods are detected, the “is" method becomes lhe
accessor method.
For example, the presence of either of the following methods indicates that the bean has a
boolean “roasted" property:
public boolean isRoastedO
public boolean getRoastedQ
public void setRoasted(boolean roasted)
Introspector
java.beans
Indexed Property Pattern
public Property Type f] getPropertyNameQ
public PropertyType getPropertyName(int i)
public void set PropertyName(PropertyType[] v)
public void setPropertyName(i nt i, PropertyType v)
B If any of these signatures are detected, lhe introspector creates an indexed property descriptor
(see IndexedPropertyDescriptor) for a property called propertyName. which is the
c decapitalized version of PropertyName (see decapitalize()). lhe detected method(s)
D become the accessor methods for the property.
t For example, lhe presence of any of the following methods indicates that the bean has a
property named "flavors” consisting of an array of St ri ng objects:
F
public Stri ng [] getFiavorsO
G public String getFlavors(int i)
public void setFlavors(int i, String flavor)
H public void setFlavorsfStri ng[] flavors)
И Public Method Pattern
j The introspector creates method descriptors (see MethodDescriptor) for all of the bean’s
public methods. This includes all of lhe public methods in the bean's superclasses as well.
К
L Multicast Event Set Pattern
M public void addEventNameti stener(EventNameListener 1)
public void removed vent Л/a/neLi stener (t ven t/VameLi stener 1)
0 If both of these signatures are detected, lhe introspector creates an event set descriptor (see
EventSetDescriptor) for an event set called eventName. which is the decapitalized version
p of EventName (see decapitalizeO)* The detected methods become the listener support
q methods for the event set. EventNamelA stener must be a subclass of
java.util.EventListener.
R
For example, the presence of the following methods indicates that the bean fires action
S multicast event sets that will be processed by Acti onLi steners:
т
1 public void addActionListener(ActionListener listener)
public void removeActionListener(ActionListener listener)
V Unicast Event Set Pattern
W public void add E ven tNameLi stener (.Event NameLi stener I)
throws TooManyListenersException
X public void remove Even t/VameLi stener (EventNameLi stener 1)
Y If both of these signatures are detected, the event is considered io be a unicast event. An event
7 set descriptor is created exactly like a multicast event, except that lhe unicast attribute is set to
true.
892
java, beans
Introspectoi
For example, the presence of the following methods indicates that the bean fires action
unicast event sets that will be handled by ActionLi steners:
public void addActionListener(Actionl istener listener)
throws TooManyListenersException
public void removeActiontistener(ActionListener listener)
The Search Path
The search path is an array of package names. The introspector uses this list to find a bean-
info fora bean (described below). The introspector'* default search path "sun. beans, infos".
Locating the Bean-info
When locating the bean-info for a bean, the introspector first appends "Beanlnfo" to the pack
age-qualified class name of the bean. It then tries to instantiate a class with (hat name. For
example, if the bean name is java.util.Calendar. it tries to instantiate a class named
java.util -CalendarBeanlnfo. If no class with that name is found, it removes the package
name from the class name. For example, java.uti 1 .CalendarBeanlnfo becomes Calen-
darBeanlnfo. Il then prefixes each of the package names in the search path with the class
name (separated by ’*/') and then tries to instantiate that class. For example, if the search path
contained sun.fi rst and sun.second, the introspector tries to instantiate sun.first.Cal -
endarBeanlnfo. If that fails, it tries sun. second .CalendarBeanlnfo.
HIMBER SUMMARY
Descriptor Method
getBeanlnfoO
Retrieves the bean-info of a bean.
Search Path Methods getBeanlnfoSearchPathO setBeanlnfoSearchPathO Retrieves the introspector’* search path. Sets the introspector *s search path.
Decapitalize Method decapitalize О Decapitalizes a string.
See Also
Beaninfo, java.util.TooManyListenersException.
Example
This example runs the introspector on any class file containing a bean. The program imple-
ments a simple class loader that can load class files from the file system. The first parameter is
Introspector
java.beans
the filename of lhe bean class file. Subsequent parameters are appended to the introspector’s
search path.
This version of the introspector searches for the bean’s bean-info class file in the same
directory that contains the bean class file. If that file is not found, il uses the search path to
locate a bean-info class file.
import java.beans;
import java.lang.reflect;
import java.util.A;
class Main {
public static void main(StringLJ args) {
if (args.length < 1) {
System. err. pri ntlnC’Usage: java Main <name of bean class file>”);
System.exi t(l);
}
// The other args are to be appended to the search path.
Stringf] oldPath *= Introspector.getBeanlnfoSearchPathO;
String^] newPath = new StringfoldPath.length + args.length - 1];
for (int i-0; i<oldPath.length; i++) {
newPath[i] = oldPathLi];
}
for (int i=0; i<args. 1 ength-1; i++) {
newPath [i-‘-oldPath. 1 ength] = argsfi+l];
}
Introspector.setBeanlnfoSearchPath(newPath);
try {
// Get the bean.
Class be = FileClassLoader.load(args[0]);
pri ntBeanlnfo(bc);
} catch (IntrospectionException e) {
e.pri ntStackT race();
}
}
public static void printBeanInfo(Class c) throws IntrospectionException {
Beaninfo bi = Introspector.getBeanlnfo(c);
BeanDescriptor bd bi . getBeanDescri ptorO ;
System, out. pri ntlnC'Cl ass: ” + bd.getBeanClassQ .getNameO) ;
System.out,println(MName: " + bd.getNameO) ;
System.out.printlnC'Di splay name: ” * bd.getDisplayNameO);
System.out.printlnC'Short Description: " + bd.getShortDescriptionO);
System.out.println("Expert: ,r + bd. isExpertO) ;
System.out.println("Hidden: " + bd. i sHiddenO) ;
if (bd.getCustomizerClassO 1= null) {
System.out.println("Customizer: ” +
bd.getCustomizerClassO .getNameO);
}
System.out.printlnO ;
// Print legend
Systern.out.pri ntln(
Nh:hidden, etexpert, i:indexed, *:default, c:constrained, b:bound”);
System, out. pri ntl n(,ru: uni cast, didefault set\n”);
894
JU » U.UVUIl,-)
// ** Print the property descriptors.
printRepeatC ”, 30);
System.out.printin("PROPERTIES”);
printRepeatC'-1', 72) ;
System.out.printlnO;
printC'Attr", 5);
print("Name", 20);
print("Type", 25);
printCAccessor methods", 25);
System.out.printlnO;
printRepeatC’-", 72);
System.out.printlnO;
// Now print each descriptor.
PropertyDescriptor pds[] = bi .getPropertyDescriptorsO ;
for (int i=0; i<pds.length; i++) {
printProperty(pds[i], i == bi. getDefaultPropertylndexO) ;
}
System.out.pri ntln();
// ** Print the event set descriptors.
printRepeat(” ", 30);
System.out.println("EVENT SETS”);
printRepeat(”-”, 72);
System.out.printlnO ;
printC'Attr", 5);
pri ntC’Name", 20);
System.out.println("Registration methods”);
System.out.println(” Callback methods");
printRepeatC’-", 72);
System.out .printlnO;
// Now print each event set descriptor.
EventSetDescriptor esds[] = bi .getEventSetDescriptorsO ;
for (int i=0; i<esds.length; i++) {
printEventSet(esds[i], i bi .getDefaultEventlndexO);
}
System.out.println();
// ** Print the method descriptors.
printRepeatC ", 30);
System.out.printlnC'METHODS");
printRepeatC-”, 72);
System.out.pri ntln();
printCAttr”, 5) ;
System.out.printInCSignature");
printRepeatC-", 72);
System.out.printlnO ;
// Now print each method descriptor.
MethodDescriptor methodsf] = bi .getMethodDescriptorsO;
for (int i=>0; i«methods.length; i++) {
printMethods(methods [i]);
}
}
static void printProperty(PropertyDescriptor pd, boolean def) {
printAttributes(pd, def);
print(pd.getNameO , 20);
Introspector
java.beans
A
В
C
D
li
E
(3
H
J
К
L
M
N
0
P
Q
R
S
7’
U
V
W
X
Y
Z
printName(pd.getPropertyTypeC), 25);
// Print accessor methods.
printName(pd.getReadMethod(), -1);
System.out .print('7'’) ;
printName(pd.getWriteMethodO , -1);
System.out. pri ntln() ;
if (pd instanceof IndexedPropertyDescriptor) {
IndexedPropertyDescriptor ipd = (IndexedPropertyDescripto
printAttributes(ipd, def, true);
printC'", 20);
printName(ipd.getIndexedPropertyIype(), 25);
printName(ipd.getlndexedReadMethocK) ? -1);
System.out.printC ’7”);
printName(ipd.getlndexedWriteMethodO, 1);
System.out.println() ;
}
static void printEventSetCLventSetDescriptor esd, boolean def) {
printAttributes(esd, def);
printName(esd, 20);
// Print listener methods.
printName(esd.getAddListenerMethodO. -1);
System.out.printC"/");
printName(esd.getRemoveLi stenerMethodO, -1);
System.out.println();
// Print callback methods.
Method ems[] = esd.getListenerMethodsO ;
for (int j=0; j<ems.length; j++) {
System, out. pri nt (,r ");
printName(ems[jl, -1);
System.out.println();
}
}
static void printMethods(MethodDescriptor md) {
printAttributes(md, false);
System.out.pri ntIn(md.getMethodC).toStri ng());
if (md.getShortDescription() != null
&& !md.getShortDescription() .equals(md.getNameO)) {
System.out.println(".......V" > md.getShortDescription() *
}
ParameterDescriptor[] pds = md.getParameterDescriptorsO;
if (pds 1= null) {
for (int i=0; i<pds.length; i++) {
Sy stem, out .pri nt C.");
printAttributes(pds[i], false);
print(pds[i].getNameC), 10);
System.out.printlnO ;
if (pds[i] .getShortDescriptionO null) {
System.out.println(".... \”” +
pds[i] .getShortDescription()+"\",r) ;
}
896
jit vit j icans
I
}
}
// Prints s and pads the string with Math.maxQ, width s.lengthQ) spaces
static void print(String s, int width) {
System.out.print(s);
for (int i=0; i<Math.max(l, (width-s.1ength())); i++) {
System.out .printf' ");
}
}
// Prints s 'count1 times.
static void printRepeat(String s, int count) {
for (int i=0; i<count; i++) {
System.out.print(s);
}
}
// Prints the object’s name. If null, prints
// Also if width >= 0. pads the string with
// Math.max(1, wi dth-s . lengthQ) spaces.
static void printName(Object o, int width) {
String result;
if (o -= null) {
result •- "?";
} else if (o instanceof Class) {
result = ((Class)o) .getNameO ;
} else if (o instanceof Method) {
result = ((Method)o) .getNameO :
} else if (o instanceof FeatureDescriptor) {
result - ((FeatureDescriptor)o) .getNameO ;
} else {
throw (new RuntimetxceptionO);
}
if (width >= 0) {
print(result, width);
} else {
System.out.pri nt(result);
}
}
static void printAttributes(FeatureDescriptor fd, boolean def) {
printAttributes(fd, def, false);
}
static void printAttributes(FeatureDescriptor fd, boolean def,
boolean indexed) {
String result =
if (def) {
result +=
}
if (fd.isHidden()) {
result +- “h";
}
if (fd.isExpert()) {
result +- "e";
}
if (indexed) {
Introspector
j ava.beans
В
Г)
E
г
FQSuAt +- '‘V’;
1
if (fd instanceof PropertyDescriptor) {
PropertyDescriptor pd = (PropertyDescriptor)fd;
if (pd. i sConstrainedO) {
result "c”;
}
if (pd. isBoundO) {
result "b":
}
}
if (fd instanceof EventSetDescriptor) {
EventSetDescriptor esd - (EventSetDescriptor)fd;
if (esd.i sUnicastO) {
result *- "u”;
}
if (esd.islnDefaultEventSet()) {
result += ’’d";
}
}
pri nt (resul t, 5);
}
Output When the example program is run on the Our But ton sample bean in the BDK
I. 1.0apr97. the folio* ing output is produced:
M Class: ьипл.demo.buttons.OurButton
Name: OurButton
\J Display name: OurBatton
Short Description: OurBatton
q Expert: *als>e
Hioden: false
p Q h: u: ^hidden, eiexoe^t, i:indexed, -zdefau'iT, c:constrained , bibound
: uni cast, didefault set PROPFR’IfS
R - — — - — — . . - - — - - - - W
Attn Name Гуре Accessor methods
c - - _ . — — - — — , — _ _ - — -
о e enah1ed boo’ear. istnabled/setFnab1ed
b preferredSize java.awt.Dimension getPreferredSize/?
1 b foreground java.awt .Color getForeground/serForeg»'oand
b 1 abe" java. lang. String geti_abe 1 /setLabe 1
L h visible boolean -sVisible/setVisib le
b background java.awt.Color getBackground/set Background
V b fontSize int getFontSize/setFontSize
b font java.awt.font getFont/setfont
W name java, '.ang. St’i ng get Name/set Name
b larger ont boolean isiargeFont/setLarqef опт
v b debug boolean getOchag/setDebug
Л b minirumSize java.awt.Dimension getvinimumSi ze/?
Y EVENT SI IS
_ _ _ ~ - . - - — — - — — , — - • _ _ .
7. Att r Name Registration methods
Callback methods
- • — — - - — — - л. - , . — — - .
a mouse addN'ouscListener/remove^ousei istener
moused i eked
898
inn Vl1|/vvivi
JUVd.lH. lll|>
decapitalize!)
monsePreused
rouseReleased
rrouse Entered
mouseFx’ted
d
d
d
d
d
d
key
key!yped
keyPressed
keyReleased
component
componentResized
c omponentMoved
componentShown
c omponentHidden
action
actionPer forced
propertyChange
propertyChange
focus
focusGained
focuslost
mouseMotion
r>ouseDragged
rrouseMoved
addKeyli st ener/removeKeyt i stener
add(opponent i istener/removeComporentI istener
addActionl'stener/reroveAcfonListoner
addP'opertyChange^istener/removeProper! y(hangel i stener
add FoeusL » st one r/ removef-ocusl i stener
addPouse^ot i onLi stene^/removeMouseMoti o^Li stener
MF IHODS
Attr Signature
public boolean java . awt .Component. i sVi si b le()
public synchronized void
java.awt.Component.addMousecistener(java.awt.event.voaseListenerj
public void java. awt. Component. enableO
public void java.awt.Component.move(intfint)
public java.awt.Dimension java.awt.Component.getSize()
public void java. awt. (orrponent. addNot i f у 0
<<< Two pages of output have been truncated. >>>
decapitalize()
purpose Decapitalizes a string.
Syntax public static String decapitaiize(String name)
description l he decapitalization rule is that the first letter of name is decapitalized using
Character.toLowerCaseО However if name is at least two characters long
and both the first and second characters are capitalized, this method simply
returns name.
For example, if name is "Flavor." "flavor" is returned. If name is "J." "j" is
returned. If name is "URL," "URL" is returned.
This method is used heavily by the introspector while it is creating implicit
feature descriptors. It is used lo derive property and event set names from the
name of a method. For example, if a method name is setFlavor, the property
name is "flavor."
java, beans
Introspector
getBcanlnfo()
PAR.AMETERS
name The non null siring to be decapitalized.
rlji rss A non-null string containing rhe decapitalized version of name.
i x \MPLt: This example simply invokes decapitaiize() on all of the program s argu-
ments.
import java. beans , ;
class N*a i n {
public static void main(St ringf] args) {
for (int i=0; i<args.1ength; i++) {
System.out.printlnfargs[i’ < “ -> “
t Introspector.decapitaiizeCargs[i]));
}
}
1
getBcanlnfoO
pi rpose Retrieves the bean-info of a bean.
syntax public static BeanTnfo getBeanlnfofClass beanClass) throws
IntrospectionException
public static Beaninfo getBeanlnfofClass beanClass, Class
stopClass) throws IntrospectionException
inscription This method constructs a bean-info from the bean's Class object. Some fea-
ture descriptors in the returned bean-info object may be explicit, which means
they were extracted from a bean-info object supplied by the bean (see Bean-
Info). Some may be implicit, which means thex were deduced by the intros-
pector using introspection. See the class description for more del ails on
locating and using a bean-info and on the process of introspection.
I’he descriptor arrays that are returned from this bean-info are never null. If
the descriptor array is empty, it mere!} has zero length. This differs from
directly accessing the bean-info object supplied by the bean, in which case lhe
descriptor array can be null.
By default, when the introspector introspects, it uses all of the bean's public
methods, including the public methods in the bean's superclasses. However, it
is possible to exclude some superclasses using stopClass. If stopClass is
specified, the introspector includes all of the public methods up to and includ-
ing those in stopClass but not an> of stopClass's superclasses. stopClass
must specify a superclass of beanClass and must not be the same as bean-
Class
900
JdV U.UUUI1?>
getBeanlnfoSearchPathf)
f
•' PARAMETERS
beanCl ass The Class object for a bean.
stopClass The possibly null Class object of one of the beans superclasses.
returns A non-null bean-info for beanClass.
exceptions
IntrospectionException
If an exception occurs during introspection or if stopClass is not a superclass
ofbeanClass.
example See the class example.
getBeanInfoSearchPath()
PURPOSE Retrieves the introspector's search path.
SYNTAX public static String!] getBeanlnfoSearchPathQ
DESCRIPTION This method returns the introspector's search path, which is used to find lhe bean-info for a bean. See the class description for details on how the search path is used. The search path initially contains a single element: “sun.beans, infos’1.
RETURNS A possibly null array of package names.
SEE ALSO setBeanlnfoSearchPathQ.
EXAMPLE See the class example.
setBeanlnfoSearchPathO
purpose: Sets the introspector's search path.
syntax public static void setBeanInfoSearchPath(String pathLJ)
description This method sets the introspector's search path, which is used to find a bean- info for a bean. See the class description for details on how the search path is used. When setting a new search path, include the elements of the current search path in the new search path. The current search path can be retrieved by calling getBeanlnfoSearchPathO.
PARAMETERS path A possibly null array of package names.
SEE Al^O getBeanlnfoSearchPathO.
EXAMPLE See the class example.
java.awt.event
ItemEvent
A
В
C
D
t:
t-
G
H
J
к
L
M
N
Syntax
public class ItemEvent extends AWTEvent
о
p
Q
R
s
T
L
V
W
X
Y
Description
An item event is fired by an item-selectable object (see ItemSelectable! when the selection
state (selected or deselected) of an item changes. An item event that contains the affected item
and its current selection state. The components that fire item events are Checkbox, Checkbox-
Menultem. Choice, and Li st.
Note that an item-selectable object may fire an item event even if the selection stale of the
item did not change (for example, by reselecting an already selected item). Also, an item-
selectable object does not always fire an item event if an item is deselected (for example, when
a change is made in a checkbox group or a choice). However, an item event is always fired for
an item that is newly selected. For more general information about events, see AWTEvent.
Listening for hem Events
To listen for item events from an item-selectable object, the listener must implement the Item-
Li stener interface. After that, the listener must be registered with the object. It becomes reg-
istered by calling the object’s addltemLi stenerQ method.
As with most events, an item event is delivered to its listeners after the operation has taken
place.
The hem Property
The item property of an item event contains a representation of the item whose selection state
has changed. The representation varies with the type of item-selectable object that fired the
event. In particular, the item property from a checkbox, choice, or checkbox menu item com-
java.awi.eveni
ponent is the item label string. The item property from a list is an Integer object containing
the index of the item.
The State Change Property
The state change property of an item event indi-
cates whether the item was selected or dese
Jected.
Item Event Flow
Figure 222 shows how item events typically
flow through (he system. First, the event is fired
by a component peer in response to some user
gesture. This event is posted on the event queue
(see EventQueue). When the event makes its
way to the front of the queue, it is given to the
component via its di spatchEvent О method.
The main purpose of this method is to discard
the event if the item event type is not enabled or
if there are no item event listeners. Otherwise,
di spatchEventO calls processEventO,
which in turn calls different methods depending
on the event type. Since this is an item event,
Peer
System
Event
Queue
ItemSelectable
ItemEvent
processEventO
FIGURE 222: Item Event Flow.
ItemL i stener
processItemEventO is called. The main purpose of this method is to notify the item event
listeners.
A component can override processItemEventO to process item events before they are
delivered to its listeners. The overridden method should call super.processItemEventO to
ensure that events are dispatched to the component's listeners.
HiMBER summary —I J
Constructor ItemEventO Constructs an ItemEvent instance.
I Property Methods getltemO getltemSelectable() getStateChangeO Retrieves the item whose selection state has changed. | Retrieves the item selectable object that fired this event. Retrieves the new selected state of the item. ।
4 Item Event Id Constants ITEM FIRST ITEM-LAST ITEM-STAIE-CHANGFD Constant specifying the first id in lhe range of item event ids. Constant specifying the last id in the range of item event ids. i Event id indicating that an item event occurred. '
Coniimu‘d J
A
В
C
D
E
F
C:
F
J
к
L
\
Г
(
1
(
J
ItemEvent
java.awl.event
MEMBER SUMMARY
Selection State Change Types
DLSLLLCTED
SF LFCTFD
/X
в
c
Item stale change ivpe indicating that an item has been dese
lecied. i
hem state change tvpe indicating ihai an item has been selected. |
Debugging Method
paramStri ng() Generates a string representing the item event's state.
e
F
н
See Also
ItemLi stener, java.awt.AWTEvent, java.awt,Checkbox,
java.awt.CheckboxMenuItem, java.awt.Choice, java.awt.ItemSelectable,
java.awt. 1 i st.
j
к
I.
M
N
О
P
Q
R
S
T
и
V
Example
This example demonstrates how to gel item events from a
component that fires them. The example creates a menu
with some checkbox menu items and listens for item events
from the menu items. In response to an item event, the spe-
cifics of the event are printed. See Figure 223.
import java.awt.';
import java.awt.event.
class Main extends Frame implements Itemlistener
{
Main() {
super(”ItemEvent Example”);
MenuBar mb = new MenuBarO;
Menu m - new MenufFi 1 e”) ;
I * ItemEvent Ex ORiEJ;
itemO /tem1 item 2 /Item 3
FIGI RE 223: ItemEvent.
mb.add(m);
for (int i=0; i<4; i++) {
CheckboxMenuItem c - new CheckboxMenuItem(”item "+i);
// Listen for item events.
c.add!temLi stener(thi s);
m.add(c);
}
w
X
Y
Z
setMenuBar(mb);
showO;
public void itemStateChanged(ItemFvent e) {
System.out.println("item selectable: ”+e.qetItemSelectableO);
System.out.print 1n("item: и+е.getltemO);
System.out.printC'state change: ”);
904
java.awi.cveni
DbSELBCTED
switch (e.getStateChangeO) {
case ItemEvent.SELECTED:
Systeir. out. pri ntl n ("SE- LECTED");
break;
case ItemEvent.DESELECTED:
Syst em.out.pri nt 1 n("DESELECTED”);
break;
}
}
public static void main(String argsLD {
new Main();
DESELECTED
PURPOSE Item state change type indicating that an item has been deselected.
SYNTAX public static final int DLSFLECIED
DESCRIPTION When an item event is fired, the new selection state of the affected item can be retrieved by getStateChangeO. /4 return value of DESELECTED (value 2) from getStateChangeO indicates the item has been deselected.
SEE ALSO getStateChangeO, SELECTED.
EXAMPLE See the class example.
getltemO
PURPOSE Retrieves the item whose selection state has changed.
SYNTAX public Object getltemO
♦ DESCRIPTION 5 I The item property of an item event contains a representation of the item whose selection state has changed. The representation varies with the type of item- selectable object that fired the event. In particular, the item property from a checkbox, choice, or checkbox menu item component is the item label string. The item property from a list is an Integer object containing the index of the item.
RETURNS Л non-null representation of the item that changed.
SEE ALSO CheckboxMenuItem, Choice, java.1ang.Integer, List.
EXAMPLE See the class example.
java.awt.event
ItemEvent
getltemScleclableO
get Item Selectable!)
Pl RPOSE Retrieves the item-selectable object that fired this event.
SV MAX public TtemSelectable getltemSe 1 ectabl eO
Л DFSCRIPTIOX This method returns the item-selectable object that fired the item event. This is
в the same object returned by FventObject.getSourceO
c RETURNS A non-null item-selectable object.
D SIT Al so java .util . Eventobject. getSourceO.
I-: IA WIPI 1 Sue lhe class example.
F
(5 getStateChangc()
H
Pl RPOSL Retrieves the new selected state of the item.
J SYNTAX public int getStateChangeO
DESCRIPTION The state change property of an item event indicates whether lhe item was
к selected or deselected. This method retrieves the new selected Mate ol'the item.
L REIT RNS Either SELECTED or DESELECTED.
M SEE Al SO SELECTED. DESELECTED.
N EXAMPl E See the class example.
()
P ITEM FIRST
Q R Pl RPOSI Constant specifying the first id in the range of item event ids.
s S'! X 1 AX public static final int HEM FIRST
1 DESCRIPTION All item event ids must be greater than or equal to ITEM-FIRST (value 701).
c SET: ALSO ITEM-LAST
V I X.AMP1 1 See java.awt.Component.processEventО.
w
X ITEM_LAST
Y Pl RPOSL Constant specifying the last id in the range of item event ids.
Z SYNTAX public static final int ITEM LAST
DESCRIPTION ЛП item event ids must be less than or equal to ITEM_LAST (value 701).
906
java.awt .event
iieiur.veui
ITEM STATE .CHANGED
SEE ALSO ITEv.riRST.
EXAMPLE See java.awt.Component.processEventO.
ITEM STATE_CHANGED
purpose Event id indicating that an item event occurred.
SYNTAX public static final int ITFV_STATE_CHANGLD
DESCRIPTION An item event with this event id (value 701) is fired when an item in an item- selectable object becomes selected. Item events are also sometimes fired if an item becomes deselected. The item that changed can be retrieved by a call to getltemO.
SEEALSO ItemFventO.
EXAMPLE See the MenuContainer class example.
ItemEvent()
PURPOSE Constructs an ItemEvent instance.
SYNTAX public ltemEvent(ItemSelectable source, int id, Object item, int newState)
DESCRIPTION This constructor constructs an item event that has source as the item select-
I- able object firing the event. At present, there is only one item event type, so id must be set to ITEM_STATE_CHANGED. newState specifics whether (he item was selected or deselected. After the item event is created, the source object can distribute it to its listeners by calling AWTEventMul ti caster. i temStateChangedO. If the event is not created by source, the creator can deliver the event to the source component either by posting the event to the event queue (see Fvent Queue .postEventO) or by calling the source component's Component .dis- patchEventO method directly.
PAR AM h I'ERS id item source newState Must be TTEM_STATE_CHANGED. I he non-nul 1 item whose state has changed. The non-nul 1 item-selectable object that is firing this item event. Either SELECTED or DESELFCTED.
SEE Al SO DESELECTED, getltemf), getltemSelectableO , I IFM.STATF.CHANGED, java . awt .AWTEvent. getIDO , java.awt.uti1.FventObject.get Source О. SELECTED,
EXAMPLE See the java.awt.MenuContainer class example.
java.awt.event
ItemFLvent
paramStringO
A
В
C
D
F.
F
paramStringO
pi rpose Generates a string representing the item event’s state.
syntax public String paramStringO
di -.scrip i ion The returned string contains the name of the item event, the name of the itein.
and an indication of the whether the item was selected or deselected. A sub-
class of this class should override this method and return a concatenation of its
state with the results of super.paramString(). This method is called bv the
AWTEvent. toStri ngO method and is typically used for debugging.
returns A non-nul 1 string representing the item event's state.
overrides java.awt.AWTEvent.paramStri ng().
si-f ai so java . awt .AWTEvent. paramStri ng() , java. lang .Object. toSt ri ng О •
i хам pi e See the java.awt.AWTEvent class example.
J
К
I
M
N
()
P
Q
R
S
T
i:
v
SELECTED
pi rpose hem state change type indicating that an item has been selected.
syntax public static final int SELECTED
description When an item event is fired, lhe new selection stale of the affected item can be
retrieved by getStateChangeQ. A return value of SELECTED (value 1) bv
getStateChangeO indicates the item has been selected.
SEE ALSO getStateChangeO, DESELECTED.
exampi г See lhe class example.
X
Y
z
908
java.awi.evuiu
ItemListener
Syntax
public interface ItemListener extends EventListener
Description
An item event is fired by an item-selectable object (see ItemSel ectabl el. hem-selectable
objects have a set of {items j that can be selected and deselected. When rhe selection slate of
an item changes, the item-selectable object fires an item event that contains the affected item
and its current selection state, hem events are fired by the components Checkbox, Checkbox -
Menuitem. Choi ce, ItemSel ectabl e. and Li st. See ItemEvent for more details.
When an object (listener) wishes to receive item events from an item-selectable object (the
source object), two things must be done:
1. The listener must implement lhe ItemLi stener interface and the i temStateChangedO
method required by this interface.
2. The listener must be registered with the source item-selectable object by making a call to
the object's addlteml i stenerO method.
For more information about item events, see ItemEvent.
on*
ItemListener
ja\ a.awt. event
MEMBER SUMMARY
Item Event Callback Method
i temStateChangedO Called when an item event occurs.
В
C
I)
F
F
C
II
J
К
1
M
N
()
P
Q
R
S
T
I’
V
w
X
Y
See Also
ItemEvent, java.awt.AWTEventMulticaster,
java.awt.CheckboxMenuItem, java.awt.Checkbox,
java.awt.Choi ce, java.awt.ItemSelectable,
java.awt.Li st, java.util.EventListener.
Example
This example implements a list that can display images and fire item
events. 1’hc list shows the currently selected image, and when the
selected image changes, it fires an item event. The image list fires first
an item event for the item that has been deselected and then an item
event for the newlv selected item. See Figure 224.
The image list implements the ItemSelectable interface so that
it can fire item events.
import java.awt.-;
import java.awt.event.x;
import java.util.*;
FIGI RI 224:
Image I ist.
public class Main extends Frame
implements ItemListener {
ImageLi st list = new ImageListO;
Main(String □ filenames) {
super'("ItemLi stener Exampl e") ;
// Add images.
for (int i=0; i<fi1enames.1ength; i-r+) {
list.addfgetToolki t().getImage(fi1enames[i]));
}
// Layout component and listen for item events.
addflist, BorderLayout.CENTER);
list.addltemLi stener(thi s);
pack();
show();
}
public void itemStateChanged(ItemEvent evt) {
// Simply print out the event.
System.out.println(evt);
}
910
public static void main(St ring args[]) {
if (args.length < 1) {
System.err.println(
''Usage: java Main <imagefile 1> <imagefile 2>...");
System.exi t(l);
}
new Mai n(args);
}
}
class ImageList extends Component implements ItemSelectable {
// Number of pixels to surround each image.
int margin = 3;
// Currently selected image; -1 means no image selected.
int curlmage = 1;
// Used to hold the images.
Vector images = new VectorQ;
ImageListO {
addMouseListener(new MouseEventHandlerO);
}
// Adds an image to the image list.
void add(Image image) {
MediaTracker tracker = new MediaTracker(this);
// We need to get the dimensions of the image.
try {
tracker.addlmage(image, 0);
tracker.wai tForAll ();
} catch (Exception e) {
e.pri ntStackTrace();
}
images.addElement(image);
}
publ i c Object LI getSelectedObjectsO {
if (curlmage >- 0) {
ObjectLJ result {images.elementAt(curlmage)};
return result;
I
return null;
}
// Paint the items.
public void paint(Graphics g) {
int у ft margin;
for (int i-0; i<images.size(); i++) {
Image image = (Image)images.elementAt(i);
int x - (getSize().width - image.getWidth(nul1))/2;
g.drawlmage(image, x, y, this);
if (i curlmage) {
// Draw an outline around selected image.
g.setColor(Col or.red);
ni
ItemListener
java.awt.event
for (int j = l; j<=margin; j++) {
g.drawRect(x-j, y~j,
image.getWidth(nu 11 )+2?-j -1,
image.getHeight(null)+2*j-1);
}
}
у +- image.getHeight(nulI) 2*margin;
}
}
// Computes the preferred size of the whole image list.
public Dimension get PreferredSize() {
int width - 0;
int height = 0;
for (int i=0; i«images . si ze(); i++) {
Image image - (Image)images.elementAt(i);
width - Path.max(width, image.getWidth(nu11));
height += image.getHeight(nul1);
}
// Add space for margins.
width -= 2*margin;
height += 2-margin'-(images.size()) ;
return new Dimension(width, height);
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
int у = margin;
// Find which image under the mouse coordinates.
for (int i=0; i«images.size(); it-*) {
Image image = (Image)images.elementAt(i);
int x - (getSize().width - image.getWidth(nul1))/2;
// Is the mouse coordinates on this image?
if (evt.getXO > x && evt.getXO < x+image.getWidth(nul1)
&& evt.getYO > у && evt.getYO < y+image.getHeight(nulL
// Fire an item event to deselect previous item.
if (curlmage >- 0) {
processltemFvent(
new ItemEventdmageList.this,
ItemEvent.ITEM STAT EXCHANGED,
new Integer(curlmage)f
ItemEvent.DESELECTED));
}
// Now fire an item event to select new item,
curlmage = i;
processItemEvent(
new ItemEvent(Imagetist.this,
ItemE vent.11FM_STAT F-CHANGED,
new Tnteger(curTmage)t
ItemEvent.SELECTED));
repaintO ;
break;
912
item State Ch an gcd()
}
у 4-- image.getHeiqht(nul 1) i- 2*margin;
}
}
}
// Methods to support item event listeners.
transient ItemListener ItemListener;
public synchronized void addltemListener(Ireir.Listener 1) {
itemlistener ~ AWTEventMulticaster.add(itemlistener, 1);
}
public synchronized void removelterListener(TtemListener 1) {
ItemListener AWTEventMulticaster.removedtemlistener, 1);
}
protected void process!temFvent(ltemEvent e) {
if (itemlistener I- null) {
i temLi stener.i temStateChanged(e);
}
}
}
itemStateChangedf)
PURPOSE Called when an item event occurs.
SYNTAX void itemStateChanged(ItemEvent evt)
DESCRIPTION This method is called after an item in an item-selectable object becomes selected. This method is sometimes called if an item becomes deselected. The item that changed can be retrieved by calling evt. getltemQ* The new selected state of the item can be retrieve by calling evt. getStateChange().
PARAMEI ERS evt The non-null item event.
EXAMPLL See the class example.
Q11
java.awt
ItemSelectable
«rr.Selcctabl#»
A
В
C
D
E
E
Syntax
public interface ItemSelectable
Description
H Phe ItemSelectable interface is implemented by components that support the selection of
zero or more items in single or multiple selection mode. The AWT components that implement
ItemSelectable are Checkbox. CheckboxMenuItem. Choice, and List.
J
К Events
A component that implements ItemSelectable fires an item event whenever the state of the
selection changes. For example, a checkbox fires an item event when it is clicked: a choice
M fires an item event when its selection changes. See ItemEvent and the class descriptions of
N the individual components that implement ItemSelectable for details.
See the AWTEvent class tor details on how to filter or handle events.
О
P
Q
R
S
T
I’
V
[member summary
. Fields
I getSelectedObjectsO Retrieves this component's current!} selected items.
j Event Methods
addrtemListenerO
I removeltemListenerQ
Adds a listener to receive item events fired b\ this component.
Removes a listener from receiving item events fired by this сотри- I
nent. ।
W
x See Also
Y Checkbox, CheckboxMenuItem, Choice, List.
Z
914
Example
This example creates a panel of buttons,
only one of which may be selected al
any time. When a button is selected, the
panel fires two item events, one to indi-
cate which button was selected and one
to indicate which one was deselected.
See Figure 225.
’ ItemS electable example RREJi
first | second j third | fourth [[fifth
FIGI RE 225: ItemSel ectabl e.
import java.awt.*;
import java.awt.event.*;
import java.uti1.Vector;
class Main extends Frame implements ItemListener {
Main() {
super(“ItemSelectable Example");
ButtonPanel bp = new Buttonpanel();
bp.add(new Button(“first"));
bp.add(new ButtonC'second”));
bp.add(new Button(‘“third"));
bp.add(new Button(“fourth’'));
bp.add(new Button("fifth"));
add(bp, BorderLayout.SOUTH);
bp.addltemL istener(thi s);
packO;
show();
}
public void itemStateChanged(ItemEvent evt) {
ItemSelectable src (ItemSelectable)evt .getSourceO;
Object[] selected src.getSelectedObjects();
System.out.println(“item event: “ + evt);
for (int i _ 0; i <selected.length: i++) {
System.out.print 1n("selected: “ + seiectedfiJ);
}
}
public static void main(String[j args) {
new MainQ;
}
}
class ButtonPanel extends Container implements ItemSelectable, ActionListener {
transient ItemListener iterListener;
int selected = -1;
Vector vec =- new Vector();
ButtonPanel () {
super() ;
setLayout(new GridLayout (1, -D);
enab I eEvents(AWTEvent.TTEM_EVENT_MASK);
ItemSelectable
java.awt
}
void add(Button b) {
super.add(b):
b.addActionListener(thi s);
vec.addElement(b);
if (selected — -1) {
selected = 0;
b.setEnabled(false);
} else {
b.setEnabled(t rue);
}
}
public void dctionPerformed(ActionEvent evt) {
Object src = evt .getSourceO ;
int where - vec.indexOf(src);
if (where >- 0) {
Button oldb = (Button)vec.elementAt(selected);
oldb.setEnab led(true);
Button newb - (Button)vec.elementAt(where);
newb.setEnabled(fa Ise);
selected = where;
ItemEvent oldEvt -
new ItemEvent(this, ItemEvent.IГ EM.STATE-CHANGED,
oldb, ItemEvent.DFSF1ECTED);
// dispatch item event for old button
processEvent(oldFvt);
ItemEvent newEvt •=•
new ItemEvent(this, ItemEvent.ITEM_5TATE_CHANGED,
newb, ItemEvent.SELECTED);
// dispatch item event for new button
processEvent(newEvt);
}
}
public Object” getSel ectedObjectsO {
if (selected >- 0) {
Object[] answer - new ObjectUJ;
answerLOJ = vec.elementAt(selected);
return answer;
} else {
return new ObjectLOJ:
}
}
public synchronized void addltemListener(ItemListener 1) {
itemlistener = AWTEventMul ti caster. add(i teril i stener, 1);
}
public void removeltemListener(Iteml istener 1) {
iterrListener - AWIFventMulticaster.removedtemListener, 1)
}
protected void processEvent(AWTEvent e) {
if (e instanceof ItemEvent) {
processItemEvent((ItemEvent)e);
return;
916
add!temListener()
}
super.processEvent(e);
protected void processItemEvent(ItemEvent e) {
if (itemListener 1= null) {
itemListener.i temStateChanged(e);
addItemListener()
PURPOSE Adds a listener to receive item events fired by this component.
SYNTAX public void addltemListener(ltemListener listener)
DESCRIPTION See ItemEvent for more details on item events. After this method is called, the item listener 1 i stener will receive item events Tired by this component. If 11 stener is nul 1, this method does nothing.
PARAMETERS listener The possibly null item listener to add.
SEE ALSO java.awt.event.ItemEvent, java.awt.event.ItemListener, remove! temLi stenerO.
EXAMPLE See the class example.
getSelectedObjects()
purpose Retrieves this component s currently selected items.
Syntax public synchronized Object[] getSel ectedObjectsO
returns An array of strings containing this component's currently selected items. The
return array is never nul 1 but may have length 0. which indicates that no items
were selected.
example See lhe class example.
ItemSeiectable
removeltemListenerf)
java.awt
removeItemListener()
A
В
c
D
Ei
E;
(i
EE
purpose Removes an item listener from receiving item events fired by this component.
syntax public void removeltemListener(ItemListener listener)
description See ItemEvent for more details on item events. After this method is called,
the item listener listener will no longer receive item events fired by this
component. If listener is null, this method does nothing.
PARAMETERS
1 i stener The possibly nul 1 item listener to remove.
seealso addltemListenerO, java.awt.event.ItemEvent,
java.awt.event.ItemLi stener.
E’Xample See removeActionListener() in Menuitem.disableEventsO.
J
К
I.
M
N
()
P
Q
R
u
V
X
У
z
918
Key Adapter
Syntax
public abstract class KeyAdapter implements Keylistener
Description
The key adapter is a key listener in which all callback methods are empty implementations.
The key adapter makes it more convenient for an object to listen for key events. In particular,
by using the key adapter, you can implement only those callback methods in which you are
interested. Without the key adapter, you are required to implement all callback methods, even
if the method is empty.
To use a key adapter, you create a subclass of KeyAdapter and override lhe desired call-
back methods. You then create an instance of the key adapter subclass and call the compo-
nent's addKeyListenerf) method with it. The key adapter subclass is typically an inner
class.
||bember summary
Key Event C allback Methods
keyPressedO Called when a key on the keyboard is pressed.
keyReleased() Called when a key on lhe keyboard is released.
keyTypedO Called when a pressed key or key combination fires a key char-
acter.
See Also
java.awt.Component.addKeyListener(), KeyEvent, KeyListener.
Example
This example implements a ‘typing tutor." After you click the Start button, letters start drop’
ping from the top. Your goal is to eliminate lhe letters before one hits the bottom. You elimi-
nate a letter by typing lhe appropriate key. The number of eliminated letters is shown at the
bottom of the display. See Figure 226.
9B
KeyAdapter
java.awt.event
Л
В
С
D
г:
ь
G
11
1
J
L
М
s
о
р
Q
R
S
т
с;
v
w
х
Y
z
The Typinglutor class uses a thread that is
responsible for creating letters and moving them
toward the bottom. Л letter is created with a probabil-
ity. That probability increases each time a letter is
eliminated.
The typing tutor also handles focus and mouse
events. When it receives a focus lost event, it stops
the letters from moving. When it receives a mouse
clicked event, it resumes moving the dropping letters.
The typing tutor uses an off-screen image (bbuf) to
implement double buffering in order to eliminate
flickering. The off-screen image is first cleared, and
then all of the characters are painted at their current
locations. The completed off-screen image is then
painted on the screen
FIGURE 226: l\ping ITiton
К
import java. awt.
import java.awt.event.*;
public class Main extends Frame implements ActionListener {
Label statusBar = new LabelLabel.CENTER);
TypingTutor TypingTutor = new TypingTutor(statusBar);
Button startButton = new ButtonC'Start”) ;
MainO {
super("KeyAdapter Example”);
// Listen for events
startButton.addActionLi stener(thi s);
// Layout components
add(startButton, Borderl ayout.NORTH);
add(statusBar, BorderLayout.SOUTH);
add(TypingTutor, BorderLayout.CENTER);
pack();
showO;
}
public void actionPerformed(ActionFvent evt; {
Typi ngTutor.request FocusO;
Typi ngTutor. startQ ;
}
public static void main(String argsf]) {
new Mai n() ;
}
}
class TypingTutor extends Canvas implements Runnable {
int width - 200;
int height = 300;
Label statusBar;
int score;
920
// Reference to the timer thread.
Thread timer;
// Unless true, the start() method is ignored,
boolean done = true;
// Locations and value of letters.
point[] letterPts;
char[] letters;
// Double buffer variables
Image bbuf;
Graphics bbufG;
// Font variables
Font f new Font("Monospaced", Font.BOLD, 20);
FontMetrics fm;
TypingTutor(Label statusBar) {
this.statusBar = statusBar;
addKeyListener(new KeyEventHandlerQ) i
addFocusListener(new FocusFventHandlerQ) ;
addMouseL istener(new MouseEventHandlerQ);
}
// This method should be called only when the com
// is visible.
synchronized void startO {
// Initialize font metrics if necessary,
if (fm == null) {
fm - getFontMetrics(f);
}
// Create the double buffer if necessary.
if (bbuf null) {
bbuf = createlmage(width, height);
bbufG - bbuf.getGraphics();
}
// Set variables
newLetterProbabi 1 ity = .05;
letterPts - new Point[200];
letters - new char[2001;
score = 0;
statusBar. setTextC’+score);
done false;
(timer = new Thread(this)).start();
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
if (letterPts == null) {
return;
}
// Clear the background.
bbufG.setColor(Color.yellow);
KeyAdapter
java.awi.event
bbufG.fi1lRect(0, 0, width, height);
bbufG.setColor(Color.black);
bbufG.drawRect(0, 0, width 1, height-1);
bbufG.setFont(f);
// Paint all the letters.
Л for (int i-0; i<letters.1ength; i++) {
if (letterPts[i] := null) {
В obufG.drawChars(letters, i, 1,
1etterPts[i].x, letterPtsLi J.y);
D
// Draw the off-screen image to the display.
E g.drawlmage(bbuf, 0, 0, this);
}
F
public Dimension getPreferredSize() {
G return new Dimension(width, height);
}
H
// Key events.
I class KeyEventHandler extends KeyAdapter {
public void keyTyped(KeyEvent evt) {
J int hiV = 0;
int 11 r - - 1;
К
// Find the lowest copy of that letter.
L for (int i=0; i<1etters.1ength; i+*) {
if (1etterPts[i] != null
M && lettersLi] == Character.toUpperCase(evt.getKey<
if (letterPts[i].у > hiV) {
N hiY - 1etterPts[i].у;
1 tr = i;
° }
P }
Q // If the letter is found, erase it.
if (Itr >= 0) {
R letterPts[1trj - null;
score++;
S statusBar. seMextC"’♦score);
T // Increase the probability of creating new letters
newLetterProbabi1ity .005;
U repaintO;
}
V }
}
W
// Focus events.
X class PocusEventHandl er extends FocusAdapter {
public void focusLost(FocusEvent evt) {
Y timer’ = null ;
}
Z }
// Mouse events,
class MouseEventHandler extends MouseAdapter {
922
public void mousePressed(MouseEvent evt) {
requestFocusO ;
(tiTer = new Thread(ГуртngTutor.this)).start() ;
}
}
// The duration of each tick.
int delay - 120;
// The probability of a new letter being created at each tick.
double newl etterprobabi1ity;
public void run() {
int count - 0;
try {
while ('done && timer -- thread.currentThreadO) {
for (int i^=0; i«letters.length; i+*) {
if (letterPts[i J !- null) {
letterPts[i].у *- 3;
// Check if the letter is at the bottom
if (1 e 11 e r Pt s f i □ • у >- height) {
// If so, clear all letters
for (int j=0; j<letters.length; j**) {
letterPtsLj] - nul1;
done = true;
}
}
}
}
if (Math. randomO < newLetterProbabi1ity) {
// Find a slot
for (int i-0; i«letters.length; i-+) {
if (letterPts[i1 == null) {
// Create a starting position for the letter.
letterPtsfi J =• new Point(
(int) Math . floor (Math. randomO *wi dth) , 0) ;
letterPts[iZ-X = Math.min(letterPts[i.x ,
width-fT.charWidth('X1));
// Pick a letter
letters[ij - (char)CA’
+ vath.floor(Math,random()-26));
break;
}
}
}
repaintO ;
Thread.sleep(delay);
}
} catch (Exception e) {
e.printStackTraceO;
}
}
}
KeyAdapter
key Pressed))
java.awt.event
keyPressedO
A PURPOSE SYNTAX DESCRIPTION Called when a key on the keyboard is pressed. public void keyPressed(KeyEvent evt) This method is called if the source component has the focus and a key is
В C D E F PARAMETERS pressed on the keyboard, l he identity of the key that was pressed can be retrieved by calling evt.getKeyCodeO. If the system supports autorepeat, this method is called each time the key is repeated. See lhe KeyEvent. KEY-PRESSED for more details about key pressed e\ents. This method, by default, has an empty implementation.
G evt The non-null key event.
H EXAMPLE See the KeyEvent class example.
keyReleasedO
К
“ purpose Called when a key on the keyboard is released.
L
syntax public void keyReleased(KeyEvent evt)
M
description This method is called when a key is released. The identity of lhe key that was
N released can be retrieved by calling evt.getKeyCodeO. See
О KeyEvent.KEY-RELEASED for details about key released events.
p This method, by default» has an empty implementation.
Q PARAMETERS
evt The non-null key event.
R
example See the KeyEvent class example.
T
U keyTypedO
V PURPOSE Called when a pressed key or key combination fires a key character.
w SYNTAX public void keyTyped(KeyEvent evt)
X Y z DESCRIPTION This method is called when a pressed key or key combination produces a key character. If the platform supports autorepeat, this method is called each lime the key character is repeated. See KeyEvent. KEY-TYPED for details about key typed events. This method, by default, has an empty implementation.
924
keyTyped
PARAMETERS
evt The non-nul 1 key event.
example See the class example.
java.awt.event
KeyEvent
A
В
C
D
E
E
G
H
I
L
M
N
()
P
Syntax
public class KeyEvent extends InputEvent
J
К
Description
Key events are tired by the component that has the focus (see Component} whenever the user
types at the keyboard For example, when the user presses the A key. a KEY PRESSED e\ent is
fired by the component that has the focus. To listen for key events from a component, you need
to call the component's addKeyListener() method. For more general information about
events, see AWTEvent.
The key event type has three event subtypes, shown in Table 16. See the field descriptions
for detailed information on these event subtypes.
Kev Event Suhtvpe ID Fired When ...
R s KEY PRESSED KEY-RFL EASED 1 KtY_IYPED A key on the keyboard is pressed. A key on the keyboard is released. A key character on the keyboard is pressed.
TABLE 16: Key Event Subtypes.
W
Listening for Key Events
X To listen for key events from a component, the listener must implement the KeyListener
Y interface. After that, the listener must be registered with the component, h becomes registered
by calling the component s addKeyLi stener() method.
An alternathe. and possibly more convenient, wax of receiving key events is to use a key
adapter. See KeyAdapter for more details.
926
Unlike most events, key events are delivered to its listeners before the operation has taken
place. This gives the listeners an opportunity to consume the event (see InputEvent.con-
sumeO).
Key Codes
Every key on the keyboard is assigned a unique value called a Aev code. When a key is pressed
on the keyboard, it fires a key event containing the key s key code. The same key code is emit-
ted by a key regardless of the state of the modifier keys. Ail keys on the keyboard (including
the modifier keys) fire a KEY-PRESSED event when pressed and a KEY-RELEASED event when
released. If the platform supports autorepeating keys, a KEY_PRESSED event is fired each time
the key is repeated.
The AW7' system defines a set of common key codes that can be fired by most keyboards.
However, some keyboards may not be able to fire al) of the key codes. Likewise, some key-
boards may have keys that don't correspond to any of the standard AWT key codes. Such a key
is called an unknown key code. An unknown key code will still fire a key event when pressed;
the key code value in the event will simply not be one from the standard set.
It is important to use the symbolic name for a key code (e.g., VK_HOME) rather than the key
code value itself. This is because in a future release of the Java, some key code values may
possibly change.
The value VKJJNDEFINED is used to represent an undefined key code.
Key Characters
A key character is a valid Unicode character that is fired by a key or key combination on the
keyboard. Whereas a key always fires the same key code, that key may fire different key char-
acters depending on the slate of the modifier keys. For example, the A key fires the key char-
acter (value 97) when the Shift key is not pressed and "A" (value 65) when the Shift key is
pressed.
The value CHAR__UNDEFINED is used to represent an undefined key character.
Action Keys
In Java 1.0.2. certain keys were designated as action keys. These were, in general, keys that
did not fire Unicode characters (e.g., the Home key). These action keys, when pressed and
released, were delivered to an application as the events Event .KEY-ACTION and
Event. KEY-ACTION^RELEASE.
For the most part, these old-event-style action events are now delivered to an application
as KEY-PRESSED and KEY-RELEASED events. T he key character property of these events is
always CHAR_UNDEFINED.
Table 17 shows the key codes that action keys can fire (this list may change in the future).
Unless your application is interested in exactly the keys in this table, the action key designa-
tions will not be particularly useful to you. Some keys, such as the Help key, naturally belong
in the action key group, but they are not there.
92
KeyEvent
java.awt.event
A
В
C
D
E
F
G
H
I
J
L
VK_HOME VCEND VK_PAGE_UP
VK_PAGE_DOWN VK_UP VK.DOWN
VK_LEFT VK_RIGHT VK_F1
VK_F2 VK_F3 VK_F4
VK_F5 VK_F6 VK_F7
VK_F8 VK_F9 VK_F10
VK_F11 VK_F12 VK_PRINTSCREEN
VK_SCROLL_LOCK VK_CAPS_LOCK VK_NUM LOCK
VICPAUSE VK INSERT
TABLE 17: Action Key Key Codes.
M
N
G
P
Q
R
S
T
U
V
Key Event Flow
Figure 227 shows how key
events typically flow through the
system. First, the event is tired
by a component peer in response
to the user's pressing a key on
the keyboard. This event is
posted on the event queue (see
EventQueue). When the event
makes its way to the front of the
queue, it is given to the compo-
nent via its dispatchEventO
method. The main purpose of
this method is to forward the
event directly back to the com-
ponent peer if the key event type
is not enabled or if there are no
key listeners. Otherwise, the
di spatchEvent() method
calls processEventO, which
in turn calls different methods
depending on the event type.
Component Peer
KeyEvent
System
Event
Queue
Component
di spatchEventO
processEventO
processKeyFvent О
consumeO
Componentpeer handleEvent()
FIGURE 227: Key Event Flow.
Keylistener
w
X
Y
Z
Since this is a key event, processKeyEventO is called. The main purpose of this method is
to notify the key event listeners. Finally, if the event has not been consumed (see
InputEvent), it is forwarded back to the originating component peer.
A component can override processKeyEventO to process key events before the\ are
delivered to its listeners. The overridden method should call super.processKeyEventO to
ensure that events are dispatched to the component's listeners.
928
Simulating Key Events
Key events are normally created by the AWT system when the user interacts with the key-
board. However, it is possible for any object to create key events in the same way. For exam-
p]e> a program designed to test a text field can create various key events and deliver them to
the text field. The text field will treat the key events exactly as if they came from the AWT sys-
tem.
A simulated key event can he delivered io a component in one of two ways either by
posting the event to (he event queue (as in Figure 227) or by calling the component's dis-
patchEventO method directly. See the KEY-TYPED field description for an example of simu-
lating key events.
BmRMBER SUMMARY Constructor KeyEvent() Constructs a KeyEvent instance. j
Property Methods getKeyCharO getKeyCodeO i sActionKeyO setKeyCharO setKeyCodeO setModifiersO Retrieves the key event's key character. Retrieves the key event's key code. Determines if this key event was fired by an action key Modifies the key event’s key character. Modifies the key event's key code. Modifies the key event's set of modifier keys.
Key Event Id Constants KEY-FIRST KEY-LAST KEY-PRESSED KEY_RELEASLD KEY-TYPED Constant specifying the first id in the range of key event ids. Constant specifying the last id in the range of key event ids. [went id indicating that a key on the keyboard was pressed. Event id indicating that a key on the keyboard was released. Event id indicating that a pressed key or key combination fired a key character. |
Key Codes CHAR_UNDFFTNED VK_0 VK_1 VK_2 VK_3 VK_4 VK_5 VK..6 VK—7 VK_8 Constant specifying an undefined key character (0). The 0 key (48). ' The 1 key (49). The 2 key (50). i The? key (51). The 4 key (52). The 5 key (53). The 6 key (54). The 7 key (55). The 8 key (56). 1
Ct nit in и cd
KeyEvent
java.au t.ex ent
A
В
C
D
E
F
G
H
I
X
Y
Z
| MEMBER SUMMARY
Key Codes (Continued)
VK .9 The 9 key (57).
j VK_A The A key (65).
VK_ACCFPT Asian keyboard-specific key (30).
VK_ADD The numpad + key (107).
VK„AL T The Alt key (18).
VK_B The R key (66).
VK_.BACK_QUOTE Thu ' key (192).
VK„BACK-SLASH The \ key (92).
VK_8ACK_SPACF The backspace key (8).
VK._C The C key (67).
VK-CANCFL The Cancel (Control C) key (3).
VK_CAPS_LOCK The Caps Lock action key (20).
VK_CLEAR The Clear (Control 1.) key (12).
VK CLOSE BRACKET The ] key (93).
VK_C0MMA The , key (44).
VK .CONTROL The Control key (17).
VK-CONVERT Asian keyboard specific key (28).
VK_D The D key (68).
VK DECIMAL The numpad . key (110).
VK_DELETE The Delete key (127).
VK.DIVIDE The numpad / key (111).
VK DOWN lhe Down action key (40).
VK E The E key (69).
VK_END The End action key (35).
VK_ENTER The Enter key (10).
VK_TSCAPE 'The Esc (escape) key (27).
VK_F The F key (70).
VK_ri I'hc Fl action key (112).
VK F10 The l;10 action key (121).
VK_F11 The Fl 1 action key (122).
VK. F12 The Fl 2 action key (123).
VK_F2 The 12 action key (113).
VK_F 3 The F3 action key (114).
VK_F4 lhe 1*4 action key (115).
VK_F5 'fhe 1'5 action key (116).
VK_F6 The F6action key (117).
VK_F7 l he F7 action key (118).
VK F8 The F8 action key (119).
VK_F9 The E9 action key (120).
VK_FINAL Asian keyboard-specific key (24).
’ VK_G The G key (71).
930
;MBER summary
VK_H 1Ъе H key (72 k
VICHELP ITie Help key (156).
VICHOME The Home action key (36).
VICI The 1 key (73 k
VICINSERT The Insert action key (155).
VICJ The J key (74).
VICK I'hc К key (75).
VJCKANA Asian keyboard-specific key (21 к
VICKANJI Asian key board-specific key (25).
VK_L The L key (76).
VICLEFT The left action key (37).
VK_M The M key (77).
VK.META The Meta key (157).
VICMODECHANGE Asian keyboard-specific key (31 к
VICMULTIPLY Th e n u in pad * кeу (1 ()6).
VICN The X key (78).
VICNONCONVERT Asian key hoard-specific key (29).
VICNUICLOCK The Sum Lock action key (144).
VCNUMPAD0 The numpad 0 key (96).
VICNUM PAD 1 'I’hc numpad-1 key (97).
VK.NUMPAD2 The numpad-2 key (98).
VICNUMPAD3 The numpad-3 key (99).
VICNUMPAD4 The numpad 4 key (100).
VICNUM PAD 5 The numpad-5 key (101).
VICNUMPAD6 The numpad-6 key (102).
VK_NUMPAD7 The numpad-7 key (103).
VICNUMPAD8 The ninnpad-8 key (104).
VICNUMPAD9 The numpad-9 key (105).
VICO The 0 key (79).
VK_OPEN_BRACKET The [ key (91).
VK_P The P key (80).
VK_PAGE_DOWN The PageDown action key (34).
VICPAGE_UP The Page I p act i on key (33).
VICPAUSE The Pause action key (19).
VICPERIOD 'I’hc . key (46).
VICPRINTSCREEN The Print Screen action key (154).
VK_Q The Q key (81).
VICQUOTF The ‘ key (222).
VK_R The R key (82).
VK_RIGHT The Right action key (39).
VK_S The S key (83).
KeyEvent
java.awt.event
MEMBER SUMMARY
A Key Codes (Continued) VK_SCR01l_l OCK VK_SEMICOLON The Scroll Lock action key (145 ). I'he : key (59).
В VK.SEPARATER VK.SHIt I The num pad . kev (108 к The Shift key (16k
c VK_SLASH The / kev (47).
D VK.SPACE VK_SUBTRACT The Space kev (32). The num pad - (minus) kev (109).
p VK I The T kev (84).
VK TAB The lab key (9).
F VK_U The Г key (85).
G VK UNDEFINED Constant specifying an undefined key code (0).
H VK UP VK_V I'he L'p action key (38). The V kev (86). ’
I . VK W The W key (87).
J VK_X VK_Y I he X key (88). The Y key (89).
VK„Z The Z key (90).
L M Debugging Method getKeyModi f i ersTextQ getKeyTextО Returns a printable representation of the key modifier st; Returns a printable name for a key code.
N paramSt ri ng() Gene rates a string representing the key event’s state.
()
P
<J
R
S
I
u
V
w
X
Y
z
See Also
KeyAdapter, KeyListener, java.awt.AWTEvent,
java.awt.Component.addKeyLi stenerQ.
Example
This example demonstrates how to get key events
from a component. It creates a text field and lis-
tens for key events from it. In response to a key
event, the specifics of the event are printed. See
f igure 228.
. KeyEvent Example
X|
AB CDE F GHIJKLMNO P QP STUVWX YZ
HGl’RE22Xi KeyEvent.
import java.awt.*;
import java, awt. event . ;
class Main extends Trame {
Ma i n О {
super(“Keytvent Example”):
TextField tf = new Textfield();
932
CHARJJNDEHNIiD
// Listen for text events.
tf.addKeyLi stener(new KeyEventHandl erО);
tf.setFont(new Font(“Courier", Font.PLAIN, 14));
add(tft BorderLayout.CENTER);
packQ ;
show();
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
printKey(evt);
}
public void keyReleased(Keyfvent evt) {
printKey(evt);
}
public void key7yped(KeyEvent evt) {
printKey(evt);
}
void printKey(KeyEvent evt) {
switch (evt.getlDQ) {
case KeyFvent.KEY_TYPED:
System.out.pri nt(“KFY_TYPED");
break;
case KeyFvent.KEY-PRESSED;
System.out.pri nt("KFY_PRESSED");
break;
case KeyEvent.KEY.RFLEASED:
System.out.print(“KFY_RELEASED");
break;
}
Sy stem, out.pri nt(“: char-"+evt.getKeyCharQ
+**(*♦(i nt) evt .getKeyChar()+")") ;
System.out.print(“ code=”+evt.getKeyCodeO);
if (evt.isActionKeyO) {
System.out.print(“ actionkey");
System, out. pri ntlnQ ;
}
}
public static void main(String argsLJ) {
new Mai n();
}
}
CHARUNDEFINED
purpose Constant specifying an undefined key character.
syntax public static final char CHAR .„UNDEFINED
QA
KeyEvent
CHAR LNDEI1NLD
ja\a.awt.e\ent
de\scrihk)\ When the key code in a KEY .PRESSED or KEY RELEASED event does not repre-
sent a kc\ character (e.g.. VK.HOME). the event’s key character property is set to
CHAR_UNDEFINED.
see .also KEY.PRFSSFD, KEY REl EASFD.
A EXAMPLE This example watches all ke\ - _ j
В transitions, when a key character
C is seen, it displays it. It erases the
display as soon as the user J*
I) releases the key character. See
E Figure 229. ,
F FIGI RE 229: Key character watcher.
import j ava. awt. ••;
i ] import java.awt.event.*;
class Kain extends Frame {
char curKeyChar;
MainO {
superC’CHAR UNDEFINED Example’1);
// Listen for text events.
addKeyLi stener(new KeyEventHandler());
setSize(200, 100);
setFont(new Font(“Monospaced”, Font.BOLD, 36));
showO;
public void paint(Graphics g) {
Insets ir - getlnsetsO;
FontMetrics fm = g.getTontMetrics();
String s - ““ + curKeyChar;
if (curKeyChar KeyEvent.CHAR UNDIFINED) {
g.drawString(s, (getSizeO.width-fm.st ringWidth(s))/2.
i n. topi- (getSizeO .height in. top-i n. bottom-
fm. get Height () )/2+frr .getAscentO);
I’
V
W
X
Y
Z
class KeyLventHandI er extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
if (curKeyChar evt.getKeyCharO) {
curKeyChar = evt.getKeyCharQ;
repai nt();
}
}
public void keyReleased(KeyEvent evt) {
curKeyChar - KeyEvent.CHAR UNDEFINED;
repai nt();
}
}
public static void main(String argsZJ) {
934
getKeyChart >
new MainO:
}
}
getKeyChar(£
purpose Retrieves the key event s key character.
syntax public char getKeyCharQ
description For all KEY„TYPED events, calling this method yields a key character, ne\er
CHAR_UNDEFINED. For KEY-PRESSED and KEY-RELEASED events, this method
may return CHARJJNDEFINED. See the class description for more information
on key characters.
The event's key character or CHAR_UNDEFINED.
REH RNS
SEE ALSO CHAR_UNDFFINED, KEY-PRESSED,
example This example implements a sim-
ple word game. The program
chooses a word at random, and
the user must guess the word,
fhe number of characters in the
word is displayed as a sequence
of underlines, one underline per
character. When the user types a
character in the word, the char-
acters appear on the screen.
KEY-RFlEASED, KEY-TYPED.
* getKeyChar Example в® n
e ten s
javoiu
FIGURE 230: Simple word game.
Wrongly guessed characters appear below the underlines in red. See Figure
230.
For each letter, the program listens for a KEY-TYPED event, retrieves the key
character, makes it lowercase, and then checks to see if it's a correct letter.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame {
StringC] words - {“java”, “class”, “i nterface" , “extends”, “ i irplement s”} ;
// Current mystery word. Index into ‘words’,
int curWord;
// Holds current set of correctly guessed letters.
char[] letters;
// Holds current set of incorrectly guessed letters.
String wrong!.etters;
KeyEvent
get KeyChart)
ja\ a.awt.exenl
A // win is true if all letters have been guessed, boolean win; Main О { super(“getKeyChar Example"); // Listen for text events.
В addKeyl istener(new KeyfventHand1er()); newGame() ;
C setSize(300, 150); setFont(new Font(“Monospaced", Font.BOLD, 36));
D E f- showO; } void newGameC) { curWord - (int)Math. floor(Math. randomO'-words .length); letters = new char[words[curWordJ.length()J;
G wrongLetters - ; win = false;
H 1 } public void paint(Graphics g) { Insets in = getlnsetsO;
J FontMetrics fm = g.getFontMetrics(); ч уч + kliAi Гm c ♦ r4 rt /*11 A? zJ ♦ l*s M Л A -
ini cnw = t m > st г 1 ngwi Qin v. M for (int i=0; icletters.length; i*+) {
L if (letters[ij > 0) { g.drawChars(letters, i, 1, in.left+iл(chw+chw/2)t
M N in. top+fm.getAscentO); } g.fi 11 Rect(i n. 1 efvi (chw+chw/2) , in. top+fm.getHeightО , chw, < у
О j if (win) {
P g.setColor(Color.blue); g.drawString(“You Won!’’, in.left, in. top+fm. getHei ght () 5< 2);
Q } else { g.setColor(Col or.red);
R g.drawString(wrongLetters, in.left, in.top+fm.getHeightO 2)
S T j } class KeyEventHand1 er extends KeyAdapter { public void keyTyped(KeyEvent evt) {
L char ch - evt.getKeyCharО;
V if (win) { newGameO ;
W }
X // If not a letter, return. ch = Character.toLowerCase(ch);
Y Z if (!Character.isLetter(ch)) { getToolк i t().beep(); return; } // Has the letter been guessed?
936
getKeyCode(
for (int i=0; i«letters.1ength; 1+4) {
if (ch — letters[12) {
getTool ki t () .beepO ;
return;
}
}
// Is the letter already in the wrong letter list?
if (wrongLetters.indexOf(ch) >= 0) [
getlool ki t () , beepO;
return;
}
// Is the letter correct?
if (words[curWordl,indexOf(ch) >- 0) {
for (int i=0; i«letters,length; i+4) {
if (wordsLcurWord].charAt(i) == ch) {
lettersli] - ch;
}
}
boolean foundBlank = false;
for (int i=0; 1«letters.length; i+t-) {
i f (lettersTi ] =- 0) {
foundBlank = true;
}
}
if (IfoundBlank) {
win true;
}
} else {
wrongLetters ch;
}
repaintQ ;
}
public static void main(String args[D {
new MainO;
}
1
getKeyCodeO
PURPOSE Retrieves the key event's key code.
SYNTAX public int getKeyCodeO
DESCRIPTION For all KEY-TYPED events, calling this method yields VK_UNDEFINED. For all KEY-PRESSED and KEY .RELEASED events, calling this method never yields VK_UNDEFINED. See the class description for more in tonnation on key codes.
RETURNS The event's key code or VK.UNDEFINED.
SEE ALSO CHAR_UNDEFINED, KEY .PRESSED, KEY _REL FASED, KEY-TYPED.
EXAMPLE See the class example.
java. awt.event
KeyEvent
getKev Modifiers Text()
getKey ModifiersText()
Pl RPOSI Returns a printable representation of the key modifier state.
SYNTAX public static String getKeyModifiersText(int mods)
DESCRIPIION This method examines mods for the state of four modifier keys: Ah. Control. Meta, and Shift. Il then returns a string showing which modifier keys are pressed, l he name of lhe modifier key that appears in lhe siring is determined b\ calling Toolkit.getProperty(), Table IS shows the properly name of lhe modifier kev code to use when retrieving the modifier kev’s printable name.
Modifier Key Code Property Name Default Printable Name
VK AL 1 AWT.alt Alt
VK_CONTROI. AWT.control Ctrl
VK VEIA AWT.meta Mela
VK_SHIFT AWT.shift Shift
TABLE 18: Modifier Key Property and Printable Names.
A key code’s printable name is retrieved through a properties file so that the
names can be localized. See Toolkit.getProperty() for more information
on the format of property file entries and where the property file is located.
This method is typically used for debugging purposes.
PARAMETERS mods A bit vector indicating the state of all modifier ke)s. Sec InputEvent for more details on modifier kevs.
SEE ALSO InputEvent.ALT.MASK, InputEvent.CTRL.MASKT
InputEvent.META.MASK, InputEvent.SHIFTJHASK,
java.awt.Toolki t.getProperty().
example See getKeyTextO.
getKeyTextO
pi rposi. Returns a printable name for a key code.
syntax public static String getKeyText(int keyCode)
938
java.awt.event
KeyEvei
get KeyText
description This method returns a printable name for a key code. If the value of the key
code is a printable ASC II character, the character is converted to a string and
then returned. If the value is not a printable ASCII character (e.g,, VK_H0Mt),
this method calls Tool кi t .getPropertyO to retrieve the key code’s print-
able name. Table 19 shous the key code's properly name to use when retriev-
ing the key code's printable name. If the properly name does not exist in the
properties file, the default name is used instead.
Retrieving a key code s printable name through a properties file allows the
names to be localized. See Tool kit.getPropertyO for more information on
the format of property file entries and where the property file is located.
This method is typically used for debugging purposes.
Key Code Property Name Default Printable Name
unknown key code AWT.unknown Unknown key ('ode
VK_ACCEPT AWT.accept Accept
VK.ADD AWT. add Num Pad +
VK.Al T AWT.alt Alt
VK..BACK_QUOTE AWT.backQuote Back Quote
VK_BACK SPACF AWT.backspace Backspace
VK_CAPS_LOCK AWT.capsl ock Caps Lock
VK_CLEAR AWT.clear (Tear
VK.CONIROI AWT.cont rol Ctrl
VK.CONVERT AW1.convert ('on vert
VK.DECIMAL AWT.deci mai Num Pad .
VK_DELETE AWT.delete Delete
VK_DTVTDE AWT.divide Num Pad /
VK.DOWN AWT.down Down
VK.END AWT.end End
VK.ENTER AWT.enter Enter
VK.ESCAPE AWT.escape Escape
VK_T10 AWT.f10 EH)
VK-Fll AWT.fil Fl 1
VK .F12 AWT.fl2 Fi 2
VK-F1 AWT .fl n
TABLE 19: Kej ('ode Properties and Printable Names.
(Ън united
KeyEvent java, liu I.event
i get Key Text!)
Key Code Property Name Default Printable Name
VK„ F2 AWT.f2 F2
VK_F3 AWT.f3 F3
A VK_F4 AWT.f4 F4
В VK_F5 AWT.f5 F5
г* VK_F6 AWT.f6 F6
VK F7 AWT.f7 F7
D VK_F8 AWT.f8 FK
E VK F9 AWT.f9 1'9
F VK.FINAL AWT.fi nal Final
VK.HELP AWI.heip Help
G VK..HOME AWT.home Home
H VK_TNSFRT AWT.i nsert Insert
1 I VK.KANA AWT.капа Kami
I VK_KAN.1I AWT .kanji Kanji
j VK„LEFT AWT.left LlTi
VK_META AWT.meta Meta
L VK MODECHANGE AWT.modechange Mode Change
M VK_MULTIPLY AWT.mu 11ipl у NuniPad *
VK_N0NC0NVERT AWT.noconvert No Convert
N VK NUMPAD0 - AWT.numpad NuniPad
0 VK.NUMPAD1
p VK_NUM_LOCK AW1.numLock Num Lock
VK„PAUSE AWT.pause Pause
Q VK_PAGE_DOWN AWT.pgdn Page Down
R VK PAGE UP AWT.pgup Page I p
S VK_PRXN1SCREEN AWT.pri ntScreen Print Screen
VK.QUOTF AWT.quote Quote
T VK_RIGHr AWT.right Right
I VK_SCROLL„LOCK AWT. scroll Lock Scroll Lock
V VK_SEPARATER AWT . separatee NumPad .
VK.SHTFT AWT.shift Shift
w
VK_SPACE AWT.space Space
X VK. SUBTRACT AWT.subtract NumPad -
Y VK_IAB AWT.tab Tab
7 VK_UP AWT.u p Lp
TABLE 19: Key Code Properties and Printable Names.
940
java.awt .event
RETURNS
SEI- ALSO
Key к vent
ivAetionKey(
A non-null string describing the key code.
java.awt.Toolki t.getPropertyO .
example: This example handles key pressed events and displays the results of calling
getKeyTextO on the key event s key code. See Figure 231.
import java. awt. ; import java.awt .event; < getKeyText Example
class Main extends Frame { String curKeyCode = String curModifiers - Caps Lock
Main О {
super(“getKeyText Example”); // Listen for text events. addKeyListener( new KeytventHandlerO) ; НИИ IRE 231: KeyEvent. getKeyText() .
setSize(2001 100);
show() ;
}
public void paint(Graphics g) {
Insets in - getlnsetsO;
FontMetrics fm - g.getTontMetrics();
String s - curModifiers + “ “ + curKeyCode;
g.drawString(s, (getSizeO .width-fm. stringWidth(s))/2,
in.top+(getSize().height-in.top in.bottom-
fm.getHei ghtО)/2 4 f m.getAscentO);
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyFvent evt) {
curKeyCode = KeyEvent.getKeyText(evt.getKeyCodeO);
curModi fi ers = KeyEvent,getKeyModi fi ersText(evt .getModi fiersO) ;
repaintO;
}
}
public static void main(String argsLD {
new Mai n();
}
}
syntax
isActionKeyO
purpose Determines if this key event was fired by an action key.
public boolean isActionKeyO
jav a.aw (.event
KeyEvent
KKY_HRST
DESCRIPTION Action keys arc a subset of keys that don't fire key characters. l he action key group appears mainly for backward compatibility with Java 1.0.2. In Java 1.1.2. there are more keys that could be considered action keys teg.. Help), but they are not considered action keys. So unless your application is interested in
A В C D Rf.TlRSS exactly those keys considered action keys, you may not find this method use- ful. See the class description for more information on action keys, including a list of action keys. true if the key event was fired by an action key: false otherwise.
E E XAVI Pl E: See the class example.
F-
KEYJFIRST
] Pl RPOSE Constant specifying the first id in the range of key event ids.
j SYNIAX public static final int KEY_F1RST
M DESCRIPTION All key event ids must be greater than or equal to KEY-FIRST (value 400).
। SEEALSO KFY-LAST
EXAMPLE See java.awt.Component.processEventO.
N
0 KEY_LAST
P PI RPOSE Constant specifying the last id in the range of key event ids.
Q MMAX public static final int KEY_LAST
R DESCRIPIION All key event ids must be less than or equal to KEY_LAST (value 402).
S SFF ALSO KFY_ FIRST.
T EX AM PI F See java.awt.Component.processEvent().
('
V
w
KEY-PRESSED
pl rpose Eivent id indicating that a key on the keyboard was pressed.
svxivx public static final int KEY PRESSED
in sc RiE’iiox A key event w ith this id (value 401) is fired when a key is pressed on the key-
board. The event's key code property contains the identity of the key that was
pressed. If the system supports autorepeat, a KEY_PRESSFD event is fired each
942
KeyEvent
KLY RELEASEE)
java.awt.event
time the key is repeated, so there can be more than one KEY-PRESSED event for
each KEY-RELEASED event. See the class description for more information
about key characters and key codes.
The event's key character properly contains the key character. However, if the
key does not fire a key character (e.g,. the Home key), the key character prop-
erty has the value CHAR-UNDEF INED.
The event's key modifiers are captured al the lime the key was pressed.
The Caps Lock and Num Lock keys are treated differently from the rest. With
these two keys, an event is tired only when the state of these keys change. Lor
example, when the Caps Lock key is physically pressed and released, a
KEY-PRESSED event is fired (to signify that the Caps Lock key is enabled).
When the Caps Lock is physically pressed and released again, a
KEY-RELEASED event is fired (to signify that the Caps Lock key is disabled).
Note: In Java L1.2, (his beha\ior has not yet been implemented.
SEEALSO KEY .RELEASED, KEY-TYPED.
example See (he class example.
KEY-RELEASED
purpose Event id indicating that a key on the keyboard was released.
syntax public static final int KFY_RELEASLD
description A key event with this id (value 402) is fired when a key is released. The
event's key code property contains the identity of the key that was released.
See the class description for more information about key characters and key
codes.
The event’s key character property contains the key character. However, if the
key does not fire a key character (e.g., the Home key), the key character prop-
erty has the value CHAR_UNDEFINED.
T he event's key modifiers are captured at the time the key was released.
SEE ALSO KEY-PRESSED.
example See the class example.
key typed
purpose Event id indicating that a pressed key or key combination fired a key character.
SYNTAX public static final int KEY.TYPED
java.au (.event
KeyEvent
KEY_TYPED
Duse•riptiox A key event with this id (value 400) is fired when a pressed key or key combi-
nation fires a key character. If the platform supports autorepeat, a KEY_TYPED
event is fired each time the key character is repeated. See the class description
for more information about key characters and key codes.
KEY-TYPED events are delivered after KEY-PRESSED events but before
KEY. RELEASED events. The event's key character is never CHAR-UNDEFINED,
and its key code property is always VK_UNDEFINED. The event’s key modifiers
are captured at lhe time the key character w as pressed.
SEExiso CHAR_UNDEFINFD, KEY_PRESSfD, KEY-RELEASED, VK .UNDEFINED.
EXAMPI I-
This example demonstrates howj
key events can be simulated to a
text area. It implements a version
of text area that can automatically
insert some text when a function
key is pressed. For example, if
you press FL the word "class" is
inserted into the text area. Also, if
the Shift key is pressed at the
same time, the word "class"
KEY_TYPED Example RfiJB
// AUTHOR: PC HAN & PI* EE
class Main extends Frame
EH.I RE 232: KeyEvent.KEY-TYPED.
becomes "CLASS." See Figure 232.
The text area overrides the processKeyEvent О method and watches for key
press events. When an event does occur, it is converted to a series of key typed
events and the original event is consumed.
Note: As of Java 1.1.2, this example may not work on platforms other than
Win32.
import java. awt.
import java.awt.event.л ;
class Main extends Frame {
MainQ {
super("KLY_TYPED Example’’);
add(new MyTextAreaQ, BorderLayout.CENTER);
packQ;
showO ;
}
public static void main(String argsQ) {
new Main();
}
}
class MyTextArea extends TextArea {
Objectf] macros = {
new IntegerfKeyEvent.VK_F1)T “class ",
new Integer(KeyEvent.VK_F2), “interface
944
java.awt.event
Keyrven
KeyHvenU
new lnteger(KeyEvent.VK_F3)t “extends “,
new Integer(KeyEvent.VK_F4), “implements ”,
new lnteger(KeyEvent.VK F5), “// author: pchan & rlee “,) ;
MyTextAreaO {
enableEvents(AWTEvent.KEY_FVFNI_MASK);
setFontfnew Font(“Courier”t Font.Pl AIN, 14));
}
public void processKeyEvent(KeyFvent evt) {
if (evt.getlDQ — KeyEvent. KEY-PRESSED) {
for (int i-0; i<macros.1ength; i*-2) {
Integer ri = (Tnteger)macros[i];
if (ri.intValueO == evt .getKeyCodeO) {
synthesi zeKeyEvent((Stri ng)macros fi*1],
evt. i sShiftDownO) ;
evt. consumeO ;
break;
}
}
}
super,processKeyEvent(evt);
}
void synthesizeKeyEvent(String s, boolean uppercase) {
for (int j-0: j<s.length(); j**) {
char ch - s.charAt(j);
if (uppercase) {
ch - Character.toUpperCase(ch);
}
KeyEvent ke = new KeyEvent(4yTextArea.this,
KeyEvent.KEY TYPED,
System.current 1imeMi1lis(), 0,
KeyFvent.VK_UNDEFINFD, ch);
getToolkitO .getSystemEventQueue() .postEvent(ke) ;
}
}
}
KeyEventQ
purpose Constructs a KeyEvent instance.
syntax public KeyEvent(Component source, int id, long when, int
modifiers,int keyCode, char keyChar)
public KeyEvent(Component source, int id, long when, int
modifiers,int keyCode)
KeyEvent
KeyEvenU)
java.awt.event
description This constructor creates a kc\ event with source as the component tiring this event. See the class description tor more information on key codes, key char- acters. timestamps, and modifier keys. After the key event is created, the source object can distribute the event to its
A listeners by calling the key event-related methods in AWTEventMul ticaster.
В If the event is not created b\ source, the creator can deliver the event to the
C source component either by posting the event to the event queue isee Event- Queue. postEvent ()) or by calling the source componenCs Component. dis-
D E F Cl patch^ vent 0 method directly. PARAMETERS source The non-null component that is firing this kev event. i d One of the key ev ent ids. when The timestamp for this event. See System.currentTimeMillisO-
IT i modifiers The current state of the modifier keys, key Code A key code.
I key Char A key character. 1 XCEPIIONS
1 11 legalArgumentException If id is KEY.TYPED and either keyChar is CHARJJNDEFINED or key- Code is not VK..UNDEFINED.
M X deprfcatiox The usage of the second form of this constructor is deprecated. Since keyChar is not supplied, it casts keyCode to a char. Use only the first form of this con-
о structor when creating KeyEvent instances. see M so getKeyCharO . getKeyCodeO, InputEvent.getModifiersQ i
p InputEvent.getWhenf), java.awt.AWT Event.getIDO.
Q java.awt.Component.di spatchEvent О > java.lang.System.currentTimeMill isf)<
R java, uti 1 . FventObject.getSourceO.
V
V
w
X
Y
946
java, aw Lev ent
KeyEvei
KeyEvent
example
This example implements a virtual key-
pad. Each key is a lightweight compo-
nent sei in a frame that has a grid layout.
The virtual keys are highlighted when
the cursor passes over them. When the
user presses a mouse button while the
cursor is over a virtual key. it fires a
KEY-TYPED key event containing the
key character displayed in the virtual
key's label. See Figure 233.
I ' KeyEvent Example 111 iw- HMV
HGl'RE 23Л: A virtual keypad.
import java.awt.
import java.awt.event. *;
import java.uti1.*;
class Main extends Frame {
String keys - ,,123456789’;0#";
MainQ {
super(”KeyEvent Example”);
setl ayout(new Gridlayout(4, 3, 6, 6));
for (int i-0; i <keys. 1 engthO ; 14-) {
KeyButton kb - new KeyButton(keys.charAt(i));
kb.addKeyLi stener(new KeyEventHandler());
kb.setВасkground(Color.pi nk);
kb.setForeground(Color.black);
add(kb);
setSize(200. 200);
showO
}
class KeyEventHandler extends KeyAdapter {
public void keylyped(Keytvent evt) {
System.out.println(evt);
}
}
public static void main(StringL] arqs) {
new Mai n();
}
}
class KeyButton extends Component {
KeyListener keyListener;
boolean highlighted;
char key;
KeyButton(char k) {
this.key - k;
addMouseListener(new MousetventHandlerO);
javu.au Levent
KeyEvent
paramStringO
public void paint(Graphics g) { int w = getSizeO .width; int h getSizeQ • height; String s = ,,,1+key;
A FontMetrics fm - g.getfontMetrics();
В C if (highlighted) { g.setColor(getBackgroundO) ; g.fi11RoundRect(0, 0, w-1, h-1, 10, 10); г
D J g, setCol or (get ForegroundO) ; g.drawRoundRect(0, 0, w-1, h-1, 10, 10);
E I- g.drawString(s, (w-fm.stringWidth(s))/2, (h fm.getHeight())/2+fm.getAscentO); }
Ci class MouseEventHandler extends MouseAdapter { public void mousePressed(MouseEvent evt) {
H 1 if (keylistener != null) { keyLi stener.keylyped( new KeyEvent(KeyButton.this, KeyEvent.KIY.TYPED, System.currentTimeMi11i s(),
0, KeyEvent.VK.UNDLFINED, key)); г
J } public void mouseFntered(MouseEvent evt) {
L highlighted - true; repaintO ;
M N } public void mouseExited(MouseEvent evt) { highlighted = false; repai nt();
() P } } // Listener support methods
Q public synchronized void addKeyListener(Keyl istener 1) { keylistener - AWTEventMulticaster.add(keyl istener, 1);
R S T } public synchronized void removeKeyl istener(KeyListener 1) { keylistener - AWTEventMulticaster.removefkeylistener, 1); } }
i: V paramStringO
w — • -
X pi’rpose Generates a string representing the key event's state.
Y z syntax public String paramStringO desc ription The returned string contains the name of the key event, the key code, the key character, and the key modifiers. A subclass of this class should override this method and return a concatenation of its state with the results of
948
java.awt.event
лгуглст
setKeyCharO
super. paramStringO. This method is called by the AWTEvent. toStri ng О method and is typically used for debugging.
returns A non-nul 1 string representing the key event's state.
OVERRIDES SEE ALSO java.awt.AWTEvent.paramStri ng(). java.awt.AWTEvent.toStri ng О » java.1ang.Object.toStringО.
EXAMPLE Seethe java.awt.AWTEvent class example.
set Key CharQ
PURPOSE Modifies the key event s key character.
SYNTAX public void setKeyChar(char keyChar)
DESCRIPTION This method modifies the key character in the key event. Since key events are input events, the peer for the source component (the one that fired the event) will interpret the modified event. If the event is modified by a listener, all subsequent listeners will see the mod- ified event.
PARA ME I ERS keyChar The new key character.
SEE ALSO getKeyCharO , setKeyCodeO.
EXAMPLE See setModi fi e rs О <
setKeyCodeO
PURPOSE Modifies the key event's key code.
SYNTAX public void setKeyCodefint keyCode)
DESCRIPTION T his method modifies the key code in the key event. Since key events are input events, the peer for the source component (the one that fired the event) will interpret the modified event. If the event is modified by a listener, all subsequent listeners will see the mod- ified event.
PARAMETERS keyCode The new key code.
SEE ALSO getKeyCodeO, setKeyChar().
example See setModifiers().
KeyEvent
setModifiersO
java.awt.event
setModifiersO
Л
в
c
D
E
F
G
H
I
J
purpose Modifies the key event's set of modifier keys.
syntax public void setModifiers(int mods)
description This method modifies the sei of modifier keys in the kev event. Since key
events are input events, the peer for the source component (Ihc one lhat fired
the event) will interpret the modified event.
If the event is modified by a listener, all subsequent listeners will see the mod-
ified event.
PARAMETERS
mods
SEE Al SO
EXAMPLE
A bit set containing the new state of the modifier keys. Sec InputEvent on
how to interpret this bit set.
InputEvent.ALT_MASK, InputFvent.CTRL_MASK,
InputFvent.getModifiersO, InputFvent.META-MASK,
InputEvent.SHIFT_MASK.
К
L
M
N
О
P
Q
R
S
T
L
V
W
X
Y
Z
This example modi-
fies KEY-TYPED
events enroute to a
text area. The four
modifier keys are
represented by four
checkboxes. When a
checkbox is set. the
program modifies
the key character to
simulate the modi-
» setModihers Example
TYPING IN UPPERCASEl
Г alt | control | meta F" shift
FIGI’RE 234: KeyEvent. setModi fiersO •
tier key that the checkbox represents. For example, when the Shift checkbox is
enabled, all key characters are converted to uppercase. See Figure 234.
import java.awt.*;
Import java.awt.event.*;
class Main extends Frame {
Checkbox altCb = new Checkbox(“alt”);
Checkbox controlCb = new Checkbox(“control");
Checkbox metaCb = new Checkbox(“meta”);
Checkbox shiftCb = new Checkbox(’‘shift ”) ;
Main() {
super(“setModifiers Example”);
TextArea ta = new TextAreaO;
add(ta, BorderLayout.CENTER);
ta.addKeyLi5tener(new KeyEventHandlerO);
950
java.awt.event
IX C J IL V 1 11
vk_unde:hnel
Panel p = new Panel (new FlowLayoutO);
p.add(altCb);
p.add(controlCb);
p.add(metaCb);
p.add(shi ftCb);
add(p, BorderLayout.SOUTH);
setSize(300, 200);
showO;
1
class KeyEventHandler extends KeyAdapter {
public void keyTyped(KeyEvent evt) {
int mods = evt. getModifiersO ;
char ch - evt.getKeyCharQ;
if (altCb.getStateO) {
mods - InputEvent.ALT-MASK;
}
if (controlCb.getStateO) {
mods ’=• InputEvent.CTRL_MASK;
ch (char)(Character.toUpperCase(ch) - 64);
evt.setKeyChar((char)Math.max(0, ch));
}
if (metaCb .getStateO) {
mods |= InputEvent.MLTA_MASK;
}
if (shiftCb.getStateO) {
mods 1= InputEvent.SHIFT-MASK;
evt.setKeyChar(Character.toUpperCase(ch));
}
evt.setModi fi ers(mods);
}
public static void main(String[] args) {
new Main();
VKJJNDEFINED
purpose Constant specifying an undefined key code.
Syntax public static final int VK.UNDEFINED
description When the key code in a key event does not represent a key code, the event's
key code property is set to VKJJNDE FINED. The key code in all KEY-TYPED
events is VK_UNDEF INED.
SEE ALSO KEY TYPED.
example See KeyEventО.
java.awt.event
KeyListener
в
c
L)
E
E
G
H
I
J
К
L
M
X
()
P
Q
R
S
T
C
V
W
Syntax
public interface Keylistener extends EventListener
Description
When an object (listener) wishes to receive key e\ents from a component (the source compo-
nent), two things must be done:
1. The listener must implement the KeyLi stener interface and all of the methods it
requires.
2. l he listener must be registered with the source component. It becomes registered by call-
ing the source component's addKeyLi stenerO method.
bor more information about key events, see KeyEvent.
X
Y
7.
952
rvty 1ЛЭ1СПС1
keyPressedt)
java.awt .event
№ BER SUMMARY
Key Event Callhack Methods
key Pressed О Called when a key on the keyboard is pressed.
keyRel eased() Called when a key on the keyboard is released.
keyTyped() Called when a pressed key or key coni bi nation generates a key
character.
See Also
java.awt.Component.addKeyListenerO > java.util.EventListener, KeyAdapter,
KeyEvent.
Example
See the KeyEvent class example.
keyPressedO
PURPOSE Called when a key on the keyboard is pressed.
SYNTAX public void keyPressedfKeytvent evt)
DESCRIPTION This method is called if the source component has the focus and a key is pressed on the keyboard. The identity of the key that was pressed can be retrieved by calling evt.getKeyCodeO. If the system supports autorepeat, this method is called each time the key is repeated. See the KeyEvent.KEY-PRESSED for more details about key pressed events.
PARAMETERS evt The non-null key event.
EXAMPLE See the KeyEvent class example.
keyReleasedO
purpose: Called when a key on the keyboard is released.
SYNTAX public void keyReleased(KeyEvent evt)
DESCRIPTION This method is called when a key is released. The identity of the key that was released can be retrieved by calling evt. getKeyCodeO. See KeyEvent .KEY_RELEASED for details about key released events.
i
java. awt.event
KeyListener
keyTypedf)
PARAML-1 t RS
evt The non-null key event.
EXAMPLE See the KeyEvent class example
B keyTypedO
Pl RPOSI. Called when a pressed key or key combination generates a key character.
D SYNTAX public void keyTyped(Keyfvent evt)
E DI -.SCRIPT ION F T his method is called when a pressed key or key combination produces a key character. If the platform supports autorepeat, this method is called each time
Ц the kev character is repeated. See KeyEvent.KEY.TYPED for details about key typed events.
PARAMETERS * evt J EXAMPLE The non-null key event. See the KeyEvent class example.
L
N
()
P
Q
R
S
T
U
V
X
Y
Z
954
Syntax
public class Label extends Component
Description
A label is a component that displays a single line of
text. The text can be modified by the program at any
time but can never be modified by the user. A label is
typically used in conjunction with other components
that do not have labels, such as text Fields and lists.
FIGl'RE 235: Label.
Label Alignment
A label has an alignment mode that controls the placement of the label’s text in relation to the
label’s bounds. The text is always vertically centered hut can be horizontally aligned to the
left, center, or right.
Events
The label fires the same events as a component. See the Component class for more details.
Label
java.awt
MEMBER SUMMARY
Constructor Label() Constructs a new Label instance.
Alignment Mode Constants
CENIE.R LEFT RIGHT Specifies center alignment. Specifics left alignment. Specifies right alignment.
! Property Methods getAli gnment() getText() setAlignmentO setTextQ Retrieves the label's alignment. Retrieves the label's text. Sets the label’s alignment. Sets the label's text.
Peer Method addNoti fy() Creates the label's peer.
Debugging Method paramStri ng() Generates a string representing the label's stale.
Example
This example creates a label to serve as a status bar. The status bar displays mouse motion
event information while the cursor is inside the frame's paintable area (see f igure 235).
import java.awt.*;
import java.awt.event.* ;
public class Main extends Frame {
Label statusBar = new Label();
Main О {
super(“Label Example”);
add(statusBar, BorderLayout.SOUTH);
addMouseMotionLi stener(new MouseMotionEventHandler());
setSize(200, 200);
show() ;
}
class MouseMotionEventHandler extends MouseMotionAdapter {
private void updateStatus(MouseEvent evt) {
String status - ,‘(“+evt.getX()+’\” + evt.getY()+’') “;
if (evt.isControlDownQ) status
if (evt.isShiftDown()) status ♦ = “S”;
if (evt. i sMetaDownO) status +- “M”;
if (evt.isAltDown()) status ».- “A”;
956
J U v Cl. Ll V\ I
addNotify()
} statusBar.setText(status); } public void mouseMoved(MouseEvent evt) { updateStatus(evt); } public void mouseDragged(MouseEvent evt) { updateStatus(evt); }
static public void mai n (Stri ng [J args) {
new Mai n();
}
}
addNotify()
purpose: Creates the label's peer.
SYNTAX public void addNotify()
DESCRIPTION This method creates the label's peer if it does not exist. The peer is created by calling the Toolkit.createLabel () method. This method should never be called directly. It is normally called by the parent.
OVERRIDES Component .addNotifyO-
SEE: ALSO Component, Toolkit.
CENTER
PURPOSE The alignment mode specify ing center alignment.
SYNTAX public static final int CENTER
DESCRIPTION In center-alignment mode, the text is displayed in the center of the label.
EXAMPLE'. See setAl ignment().
getAlignment()
PURPOSE Retrieves the label's alignment.
SYNTAX public, int getAl i gnment()
returns The label's alignment. The return value is one of LEFT, CENTER, or RIGHT.
SEE ALSO setAl ignmentQ.
example See setAlignmentO.
Label
java.awt
gelTcxU)
getTextf)
Pk RPOSL. Retrieves lhe label's text.
SYNTAX public String getTextQ
A RETURNS A non-nul 1 string containing the label's text.
В SI-F ALSO setlextQ.
C EXAMPLE; Sec set I extО.
D
i: F Ci Labelf)
Pl RPOSF Constructs a new Label instance.
H I SWT AX public LabelO public label(String text) public Label(String text, int alignment)
J DE;S('RIPI ION The three forms of this constructor create a new Label instance w ith the string
К text and the alignment alignment. If label is null or not specified, it defaults to ”” (an empty string). If alignment is not specified, it defaults to LEFT.
M PARAML I L.RS
N ali gnment The label's alignment. It must be one of If FT CENTER, or RIGHT.
() text The string containing lhe label's text.
P EXAMPLE See the class example.
Q
R LEFT
S Pl RPOSE. The alignment mode specifying left alignment.
Г SWI AX public static final int LEFT
L DESCRIPTION In left-alignment mode, the left edge of the text is pinned to the left edge of the
V label.
W EXAMPLE; Sec setAl i gnment О -
X
V paramStringO
z Pl R POSE- Generates a string representing the label's state.
S'» Nl AX protected String paramStringO
958
RIGHT
description The returned string includes the label’s alignment and text. A subclass of (his class should override this method and return a concatenation of its state with the results of super.paramStringO. This method is called by the toStringO method and is typically used for debugging.
RETURNS A non-nul 1 string representing the label's state.
OVERRIDES Component.paramStri ng().
SEE ALSO Object.toStri ng().
example See Component.paramString().
RIGHT_____________________________________________________ _
purpose The alignment mode specifying right alignment.
SYNTAX public static final int RIGHT
description In right-alignment mode, the right edge text is pinned to lhe right edge of the
label.
example See setAl ignmentQ.
setAlignment()
PURPOSE Sets lhe label's alignment.
syntax public synchronized void setA1ignmentfint alignment)
DESCRIFI ION This method sets the label’s alignment to be alignment.
PARAMETERS alignment The label's new alignment. It must be one of LEFT, CENTER, or RIGHT
EXCEPTIONS
IllegalArgumentException
If alignment is not one of the values LEFT CENTER, or RIGHT
SEE ALSO
example
getAli gnmentO.
This example creates a label and a
checkbox group. Use the checkbox
group to change the label’s align-
ment. See Figure 236,
FIGURE 236: Label. setAl ignmentO .
Label
java.au t
setTexK)
import java.awt.-;
import java, awt. event ;
class Main extends Frame
implements ItemListener {
String[] alignLabels =
A {“LEFT”, “CENTER”, “RIGHT”};
int[] alignValues =
В {Label.LEFT» Label.CENTER, Label.RIGHT};
Label 1 = new Iabel(“CENTER”, Label.CENTER);
D
E
E
H
1
J
К
M
N
О
P
Q
R
S
T
V
W
X
Y
Z
Main() {
super(“setAlignment Example”);
CheckboxGroup eg = new CheckboxGroupO ;
Panel p * new Panel(new GridLayout(3, 0));
for (int i=0; i<alignLabels.length; i++) {
Checkbox cb = new Checkbox(alignLabels[i], eg,
1 .getAlignmentO == alignValues[i]);
cb.addltemListener(this);
p.add(cb);
}
add(p, BorderLayout.SOUTH);
add(l , BorderLayout.CENTER);
pack();
show();
public void itemStateChanged(Itembvent evt) {
String target = (String)evt .getltemO ;
for (int i=0; i<alignLabels.length; i++) {
if (alignLabels[i].equals(target)) {
1.s etAlignment(alignValuesLi]);
1.s etText(alignLabelsLi]);
return;
}
}
}
static public void mai n(Stri ng[] args) {
new Main() ;
}
U
setText()
purpose Sets the label’s text.
syntax public synchronized void setText(String label)
description This method sets the label’s text to be the string label. If label is null,
treated like an empty string
960
setText(:
Note that the minimum and preferred sizes of the label may change, so it may
be necessary to resize the label. The example shows how to cause the label's
parent to resize the label.
PARAMETERS label The siring specifying the label's new text. The value may be null.
SEE AUSO EXAMPLE getTextO. This example creates a label and a text field. Pressing Return while in the text field causes the label's text to be set to
Iset!ext Example flIFI£3]
the contents of the text field. When the text changes, so does its minimum size. This example also shows how to cause the label's parent to properly resize the label. See Figure 237. j New Label ’
FIGURE 237: Label. setTextO .
import java.awt.*;
import java.awt.event;
class Main extends Frame implements ActionListener {
Label 1 = new Label("Iabel");
TextField tf - new textField(40);
MainQ {
super(“setText Example”);
addfnew CanvasO, BorderLayout .CFNTER) ;
add(l , BorderLayout.WEST);
add(tf, BorderLayout.SOUTH);
tf. setText(l. getTextO); // init with current text
tf.addActionListener(thi s);
pack();
show():
}
public void actionPerformedfActionFvent evt) {
1. setText(tf .getTextO) ;
// the size has changed so get parent to validate itself.
1. invalidateO ;
1.getParent О.vali dateО;
}
static public void main(String[l args) {
new Mai n();
}
}
java.awt.peer
LabelPeer
A
В
I)
rt^*
E
F
G
H
J
J
К
M
Syntax
public interface LabelPeer extends ComponentPeer
N
О
p
0
R
T
i:
Description
The label component (see the Label class) in the AWT uses the platform s native implementa-
tion of a label. So that the AWT label behaves the same on all platforms, the label is assigned a
peer, whose task is to translate the behavior of the platform's native label to the behavior of the
AWT label.
AWT programmers normall)' do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
See Component and Toolki t for additional information about component peers.
MEMBER SUMMARY
Peer Methods
setAIignment() Sets the label's alignment.
setText О Sets the label s text.
962
J« VU.UVVl.pVLl
setAlignmenK)
See Also
java.awt.Component, java.awt.Label, java.awt.Toolkit.
setAlignment()
PURPOSE Sets the label’s alignment.
SYNTAX void setAlignmentfint alignment)
PARAMETERS alignment The label's new alignment.
SEE ALSO j ava.awt.Label.setAli gnment 0.
setText()
purpose: Sets the label’s text.
syntax void setFext(String label)
PARAMETERS label The string specifying (he label’s new text. The value may be null.
SEE ALSO java.awt.Label . setTextO-
java.awt
LayoutManager
( LayoutManager
Syntax
public interface LayoutManager
()
out
the
LEFT
FlowLayout Example
RIGHfll
МптшагеаайЯ
Description
A layout manager is responsible for laying
components in a container. For example.
FlowLayout layout manager places the compo-
nents in a left-right, top-down fashion. Figure 238
shows an example of a container with the Flow-
Layout layout manager.
Typically, a newly created container has a
default layout manager For example, the default lay -
out manager for the Panel container is FlowLay-
out. The layout manager for a container can be
changed by calling Contai ner. setLayoutQ. but deciding when it is safe to call this method
is left to the layout manager. In general. any layout manager that maintains some stale, such as
lhe gridbag and border layout managers, can be safely set only when the container contains no
components.
center! 4 I 5 I
макшжжмммашЛ uimmmmI 4MMM
FKJI RE 238: FlowLayout.
N
Q Container Validity
R A container's layout manager is invoked only if the container is invalid. A container automati-
cally becomes invalid if lhe container is resized or if a child component has been added,
s removed, or moved within the container. The system automatically calls the container's layout
p method if the user resizes the top-level w indow. However, if a container must be laid out again
(perhaps because some layout parameter has changed). Component, invalidate О must be
called on the container first, followed by Component.validate().
V
w ‘"“‘X
When implementing lhe methods that return dimensions, you must always take into account
X lhe container's insets. That is. the components must be laid out within the area defined by the
Y container's insets. Sec the Contai ner class for a description of insets.
964
MEMBER SUMMARY
Layout Manager Methods addLayoutComponent() 1ayoutContai ner() removeLayoutcomponent() Adds a component to the lax out. Lays спи the container in the specified panel. Reinoxes the specified component from the layout.
Dimension Methods minimumLayoutSi ze() Calculates the minimum size dimensions for the specified component.
preferredLayoutSi ze() Calculates the preferred size dimensions for the specified component.
See Also
BorderLayout, CardLayout, FlowLayout, GridBagLayout, GridLayout,
LayoutManager?.
Example
This example implements a layout manager that displays components in a horizontal or verti-
cal list. See Figure 239. The name of the component specifies how the component should be
stretched in the list. If the name is the component will be stretched in both directions. If
the name is “v". the component will be stretched only in the horizontal direction. If the name is
"h‘\ the component will be stretched only in the vertical direction. If the name is null or some
other string, the component will not be stretched.
(a i Vertical List
i b) Horizontal List
FIGI RL 259: Vertical and Horizontal List Layouts.
LayoutManager
java.awt
import java.awt.";
import java .util.*;
class Main extends Frame {
Main(boolean vertical, String title) {
super(ti tie);
setLayout(new Г1exLayout(vertical, 2));
add(new Button(“one”));
addC’h”, new ButtonCtwo”)) ;
add("*", new But ton C‘three”));
add(new Button(“four”));
setSize(100, 200);
show();
public static void rrain(String args'L]) {
new Main(true. ‘‘LayoutManager Example 1”);
new Main(false, "LayoutManager Example 2”);
}
}
class Flexl.ayout implements LayoutManager {
int gap;
boolean ver;
Hashtable comps - new Hashtable();
public Flexlayout(boolean v, int gap) {
ver = v;
this.gap = gap;
}
public void addiayoutComponent(String name, Component comp) {
comps.put(comp, name);
}
public void removeLayoutComponent(Component comp) {
comps.remove(comp);
}
public Dimension 1ayoutSize(Container parent, boolean minimum)
Insets insets - parent.getlnsetsO;
int w = 0, h = 0, n;
// Crab tree lock to make sure components are not removed v
// getting their sizes
synchronized (parent.getTreeLockQ) {
n = oarent.getComponentCountO;
for (int i-0; i<n; i++) {
Component c = parent.getComponentO);
Dimension d = minimum ? c.getMinimumSize() :
c.getPreferredSizeO;
if (ver) {
w - Math.max(w, d,width);
h -»-= d.height;
} else {
w += d.width;
h - Math.max(h, d.height);
}
966
java.awt
Lay out.VI ai
}
}
if (n > 0) {
if (ver) {
h +=- (n-l)*gap;
} else {
w -h= (n-l)*gap;
}
}
return new Dimension(insets.left ♦ insets.right * w,
insets.top + insets.bottom * h);
}
public Dimension minimumlayoutSize(Container parent) {
return 1ayoutSizefparent. true);
}
public Dimension preferredLayoutSi7e(Container parent) {
return layoutSize(parent, false);
}
public boolean isFlexible(Component c, boolean v) {
String name = (String)comps.get(c);
if (name == null) {
return false;
} else if (name.equa 1 sC’")) {
return true;
} else if (v) {
return name.equa1s(“v");
}
return name.equals(“h");
}
public void layoutContainer(Container parent) {
Insets insets = parent.getlnsetsO;
Dimension dim - layoutSize(parent, false);
// Grab tree lock to make sure components are not removed while
// laying them out.
synchronized (parent.getTreel ock()) {
intn- parent.getComponentCount();
int flexCnt - 0;
int extra = 0;
int add = 0;
for (int i-0; i<n; i ♦ ♦) {
if (i sFlexible(parent.getComponentO), ver)) {
f lexCnt++;
}
}
if (flexCnt > 0) {
if (ver) {
extra - parent.get SizeO . height dim. height;
} else {
extra =- parent.getSize() .width dim.width;
}
add = extra/flexCnt;
LayoutManager
java.awt
if (ver) {
int у insets.top;
for (int i-0; i<n; in) {
i nt x =7 i nsets.left;
Component c = parent.getComponent(i);
String name *- (String)comps.get(c);
Dimension d = c.getPreferredSize();
if (i sFlexi bl e(c , ver)) {
d.height add;
extra -- add;
if (extra < 0) { // adjust for round off error
d.height extra;
}
1
if (isFlexible(c, !ver)) {
d.width = parent.getSize().width -
insets.left - insets.right;
} else {
x = (parent.getSize().width - d.width)/2;
}
c.setBounds(x, y, d.width, d.height);
у d.height + gap;
}
} else {
int x - insets.left:
for (int i-0; i<n; i++) {
int у = insets.top;
Component c - parent.getComponent(i);
String name = (String)comps.get(c);
Dimension d = c.getPreferredSize();
if (i sFl exi bl e(c , ver)) {
d.width -= add;
extra — add;
if (extra < 0) { // adjust for round off error
d.width += extra;
1
}
if (isFlexible(c, !ver)) {
d.height - parent.getSize().height --
insets.top - insets.bottom;
} else {
у = (parent.getSizeO.height - d.height)/?;
}
c.setBounds(x, y. d.width, d.height);
x +- d.width + gap;
}
}
}
}
public String toStringO {
return getClassO .getNameO + “[ver=” t ver + ll,gap~’' + gap +
}
1
968
Layout ма па;
add I .ay ou tComponer
java.awt
addLayoutComponentt)
PVR POSE Adds a component to the layout manager's list of components.
SYNTAX void addLayoutComponent(String name, Component comp)
DESCRIPTION When a component is added to a container along with an accompanying name (i.e.< the Container.add(String, Component) method is called), the con- tainer not only adds the component to its list of components but also calls this method with the component and its name. I’he container does not call this method if the component is added without a name (nul 1 is a valid name). The container does not use the component name at all. Nor does it remember lhe name. So this method must maintain the name-component association if neces- sary. The name is. more accurately, layout information that the layout manager uses to place lhe component. I he name does not have to be unique. Nor does it have to be non-nul 1 it's up to the layout manager to decide what is a valid name. For example, in the BorderLayout layout manager, the name determines at which edge lhe component should be placed. Using the name "North" causes the component to be placed against the top edge of the container. BorderLayout expects the names of the components to be chosen from a fixed set of names and to be unique; the results are undefined if this rule is violated. By the time this method is called, comp is already added to the container and a peer is created if necessary. Note that the Container class does not include an add() method in which both the name and a position can be specified. To work around this deficiency, you can first insert lhe component without an accompanying name and then call addLayoutComponentO directly lo assign a name lo the component.
PARAMETERS comp name The non-nul 1 named component that has just been added to the container. A possibly null string specifying the name of the component.
SEE ALSO Container.add(), LayoutManager?.addLayoutComponent().
example See the class example.
layoutContainer()
purpose: Lays out the components in a container.
syntax . void 1ayoutContainer(Container cont)
DESCRIPTION This method is called by the container's parent to lay out the components in cont. The size of cont can be retrieved by calling cont.getSize(). which
java.awt
LayoutManager
minimum La\oulSize()
will include the container’s insets. The components should be laid out using Component.setBounds() and placed inside the area defined b\ the insets. When the dimensions of a component are retrieved, the componenTs preferred size should be used.
PARAMETERS cont The non-null container using this layout instance.
EX.AM 1*1 t See the class example.
pi к post : Calculates the layout's minimum size dimensions.
SYNTAX Dimension minimumLayoutSize(Container cont)
DESCRIPTION This method calculates the minimum size dimensions for the container cont. I’he minimum sizes of the components arc used in the calculations. I'he result includes the container's insets.
PARAMEIERS cont Ihe non-null container using this layout instance.
RETt RNS The non-null dimension containing the container's preferred size.
SEE ALSO Component.getMi nimumSizeQ * LayoutManager2 .maximumLayout SizeO . preferred! ayoutSizeQ.
EXAMPL 1 See the class example.
preferredLayoutSize()
Pl'RPOSL Calculates the layout's preferred size dimensions.
SX NT AX Dimension preferredLayoutSizefContainer cont)
DESCRIPTION This method calculates the preferred size dimensions for the container cont. I he preferred sizes of the components are used in the calculations. I'he result includes the container's insets.
PARAMETERS cont The non-null container using this layout instance.
RFTLRNS I he non-null dimension containing the container's preferred size.
SEE Al SO Component.getPreferredSi ze(), LayoutManager2.maximum!ayoutSize(), minimumLayoutSize().
EXAMPLE See the class example.
970
IjUJ VUliHUllU^Vl
remove I .ay outComponentf
. removeLayoutComponentf)
PURPOSE Removes a component from the layout manager s list of components.
SYNTAX void removeLayoutComponent(Component comp)
DESCRIPTION This method is called by a container whenever a component is removed from the container, regardless of whether the component was named. ?\t the time this method is called, comp is not yet removed from the container.
parameters comp The non-null component about to be removed from the container.
EXAMPLE See the class example.
java.awt
LayoutManager2
'^ИИИ1«Р«тИЖяИИвИИ»Ш«И^в^Ии1
A -0"*^^ I* ! -_ _ _ -II I
B ' — . I
c
r) Syntax
P public interface LayoutManager? extends LayoutManager
F
Description
(l This interface is an extension of LayoutManager that adds a few new methods to support
H alignment-based layout. These methods really belong in LayoutManager; they were not added
j so as to maintain compatibility with LayoutManager in Java 1.0. If they were included, all
layout managers would fail to load in the Java 1.1 runtime because they would lack implemen-
J tations for them. New* layout managers should implement LayoutManager? rather than Lay-
K outManager.
The Alignment Point on Components
M A component has an alignment property that specifies an alignment point on lhe component.
By default, the alignment point is the component's center. It is a value that affects how some
layout managers do their layout. How a layout manager uses the alignment property differs by
О manager. For example, one type of layout manager could draw lines between the alignment
p points. Another could overlap all of its children so that their alignment points are coincident.
Some may completely ignore the alignment property.
Q The alignment property is a pair of floating-point values—one that specifies the v-align-
R inent and one that specifies the v-alignment. Together, the values specify the alignment point.
s In particular, the alignment point on a component c is
T (x_alignment - c.width, у alignment " c.height)
U The alignment values lie in the range 0.0 to 1.0. For example, an alignment value of (0.0,
0.0) specifies the top-left corner of the component, while an alignment value of (0.5. 0. 5)
specifies the center of the component. Notice that the alignment point cannot be outside the
w bounds of the component.
X Note: In Java 1.1.2. none of the AWT layout managers use a component's alignment prop-
erty vet.
Y
7 The Alignment Point on Containers
The alignment point for a container is determined by its layout manager. A layout manager
may return a constant alignment point value, which is usually (0.5. 0.5). Or it first may need
972
java.awl
1 ,<1 VUULLVlUJlcl^Ul
to lay out its children before it can determine (he alignment point value. For instance, the lay
out manager in the class example places all of the components so that their у alignment coordi-
nates are colinear. This line determines the y-alignmem value of the layout manager and of the
container. The layout manager cannot determine the location of this line until it has laid out all
of the components and adjusted its height so that all of the components are fully visible.
Setting Alignments
There are no methods for setting the alignment properly. For a component to change the
default alignments, it must override the "gel alignment” methods and return the desired results.
This means that you cannot change a component’s alignment: the component must do it itself.
If the ability to change the component’s alignment is necessary, the component needs to pro-
vide its own "set alignment” methods.
MEMBER SUMMARY
Layout Manager Methods addLayoutComponent() i nvali dateLayoutО Adds a component to the layout manager's list of components. Invalidates the layout manager.
Alignment Methods getLayoutAl i gnmentXO getLayoutAli gnmentY() Calculates the layout manager's л-alignment value. Calculates the layout manager's у-alignment value.
Dimension Method maxi mumLayoutSi ze () Calculates the layout's maximum si/e dimensions.
See Also
Component, Containert LayoutManager.
Example
This example implements a special component that simply paints lhe word "java." The com-
ponent can paint the word in different point sizes. By clicking lhe component with the left
mouse button (button 1). you can increase the point size of the font: clicking with the right
mouse button (button 3) decreases the point size. The size of lhe component is exactly the
dimensions needed to display the string in the current point size (plus a half of a space charac-
ter on the left and right side of the string).
The component also has an alignment value that is based on the string in its current point
size. In particular, the л-alignment is always 0.5, but its v-alignment is such that it matches the
font’s baseline (see FontMetri cs). For example, if the baseline is two-thirds from the top, the
LayoutManager!
ja\ a.aw l
\-alignment would be 0.67. To help you see the baseline, the component draws a line on its
baseline.
A
В
('
I)
I.
F
G
H
1
J
К
This example also implements a layout manager that la\s out its children horizontally. like
the flow layout manager does. Howe\er. it uses the component's v-alignmenl property to align
the components \erticallx so that the \-coordinates of their alignment points are colinear See
Figure 240. The preferred w idth of the la\oul manager is the total w idth of the components.
The preferred height is the height necessary for all of the components to be \ isible after their \-
alignment points ha\e been lined up.
The laxoiit
manager's y-
alignment xalue is
determined by
the location of
< LayoutManager/ Example
java java java java J.2LV a java jm java jm
the baseline after 1 k;i ri: 240: Baseline-aligned C omponents.
the component's
v-alignmcnl points ha\c been lined up. If the fonts used in all of the components arc the same
(as in this example), then (he y-alignmenl of the layout manager is essentially the same as that
of the component with the largest point si/e. This means that if you nest containers using this
la\ out manager, all of the components will line up. no matter what containers lhe\ arc in. This
example demonstrates this b_\ nesting a container of components.
M
N
О
P
Q
R
S
I
I
\
w
X
Y
To sec dif ler-
cnl types of align-
ments. you can
change a compo-
nent's alignment
b\ clicking it
when the Shift
key is held down.
This changes the
alignment from
< LayoutManager? Example
жж
iava ,ava, . lavagW-
java jaxa*
I K-l RE 241: lop- and Bottom-aligned Components.
baseline, to center, to top. and then to bottom. Figure 241 shows the components alternating
between top and bottom alignment.
Finally, the component is made focus-tra\ersable (see Component.isFocusTravers-
ableQ) (for no particular reason except for demonstrate c purposes). Pressing the Tab or
Shift-lab keys mo\es the focus from one component to the next. Notice (hat when the locus
reaches the container, the locus is gi\en to a component inside the container.
import java.awt."':
i mport j ava. awt. event. ;
class Main extends Frame {
Main О {
super(“LayoutManager? Example");
setLayout(new TextFlowLayout());
974
java.awt
// Add a few of our special labels,
for (int 1=0; i<3; i++) {
' add(new LabelComponent(“java”, 20*2*i));
r
'' // Now add a container with a few of our special labels.
, Panel p = new Panel (new TextFlowLayoutO);
p.$etBackground(Color. green) ;
for (int i-0; i<3; i4+) {
p.add(new LabelComponentC java” , 30*2*i));
}
add(p);
// Add a few more special labels.
for (int i=0; i<3; i+ч-) {
add(new Label Component(“java”r 10+2*i));
}
pack();
showO;
}
public static void Tain(String[Z args) {
new Mai n();
}
}
class TextFlowLayout implements LayoutManager2 {
// If < 0, the layout is invalid.
int maxAscent = -1;
int maxDescent = 0;
// type=0->minimum, type=l->preferred, type=2->maximum.
public Dimension layoutSize(Container cont, int type) {
Insets insets - cont .getlnsetsO ;
int w = 0;
// Grab tree lock to make sure components are not removed while
// getting their sizes
synchronized (cont.getTreel ock()) {
Dimension d - new Dimension^, 0);
maxAscent = 0;
maxDescent = 0;
for (int i=0; i<cont.getComponentCountО; i+*) {
Component c = cont .getComponentO ):
switch (type) {
case 0*.
d = c.getMinimumSizeO ;
break;
case 1:
d = c.getPreferredSizeO ;
break;
case 2;
d = c.getMaximumSizeO ;
break;
L >
LayoutManager!
jaxa.awt
int a = (int)(c.getAlignmentY()”d.height);
maxAscent - Math,max(maxAscent, a);
maxDescent = Math,max(maxDescent, d.height-a);
w -- d.width;
}
}
return new Dimension^’nsets.left + insets.right + w,
insets.top t insets.bottom ч maxAscent+maxDescent);
}
public Dimension minimumLayoutSize(Container cont) {
return layoutSize(cont, 0);
}
public Dimension preferredLayoutSize(Container cont) {
return layoutSize(cont, 1);
}
public Dimension maximumLayoutSize(Container cont) {
return layoutSize(cont, 2);
}
public void layoutContainer(Container cont) {
Insets insets = cont.getlnsetsO;
if (maxAscent < 0) {
1ayoutSize(cont, 1);
)
// Grab tree lock to make sure components are not removed while
// laying them out.
synchronized (cont. getTreeLockO) {
int x - insets.left;
for (int i-0; i<cont.getComponentCountO; i++) {
Component c = cont.getComponent(i);
Dimension d = c.getPreferredSize();
c.setBounds(x T
insets, top (int)(maxAscent-d.height*c.getAlignment’
d.width, d.height);
x += d.width;
}
}
}
public float getLayoutAlignmentX(Container cont) {
return 0.5f;
public float getLayoutAlignmentY(Container cont) {
if (maxAscent < 0) {
layoutSize(cont, 1);
}
if (maxAscent > 0) {
return (float)maxAscent / (float)(maxAscent+maxDescent);
}
return 0.5f;
}
public void invalidate!ayout(Container cont) {
maxAscent = -1;
}
// These methods are not used.
976
java.awt
Layout [Vi an
F"
public void addLayoutComponent(String name, Component comp) {
}
public void addLayoutComponent(Component comp, Object constraints) {
}
public void removeLayoutComponent(Component comp) {
}
}
class Label Component extends Canvas {
String label;
Font font;
FontMetrics fontM;
boolean hasFocus - false;
int curAlignment = 0;
float[] alignments = { 1.0f, // baseline alignment
Component.CENTER„ALIGNMENT,
Component.TOP ALIGNMENT,
Component. BOTTOM..ALIGNMENT} ;
LabelComponent(String label, int size) {
this.label = label;
font = new Font (“Serif", Font.PLAIN, size);
fontM = getFontMetrics(font);
// Listen for mouse events.
addMouseListener(new MouseEventHandlerO);
addFocusListener(new FocusFventHandler());
}
public float getAl ignmentYO {
if (alignments[curAlignment] == 1.0f) {
return (float)fontM.getAscentO / (float)fontM.getHeight();
} else {
return alignments[curAlignment};
}
}
public Dimension getPreferredSize() {
int space = fontM. charWidthC *);
return new Dimension(space 4 fontM.stringWidth(label),
fontM.getHeight());
}
public void paint(Graphics g) {
if (hasFocus) {
g.setColor(Col or.pink);
} else {
g.setColor(Color.1i ghtGray);
}
g.fillRect(0, 0, getSize().width, getSize()-height);
g.setColor(Col or.black);
// The following isn't necessary in a native component,
g.setFont(font);
FontMetrics fontM = g.getFontMetrics();
g.drawString(label, fontM.charWidth(‘ ‘)/2, fontM.getAscent());
// Draw baseline.
g.drawLine(0, fontM.getAscentO , getSizeO .width, fontM.getAscent()) ;
I .ayout M a n a ger 2
ja\u.a\41
A
В
C
D
E
f;
G
H
1
J
К
M
N
О
J’
Q
R
S
T
г
1
public boolean isFocusTraversableO {
return true;
}
class MousetventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
int inc = 0;
if (evt. i sShi ftDownO) {
// Change the alignment.
curAlignment - (curAlignment + 1) % alignments.length;
} else if ((evt.getModifiersO & Inputbvent.BUTTONS .MASK) != 0) {
// Decrease the font size.
if (font.getSize() > 6) {
inc = -1;
}
} else {
// Increase the font size,
inc = 1;
}
font - new Font(font.getF’ami 1 y() , font.getStyle(),
font. getSizeO * inc);
fontv _ getFontMetrics(font);
// Invalidate current component and validate the entire frame.
invalidateO ;
// Find the top-level window.
Component c getParentO;
while (c != null) {
if (c instanceof Window) {
break;
}
c - c.getParent();
V
w
X
Y
Z
// Validate the whole tree.
if (c ! = null) {
c .validateO ;
}
requestFocusO ;
repai nt();
}
}
class FocusEventHandler extends FocusAdapter {
public void focusGained(FocusFvent evt) {
hasFocus - true;
repai nt О;
}
public void focusLost(FocusFvent evt) {
hasFocus - false;
repai nt() ;
}
}
978
java.awt
addLayoutComponent)
addLayoutComponent)
! purpose Adds a component to the layout manager's list of components.
i SYNTAX void addLayoutComponent(Component comp, Object constraints)
description When a component is added to a container along with an accompanying con-
straint object (in other words, the Container .add(Component, Object)
method is called), the container not only adds the component to its list of com-
ponents but also calls this method with the component and its constraints. The
container does not use or remember the constraint object at all. so this method
must maintain the component-constraint association if necessary.
The constraint is. more accurately, layout information that the layout manager
uses to place the component. There is no special constraint class from which
all constraints are derived. Instead, lhe constraint is an object that is specific to
the layout manager. For example, the gridbag lay out manager (see GridBag-
Layout) understands only constraints that are gridbag constraint objects (see
GridBagConstrai nts).
By lhe time this method is called, comp is already added to the container and a
peer is created if necessary.
The layout manager does not need to invalidate its layout, since the container
will have called i rival idateLayout().
PARAMEIERS
comp The nonmull component that has just been added to the container.
constraints A possibly null constraint object that is specific to this layout manager.
SEE also Container.addf), LayoutManager.addLayoutComponentO-
example See the class example.
getLayout AlignmentX()
purpose Calculates the layout manager’s л-alignment value.
syntax public float getLayoutAlignmentX(Container cont)
descrip i ion The returned alignment value may be a constant, or it may depend on how' the
components are laid out. The returned value becomes the container's л'align-
ment value. See the class description for more information.
paramin RS
cont The non-nul 1 container using this layout instance.
returns A float in the range 0,0 to 1.0.
java.awt
LayoutManager!
getLayoutAlignmeniYf)
SI E Д1 SO Component. getAl 1 gnmentXO , Contai ner. getAl i gnmentXO * getLayoutAl i gnmentYQ.
EXAMPLE See the class example.
getLayoutAIignmentY()
PURPOSE Calculates lhe layout manager's y-al ignment value.
SYNTAX public float getLayoutAlignmentYfContainer cont)
DESCRIPTION The returned alignment value may be a constant, or it may depend on how the components are laid out. The returned value becomes the container's v-align- ment value. See the class description for more information.
PARAMETERS cont The non-null container using this layout instance.
RFTl RXS A float in the range 0.0 to 1.0.
SEE ALSO Component .getAlignmentYO , Container.getAlignmentY() , getLayoutAl i gnmentXO.
EXAMPLE See the class example.
invalidateLayoutO
PURPOSE Invalidates the layout manager.
SYNTAX public void invalidateLayout(Container cont)
DI SC RIPTIOX This method is called whenever the container cont is invalidated. This method would be useful if the layout manager kept some state about (he layout of (he components. It might do this for performance reasons. This method would inform the layout manager that this state should no longer be used. Therefore it should recompute the layout or size the next time the layoutContainerO method or the layout size methods are called.
PARAMET ERS cont The non-null container using this layout instance.
SEE Al.SO LayoutManager.layoutContai ner().
EXAMPLE See the class example.
980
Г JdVd.dWl
maximumLayouiSizet
f, maximumLayoutSizeO
&>._________________________________—--------------------------------------
PURPOSE Calculates the layout's maximum size dimensions.
SYNTAX public Dimension maximumLayoutSize(Container cont)
DESCRIPTION This method calculates the maximum size dimensions for the container cont. The maximum sizes of the components are used in the calculations. The result includes the container's insets.
PARAMETERS cont The non-null container using this layout instance.
RETURNS The non-null dimension containing the container's maximum size.
SEE ALSO Component.getMaximumSizeO T Container, LayoutManage r.mi ni mumLayoutSi ze 0, LayoutManager.preferredLayoutSize().
EXAMPLE See the Component class example.
java. awt. peer
LightweightPeer
A
В
C
D
E
F
(1
H
I
J
К
M
Syntax
public interface LightweightPeer extends ComponentPeer
N Description
O So that an AWT component behaves the same on all platforms, the component is assigned a
peer, whose task is to translate the behavior of the platform s native component to the beha\ ior
of the AWT component. A lightweight component is a component that does not have a nati\e
Q peer. It is rendered to a representation in the native window ing system using the native peer of
R its first ancestor that has a native peer. A lightweight component is assigned a lights eight peer.
instead of a native peen to accept and propagate methods on the component to its native ances-
S tor.
T AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatical!) manage
their peers. Only someone who is porting the AWT to another platform or building new light-
v weight toolkits should be concerned with the peer classes and interfaces. Consequently, most
w peer documentation refers to j ava. awt counterparts.
* See Component and Toolkit for additional information about component peers.
Y See Also
Z java.awt.Component, j ava.awt.Toolki t.
982
J
java.awt
List
Syntax
public class List extends Component implements ItemSelectable
Description
The list component is a scrollable vertical list of string items. The
user can select an item from the list. See Figure 242.
Selection Modes and Selected Items
The list component can be in either single- or multiple-selection
mode. When it is in single-selection mode, only one item can be
selected at a time. When it is in multiple-selection mode, more
|Q A List ВИЗЕ
apple ▲
blueberry Hi
cantaloupe —1
durian ▼ 1
FIGI RE 242: List.
than one item can be selected at one time. The gesture by which a selected item is deselected
depends on the platform. For example, on Windows 95 a selected item is deselected by a click
on the selected item.
The List class provides methods to modify and retrieve the set of selected items.
Events
A list fires an item event whenever the user selects or deselects one of its item. The item of the
item event ic the newlv sdected/deselected item Even if the selected item is reselected. an
item event is fired, since the modifier keys may have changed. In single-selection mode, the
previously selected item does not fire an event indicating that it has been deselected. See
ItemEvent for more details on item events.
List
java.awt
A
В
A list fires an action event whenever the user double-clicks an item. The action command
of the action event is the item that was double-clicked. Sec ActionEvent for more details on
action events.
Л list also fires all of the events fired by the Component class. See the Component class
for details. See the AWTEvent class for details on how to filter or handle events.
В
Г
Cl
II
I
J
к
м
N
О
р
Q
R
S
т
с
V
W
X
Y
Z
MEMBER SUMMARY
Constructor
Li st C)
Visibility Methods
getVi si blelndexQ
makeVi si Ы e()
Item Methods
add ()
addltemO
delItem()
getltem()
getltemCountO
getltemsO
getRowsO
removeO
removeAl1()
replaceltemO
Selection Methods
deselectO
getSel ectedlndexO
getSel ect edlndexesQ
getSelectedltem()
getSelectedTtemsО
getSelectedObjectsО
i slndexSelectedQ
i sMultipleModeO
selectO
setMulri pleMode()
Event Methods
addActi onLi stenerO
addltemLi stenerO
processEventO
processActionEventО
Constructs a new List instance.
Retrieves the index of the item that was last made visi-
ble.
Scrolls this list so that an item is visible.
Adds an item to (his list.
Adds an item to this list.
Deletes an item from this list.
Retrieves an item from this list.
Retrieves lhe number of items in this list.
Retrieves the items in this list.
Retrieves the number of row s in this list.
Removes an item from (his list.
Removes all items from this list.
Replaces an item in this list.
Deselects an item in this list.
Retrieves the index of lhe selected item.
Retrieves the indexes of the selected item.
Retrieves this list's selected item.
Retrieves this list s selected items.
Retrieves this list’s currently selected items.
Determines whether the item al an index is selected.
Retrieves this list’s selection mode.
Selects an item in this list.
Sets this list's selection mode.
Adds a listener to receive action events fired by this list.
Adds a listener to receive item events fired by this list.
Processes an event enabled for this list.
Processes an action event enabled for this list.
984
ER SUMMARY
processItemEventO removeActi onLi stenerO Processes an item event enabled for this list. Removes a listener from receiving action events fired by this list.
removeltemLi stenerO Removes a listener from receiving item events fired by this list.
Layout Methods getMinimumSizeO getPreferredSi ze() Peer Methods addNotifyO removeNoti fyO Calculates the minimum dimensions of this list. Calculates the preferred dimensions needed for this list. Creates this list's peer. । Destroys this list's peer.
Debugging Method paramStringO Deprecated Methods allowsMultipi eSelections О clearO countitems delltemsO i sSelectedO minimumSizeO preferredSi ze() setMultipi eSelect ions() Generates a string representing this list's state. Replaced by isMulti pleModeQ. Replaced by removeAl 1 (). । Replaced by getltemCountO. Replaced hy multiple invocations of removeQ- Replaced by i slndexSelectedO. Replaced by getMi ni mumSi ze О Replaced by getPreferredSi zeQ. Replaced by setMul tipi eMode 0.
See Also
java.awt.event.ActionEvent, java.awt.event.ActionListener,
java.awt.event.ItemEvent, java.awt.event.ItemLi stener.
Example
Fora simple example using lhe list component, see the example for the ListO constructor.
The more elaborate example presented here creates two lists and several buttons for moving
items from one list to the other. See Figure 243. One or more items on either list can be
selected and then moved to the other list. Making a selection on one list automatically clears
all of the selections on the other list. Double-clicking an item adds an asterisk to the item s
name (this was done just to demonstrate the use of replacelteinO )
The > button moves the selected items in
the left list to the right list: the < button Joes
the opposite. The » button moves all of the
items in the left list to the right list: the « but-
ton does the opposite. The ! button deselects
the selected items and selects unselected items.
This operation is applied to the list that has al
least one selection. If neither list has an\ selec-
tions. this operation is ignored.
I'he example uses a grid bag la\out man-
ager (sec GridBagLayout) to la\ out the lists
and buttons. The center column is not given
an\ weight, so ihc first and last columns
stretch w ith the w indow.
I IGI RI 243: Moving Items between Lists.
import java.awt.’’;
import java. awt. event . ;
class Main extends Frame implements ActionListener, Iteml istener 1
final static int ITEMS = 10;
List ItList - new List(ITEMS, true);
List rtList = new List(0, true);
MainO {
super(“List Example”);
GridBaglayout gbl = new GridBagLayout();
set Layout(gbl);
add(ltList, 0, 0, 1, 5, 1.0, 1.0);
add(rtlist, 2, 0, 1, 5, 1.0, 1.0);
// Add action and item listeners to list
1tli st.addAct ionl i stener(t hi s);
ItList.addltemLi stener(thi s);
rt I i st.addActionListener(this);
rtLi st.addltemLi stener(this);
// Create buttons for adding/removing items from lists
Button b;
add(b - new Button(‘‘>”), 1, 0, 1, 1, 0, 1.0);
b.addAc t i onLi stener(t hi s);
add(b - new Button(“>>”), 1, 1, 1. 1, 0, 1.0);
b.addActi onLi stener(thi s);
add(b - new Button("<”), 1, 2, 1, 1, 0, 1.0);
b.addAc t ionl i s t ener(t h i s);
add(b - new Button("<<“), 1, 3, 1, 1, 0, 1.0);
b.addActi onLi stener(thi s);
add(b - new Button("!”). 1, 4, 1, 1, 0, 1.0);
b.addActionLi stener(this);
for (int i=0; i<ITEMS; i+e) {
1tLi st.add(”i tem “ + i);
}
pack();
show();
ju va.a wi
}
void add(Component comp,
int x, int y, int л, int h, double weightx, double weighty) {
GridBagLayout gbl = (GridBagLayout)getlayoutО;
GridBagConstraints c - new GridBagConstraints();
c.fill = GridBagConstraints.BOIH;
c.gridx = x;
c.gridy - y;
c.gridwidth = w;
c.gridheight h;
c.weightx - weightx;
c.weighty - weighty;
add(comp);
gbl.setConstraints(comp, c);
}
void reverseSelections(List 1) {
for (int i=0; i<1.getltemCountO ; ii*) {
if (1.islndexSelected(i)) {
1.dese1ect(i);
} else {
1.seiect(i);
}
}
}
void deselectAlI(List 1) {
for (int i-0; i<1.getltemCountO ; if*) {
1.deselect(i);
}
}
void replaceItem(List 1, String item) {
for (int i=0; i<1 .getltemCountO ; i++) {
if (1.getltem(i).equals(itern)) {
1.replaceltem(item + i);
}
}
}
void move(List 11, List 12, boolean all) {
if (all) {
for (int i-0; i<l 1.getltemCountO ; i++) {
12.add(ll.getltem(i));
}
11. removeA HO;
} else {
Stringf] items - 1l.getSelectedItems();
intfl itemindexes = 11.getSelectedlndexesO;
deselectAll(12);
for (int i-0; i<iterns.1ength; i++) {
12.add(iterns Гi]); // add it
12 . select (12 .getltemCountO-1) ;// and select it
if (i == 0) (
12 .makeVi si ble(l2 .qetlterr.Count () -1);
}
java.awt
List
add()
A
В
C
D
E
F
G
H
I
J
К
for (int i=itemlndexes.length 1; i>=0; i -) {
11. remove(i terrindexes [i 1) ;
}
}
}
public void actionPerformed(ActionEvent evt) {
String arg - evt. getActionCommandO ;
if (“>’'. equal s(arg)) {
move(ltlist, rtlist, false);
} else if (“>>”.equals(arg)) {
move(ltList, rtlist, true);
} else if (“<“.equals(arg)) {
move(rtList, ItList, false);
} else if ("«“ .equals(arg)) {
move(rtList, ItList, true);
} else if ।.equals(arg)) {
if (1 tl i st. getSelectedltemsO . 1 ength > 0) {
reverseSelect i ons(lt Li st);
} else if (rtList.getSelectedltemsO.1ength > 0) {
reverseSelections(rtList);
}
} else {
Object target ₽ evt.getSourceO;
if (target rtList | target == ItList) {
replace!tem((List)target, arg);
}
M
N
o
p
Q
R
S
public void itemStateChanged(ItemEvent evt) {
List target = (List)evt .getSourceO ;
if (target -- Itlist) {
deselectAl1(rtLi st);
} else if (target == rtlist) {
deselectAl1(11Li st);
}
}
public static void mai n(Stri ng[] args) {
new Main();
}
T
U
add()
\V in rpose Adds an item to this list.
X
Y
Z
syntax public void add(String item)
public synchronized void add(String item, int index)
description This method adds die item item to this list, index specifies the index in this
list at which to add item. If i ndex is not specified or is -1 or greater than lhe
988
java/awi
addActionListencrO
number of items in this list, item is added to the end of this list. If index is 0. the item becomes the first item in this list. I he set of selected items does not change. This method is the same as additem().
PARAM ENTERS index The zero-based index at which to add the item. If -1, add to the end of the list.
item A non-null string to be added to this list.
SEE ALSO addltemO ♦ remove().
EXAMPLE: See the class example.
addActionListencrO
PURPOSE Adds a listener to receive action events fired by this list.
syntax public synchronized void addActionListener(ActionListener li stener)
DESCRIPTION An action event is fired when the mouse is double-clicked on an item in this list. See ActionEvent for more details. After this method is called, the action listener listener will receive action events fired by this list. If listener is null, this method does nothing.
PARAMETERS listener The possibly null action listener to add.
SEiE ALSO java.awt.event.ActionEvent, java.awt.event.ActionListener, removeActi onLi stener().
EXAMPl.t See the Li st () example and the class example.
addltem()
PURPOSE Adds an item to this list.
SYNTAX public void addItem(String item) public synchronized void addItem(String item, int index)
DESCRIPTION This method adds the item item to this list, index specifies the index in this list at which to add item. If index is not specified or is 1 or greater than the number of items in this list, i tem is added to the end of this list. If index is 0. the item becomes the first item in this list. The set of selected items does not change.
List java.awt
addltemListenerO
This method is the same as add().
PARAMETERS
index I’he zero-based index at which to add the item: if 1. add to the end of the
list.
item A non-nul 1 string to be added to this list.
see \lso add() , removeQ.
exampli In addition to the following example, see a similar usage of add О in the class
example.
import java.awt.'-';
class Main {
final static int ITFMS - 10;
static public void main(String[] args) {
Frame f = new Framefadditem Example”);
List 1 - new ListflTEMS, false);
for (int i - 0; i < ItF^S; i++) {
1.addltem(“item "*i, 0); // always insert at beginning
}
f.add(lT Borderlayout.CENTER);
f.раск О ;
f. showQ ;
}
}
addlteniListenerf)
Pl RPOSE Adds a listener to receive item events fired by this list.
SYXTA.X public synchronized void addTtemListener(ItemListener listener)
DESCRIPTION An item event is fired when an item in this list is selected or deselected. See ItemEvent and the class description for more details. After this method is called, the item listener listener will receive item events fired by this list. If 1 i stener is nul 1. this method does nothing.
PARAMET ERS 1i stener The possibly nul 1 item listener to add.
SEE, ALSO ItemSelectable, j ava.awt.event.ItemEvent, java.awt.event.ItemListener, removeltemli stenerO.
EXAMPLE See the class example.
990
java.awt
Lil3<
addNotifyt
addNotifyO
— — — — — — — - - -
pURPOSI: Creates this list’s peer
SYNTAX public void addNotifyO
description This method calls the Toolkit .createLi stQ method to create this list’s peer. This method should never be called directly. It is normally called by the component's container.
OVERRIDES Component.addNoti fy().
SEE ALSO Container, toolkit.
EXAMPLE See Component.setVi si ble().
allowsMultipleSelectionsf) deprecated
PURPOSE Replaced by isMultipl eMode().
SYNTAX public boolean al lowsMul ti pl eSei ectionsO
RETURNS true if this list is in multiple-selection mode; false otherwise.
DEPRECATION Replace the usage of this deprecated method, as in if (1 i st. al lowsMul ti pleSel ectionsO) . with if (1 i st. i sMul tipi eModeO) ...
clear() DEPRECATED
PURPOSE Replaced by removeAl 1 ().
SYNTAX public synchronized void clearO
DEPRECATION Replace the usage of this deprecated method, as in list.clear(); with list.removeAl1();
countltems() deprecated
PURPOSE Replaced by getltemCountO.
SYNTAX public int countTtemsO
RETURNS The number of items in this list. The result is always >= 0.
deprecation Replace the usage of this deprecated method, as in
java.awt
List
delltem()
int num - 1ist.countitems 0;
with
int num - li st .getltemCountO ;
delltem()
Pl’R POSE- Deletes an item from this list.
SYNTAX public synchronized void delltemfint index)
DESCRIPTION This method deletes the item at index i ndex from this list. It does not affect the selected state of the other items in this list. This method is the same as the form of remove О that accepts an index.
PARAMETERS index The zero-based index of the item in this list.
exceptions
ArraylndexOutOfBoundsException
If index is less than 0 or greater than getltemCountO 1.
sel also java. 1 ang. ArraylndexOutOfBoundsExcepti on , removeO. removeAllf).
example: See the class example.
delltems() DEPRECATE!)
PURPOSE’ Replaced by multiple invocations of remove().
SYNTAX public synchronized void delltems(int start, int end)
PARAMETERS end start The zero-based index of the last item in the range. The zero-based index of the first item in the range.
DEPRE-CATION Replace the usage of this deprecated method» as in 1 ist.de"Uteffls(start, end); with for(int i=end; i >= start; i- ) { list.remove(i); }
SEE ALSO removeAll().
992
java.awt
LISI
deselect
deselect)
PURPOSE Deselects an item in this list.
SYNTAX public synchronized void deselect(int index)
DESCRIPTION This method deselects the item specified at index index. The call is ignored if the item is not selected. The other selections are not affected.
PARAMETERS index The zero-based index of the item in this list.
SEE ALSO select(), getSelectedltemO. is!ndexSelected().
EXAMPLE See the class example.
getltem()
PURPOSE Retrieves an item from this list.
SYNTAX public String getTtemfint index)
DESCRIPTION This method retrieves the item at index index.
PARAMETERS index The zero-based index of the item in this list.
RETURNS The non-null string item.
EXCEPTIONS ArraylndexOutOfBoundsException If index is less than 0 or greater than getl temCount 0-1.
SEE ALSO getltemCountO.
EXAMPLE See the class example.
getltemCountO
PURPOSE Retrieves the number of items in this list.
SYNTAX public int getltemCountsO
RETURNS The number of items in this list. The result is always >= 0.
SEE ALSO getltemO , getltemsO.
EXAMPLL See the class example.
List
getltems)}
juvu.awi
getltems()
I ------
Pl RPOSL Retrieves the items in this list.
SYNTAX public synchronized String!.] getltemsO
A RLll'RNS A new array whose elements are the items in ——- j_'j -t'-i
В this list in the order they appear m this list.
Item 1
C SEEALSO getltem(), getltemCountO. Item 2
D EXAMPLE This example prints the list s items when the
Print button is pressed. See Figure 244.
E I Print j
*’i rfl
F FIGl'RF 244: List .getltemsQ .
G import java.awt.w;
import java.awt.event . * ;
class Main extends Frame implements Actionlistener {
List list = new List();
MainO {
super(“getltems Example”);
К
P
Q
R
s
T
и
V
M
N
О
1 i st. addltem(“ltem I*1);
1ist.additem(“Item 2”);
add(list, BorderLayout.CENTER);
Button b;
add(b=new ButtonC'Print”), BorderLayout.SOUTH);
b.addActionLi stener(this);
setSize(200, 200);
show() ;
}
public void actionPerformed(ActionEvent evt) {
String^] items - 1ist.getltemsC);
for (int i-0; i<iterns.1ength; i++) {
System.out.print 1n(iterns[ij);
}
}
static public void mai n(Stri ng[] args) {
new ^ai n();
W
x getMinimumSize()
pi rposl Calculates the minimum dimensions of this list.
syntax public Dimension getMinimumSize()
public Dimension getMinimumSize(int rows)
994
ge t Pre ferredSi /e()
DESCRI И ION This method calculates the minimum dimensions needed tor this list given that the specified number of rows must he visible. If rows is less than or equal to 0 or is not specified, (he value of getRows() is used. If this list's peer does not exist, the result of Component.getSizeO is returned. On most platforms, the preferred and minimum dimensions for this list are the same.
PARAMET 1 RS rows The number of rows.
RETURNS The non-null minimum dimensions of this list.
OVERRIDES Component.getMi nimumSizeО.
SEE ALSO getPreferredSizeO.
EXAMPLE See LayoutManager.minimumLayoutSize().
getPreferredSize()
PURPOSE Calculates the preferred dimensions needed for this list.
SYNTAX public Dimension getPreferredSizeO public Dimension getPreferredSize(int rows)
DESCRIPTH )N This method calculates the preferred dimensions needed for this list given that the specified number of rows must be visible. If rows is less than or equal to 0 or is not specified, the value of getRowsQ is used. If this list's peer does not exist, the result of Component.getSizeO is returned. On most platforms, the preferred and minimum dimensions for this list are lhe same.
PARAMETERS rows The number of rows.
RETURNS The non-null preferred dimensions of this list.
OVERRIDES Component .getPreferredSizeO.
EX AM Pl,E See LayoutManager.preferredl ayoutSi zeQ
getRowsf)
—* — — —- —. —• . . — -— —. — — —- —
PURPOSE Retrieves the number of rows in this list.
SYNTAX public int getRows()
List
getSelectedlndext)
java.awt
DESCRIPTION The number of rows is specified when this list is created; it never changes, even if the dimensions of this list change. See the ListQ constructor tor more details about rows.
RE1 URNS The number of rows.
SEE ALSO List().
EXAMPLE See removeAll ().
getSelectedIndex()
PURPOSE Retrieves the index of the selected item.
SYNTAX public synchronized int getSel ectedlndexO
RETURNS The zero-based index of the selected item or -1 if no item is selected. It this list is in multiple-selection mode» -1 is always returned.
SEE Al SO deselectO , getSelectedltemO , selectO-
EXAMPLE See the class example.
getSelectedlndexest)
PURPOSE Retrieves the indices of the selected items.
SVNLAX public, synchronized int[] getSe 1 ectedlndexesO
RETURNS A non-nul 1 array containing the list of indices. The return array is never null, but it may have length 0» which indicates that no items were selected.
SEE ALSO getSelectedlndexO . getSelectedltemO-
EXAMPLE See the class example.
getSelectedltemf)
PURPOSE Retrieves the selected item.
SYNTAX public synchronized String getSel ectedltemO
REIURNS The selected item; nul 1 if no items are selected. II this list is in multiple selec- tion mode, null is always returned.
SEEALSO getSelectedlndexO T getSelectedlndexesO.
996
getSclccted Items()
example This example creates a frame con-
taining a list. As you click any item
in the list, the currently selected item
is printed. See Figure 245.
import java.awt.';
import java.awt.event;
FIGURE 245: List . getSel ectedltemO .
class Main extends Frame
implements ItemListener {
static final int ITEMS ~ 10;
static List 1 = new List(ITEMS, false);
MainQ {
super("get5electedltem Fxample");
for (int i =0; i < ITFMS; i+Q {
1 .addltem(“item “+i);
}
add(l, BorderLayout.CENTER);
1.addltemLi stener(thi s);
packQ ;
showO ;
}
public void itemStateChanged(ItemEvent evt) {
// Use quick way to print selected item
Sy stem, out. pri ntl n( 1 .getSelectedltemO) ;
// Use another way to print
Object [1 selected = 1 .getSelectedObjectsQ ;
for (int i = 0; i < selected.length; i* + ) {
System.out.printIn(selected[ i]);
}
}
static public void main(String[] args) {
new Mai n();
}
}
getSelectedItems()
PURPOSE- Retrieves the selected items in this list.
SYNTAX public synchronized String[] getSelectedltemsO
RETURNS A non-null array containing the names of the selected items on this list.
SEE also getSel ectedlndexesQ, getSel ectedltem().
example See the class example.
List
getSelectedObjectsf)
java.awt
getSelected()hjects()
PI RPOSE Retrieves this list's currently selected items.
SY MAX public synchronized Object[] getSelectedObjectsQ
reti RXS An array of strings containing this list's currently selected items. The return array is never null, hut it may have length 0, which indicates that no items were selected.
SEEALSO getSelectedlndexO , getSelectedlndexesQ , getSelectedltemO * getSelectedltemsO , ItemSelectable.
EX YMPL E See getSelectedltem().
getVisiblelndexf)
Pl RPOSE Retrieves the index of the item that was last made visible.
SY’S 1 AX public int getVisiblelndexO
1)ES( RlPl IOX The item that was last made \ isiblc is the item passed to the most recent call to makeVi si Ы e().
REП RXS The zero-based index of the item that was last made visible w ith rhe makeVi s- ibleO method. IfmakeVisi ble() has not yet been called. 0 is returned.
SLL ALSO makeVisibleO.
isItemSelected()
Pl RPOSI Determines w hether an item in this list is selected.
SYXTAX public boolean isltemSelected(int index)
DESCRIPTION This method determines whether the item at index index on this list is selected.
RETI RXS true if the item at index index is selected: false otherwise.
P/YR AMEl ERS index The zero-based index of the item.
SLL ALSO deselectO , selectO.
EX AM Pl E See the class example.
998
isMultipleModet)
isMultipleMode()
PURPOSE. Retrieves the selection mode of this list.
SYNTAX public boolean isMu 1 tipleModeQ
returns true if this list is in multiple-selection mode: false otherwise.
SEE ALSO setMul ti pleModeQ.
example See setMultipi eMode().
isSelected() deprecated
PURPOSE Replaced by isIndexSelectedQ.
SYNTAX public boolean isSelectedfint index)
PARAMETERS index The zero-based index of the item.
RETURNS true if the item at index index is selected; false otherwise.
DEPRECATION Replace the usage of this deprecated method, as in if (1ist.isSelectedfindex)) ... with if (11 st.isIndexSelected(index)) ...
List()
PURPOSE Constructs a new list component.
SYNTAX public ListQ public List(int nrows) public List(int nrows, boolean multipleselections)
DESCRIPTION The three forms of this constructor create a new' list component tall enough to display nrows visible rows. If nrows is not specified, it defaults to 4. The number of rows can be retrieved at any time with getRowsO. However, this value never changes, even if the dimensions of the list change. If multi ple- Selections is true, the list is set in multiple-selection mode; otherwise, the list is set in single-selection mode. If mul tipi eSelections is not specified, it defaults to false. The width of the list component is set to a platform depen- dent value.
PARAMET ERS
multi pl eSeiecti ons
Specifies the selection mode of the list.
List
java.awt
makeVisiblel)
A
В
C
Г)
E
E
G
II
I
J
К
nrows The number of rows in the list is defined to be the number of items that can hr
visible at one lime, where lhe first visible item is completely visible and the
last visible item is at least partially visible. (Note that in implementations that
allow both the first and last visible items to be partially visible* it's possible for
more than nrows items to be visible.) In implementations in which a horizontal
scrollbar automatically appears if needed, the number of visible items may be
fewer than nrows when the scrollbar is present.
EXAMPI F
This example creates a list component
that has two items. See Figure 246. The
program prints out the current item
whenever an item in the list is double-
clicked.
FIGI RE 246: Simple List.
import java.awt.';
import java.awt.event;
M
N
О
P
Q
R
S
T
i:
class Main extends I rame implements ActionListener {
MainC) {
super(“List Example'*);
List list - new L ist();
1ist.addltem("ltem 1") ;
1ist.addltemC'Item 2”);
add(list, Borderlayout.CLNTER);
list.addActionLi stener(thi s);
setSize(200» 200);
show();
public void actionPerformed(Action£vent evt) {
Sy stem, out .printin (evt .get Act ionCommandO) ;
}
static public void mai n(Stri ng[] args) {
new Main();
}
V
makeVisible()
x
Y
7
purpose Scrolls this list so that an item is visible.
syntax public synchronized void makeVisible(int index)
description This method scrolls this list so that the item at index i ndex is visible.
1000
juvu.awi
mirmnumSizef)
PARA MET ERS
index I'he zero-based index of the item.
SEE also getvi si bl eindex О.
example This example creates a list component
with ten items and makes sure that the last
item in the list is visible. See Figure 247.
item 5 3
item 6
item 7 item 8 J
item 9
FIGI RE 247: List .makeVisibleQ.
import java.awt.*;
class Main extends Frame {
static final int ITEMS - 10;
static list 1 = new List<ITFMS/2, true);
static public void maiл(String J args) {
Mai n f = new Main О;
for (int i -s. 0; i < ITEMS; i++) {
1.addltem(“item “+i);
}
f.add(l, BorderLayout.CENTER);
f .packO;
f. showO:
1.makeVi s i Ы e(1T EMS -1);
minimumSizef) deprecated
purpose Replaced by getMi ni mumSi ze().
syntax public Dimension minimumSizeO
public Dimension minimumsize(int rows)
PARAMETERS
rows The number of rows.
Returns The non-null minimum dimensions of this list.
OVERRIDES Component.mi nimumSize().
DEPREC ATK)N Replace the deprecated usage of this method, as in Dimension diml = 1 i st .iri nimumSizeO ; Dimension dim2 = 1ist.minimumSize(rows); with Dimension diml - 1 ist.getMinimumSize(); Dimension di m2 - list.getMinimumSize(rows);
java.awt
List___ _
paramStringf)
paramStringO
A РГКР< >SP SYX'l A\ DESCRIPTION Generates a string representing (his lisfs state. protected String paramStringO A subclass of this class should override this method and return a concatenation
В of its state with the results of super.paramStringO. This method is called
(' b\ the toStri ng О method and is typically used for debugging.
D RI H RXS A non-null string representing this lists state.
I. O\ f .RRIDI-.S Component.paramSt ring().
h SLL ALS<) Object. toStri ngO.
G EXAMPLE See Component.paramStri ng().
preferredSize() DEPRECATED
in rpose Replaced by getPreferredSi ze(). sw'Iax public Dimension preferredSize() public Dimension preferredSize(int rows) PARAMETERS rows The number of row s. ri 11 rxs l he non-nul 1 preferred dimensions of this list. o\LRRtDt s Component.preferredSi ze(), deprecation Replace the deprecated usage of this method» as in Dimension diml = 1 ist.proferredSizeO ; Dimension dim2 - 1ist.preferredSizo(rows); w ith Dimension dinl 1ist.getPreferredSizef); Dimension ctim2 = 1ist.getPreferredSize(rows);
processActionEventO
pi rposl Processes an action event enabled for this list.
syxtax protected void processActiontvent(ActionFvent evt)
dlscrihiox An action event is fired when (he mouse is double-clicked on an item in this
list. See ActionEvent for more details. This method processes action events
for this list by calling any registered ActionListener. It is invoked onlv if
action events have been enabled for this list. This can happen either when an
1002
List
jax a.awl
replaceltemO
an item listener is added to this list or it item events are enabled explicit lx xia
Component .enableEventsO.
Typically, a program controls how item events for a list are processed b\ add-
ing or removing item listeners. It overrides processItemEventО only if it
A needs to do processing in addition to that performed by the registered listeners.
В When a subclass does override processltemEvent(). it should call
c super.processItemEvent() to perform the processing intended by its base
class (such as dispatching the listeners).
D
PARAMETERS
evt The ex ent to be processed.
E see also addltemLi stenerO , Component.enableEventsO,
java.awt.event.ItemEvent, TtemSe1ectable,
java.awt.event.ItemListener, processEventO.
pi removeltemLi stenerO.
! example See AWTEventMul ti caster. i temStateChangedQ.
J
К
replaceltem()
M
N
О
P
Q
R
S
T
L
V
w
X
Y
Z
purpose Replaces an item in this list.
syntax public synchronized void replaceItem(String newltem. int index)
description This method replaces the item at the index i ndex with newltem.
PARAMETERS
i ndex The zero-based index of the item,
newltem The non-nul 1 new item.
sn ai so addltemO.
example See the class example.
remove()
PURPOSE Deletes an item from this list.
SYNTAX public synchronized void remove(int index) public synchronized void removeCString item)
DESCRIPTION The first form of this method deletes the item at index index from this list. The second form deletes the first occurrence (from index 0) of the item i tem in this list. This method does not affect the selected slate of the other items in this list.
1004
piece ssEventf)
action listener is added to this list or when action events are explicitly enabled via the use of Component. enabl eEventsO Typically; a program controls how action events for a list are processed by add- ing or removing action listeners. It overrides processActionEvent() only if it needs to do processing in addition to that performed by the registered listen- ers. When a subclass does override processActionEventQ. it should call super.processActionEventO to perform the processing intended by its base class (such as dispatching the listeners).
PAR А МЫ ERS evt The event to be processed.
SEE Al SO addActionLi stenerQ, Component. enable Event sQ, java.awt.event.ActionEvent, java.awt.event.Act ionLi stener, processEventO , removeActionListener().
EXAMPLE- See the AWTEventMulti caster class example.
processEventO
purpose: Processes an event enabled for this list.
syntax protected void processEvent(AW[Lvent evt)
DESCRIPTIOX This method extends Component.processEvent0 by adding support for ActionEvent and ItemEvent.
PAR A ME-. I ERS evt The event to be processed.
OVERRIDES Component. processEventO.
SEE. M SO AWTEvent, processActionfventO, processItemFvent().
EX AM PI E; See the AWTEventMul ti caster class example.
processitem Event!)
Pl RPOSI. Processes an item event enabled for this list.
SY\I AX protected void processltemEvent(ItemFyent evt)
E)E SCRIP IIOX An item event is fired when an item in this list is selected/deselecred. See ItemEvent and the class description for more details. This method processes item events for this list by calling any registered ItemListener. It is invoked only if item events have been enabled for this list. Th is can happen either when
Jtl Vd.dVX’l
reinove/XctionListenei
The form of this method that accepts an index is the same as del Item().
parameters
index The zero-based index of the item in this list,
item The item to remove.
EXCEPTIONS
ArraylndexOutOfBoundsException
If i ndex is less than 0 or greater than getltemCountO 1.
IllegalArgumentException
If i tem is not in this list.
see also delltemO, java.lang.ArraylndexOutOfBoundsException,
java.1ang.Il1ega1ArgumentE xcepti on, removeAl1 О.
example. See the class example.
removeAction Listened)
PURPOSE Removes a listener from receiving action events from this list.
SYNTAX public synchronized void removeActionListener(ActionListener 1i stener)
DESCRIPTION An action event is fired when the mouse is double-clicked on an item in this list. See ActionEvent for more details. After this method is called, the action listener listener will no longer receive action events from this list. If 1 i stener is nul 1. this method does nothing.
PARAMETERS 1i stener The possibly null action listener to remove.
SEE ALSO addActionListenerO, java.awt.event.ActionEvent, java.awt.event.ActionL i stener.
EXAMPLE See Menuitem. di sabl eFvents().
removeAlK)
PURPOSE Removes all items from this list.
SYNTAX public synchronized void removeAlIQ
DESCRIPTION The effect of calling removeAl 1 () is the same as calling removeO for every item in this list.
see: ALSO remove().
java.awt
Л
В
C
D
List
reinoveAIK )
IXAMPLL
This example creates
a list component that
has ten items. Press-
ing the Remove All
button removes all of
the items in the list.
Sec F igure 248.
< remove... «ж
< remove
item 0
item i
item 2
item 3
item 4
item 5
item 6
item 7
item 8
item 9
G
H
I
J
К
M
N
О
P
Q
R
S
T
C
v
w
X
Y
z
FIGL Rk 248: Li st. removeAl 1 О .
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ActionListener {
List 1 - new L i st(10,
false);
Button b;
Main() {
super(”removeAl1 Example”);
for (int i - 0; i <10; i*+) {
1.additem(”itern “+i);
}
b -- new Button(“Remove All “ + l.getRowsO + “ Rows”);
add(l, BorderLayout.CENTER);
add(b, BorderLayout.SOUTH);
b.addActionLi stenerCthi s) ;
packQ ;
show О;
}
static public void main(String[] args) {
new Mai n();
}
public void actionPerformedfActionEvent evt) {
1.removeAl1();
// disable button and remove listener
b.setEnabled(false);
}
}
1006
JCX VU.H Y> I
removeltemLiMei
removeltemListenerf)
PURPOSE Removes an item listener from receiving item events from this list.
SYNTAX public synchronized void removeltemlistener(ItemListener 1i stener)
DESCRIPTION An item event is fired when an item in this list is selected/deselected. See ItemEvent and the class description for more details. After this method is called, the item listener 11 stener will no longer receive item events from this list. If 11 stener is nul 1 . this method does nothing.
PARAMETERS listener The possibly null item listener to remove.
SEEALSO addltemListenerQ , ItemSelectable, java.awt.event.ItemEvent, java.awt.event.ItemListener.
EXAMPLE See removeActi onLi stenerQ in Menu Item .di sabl eEventsQ.
removeNotifyO
PURPOSE Destroys this list's peer.
SYNTAX public void removeNotifyO
DESCRIPTION This method should never be called directly. It is normally called by the com- ponent's container.
OVERRIDES Component. removeNoti fyQ.
SEE ALSO Component.
EXAMPLE See Component.setVi si ble().
select()
— —- — — — — — -
PURPOSE Selects an item in this list.
SYNTAX public synchronized void selectfint index)
DESCRIPflON This method selects the item at the index i ndex. The call is ignored if the item is already selected.
PARAMETERS index The zero-based index of the item.
List
setMultipleMode( I
java.au I
EXCEPTIONS
ArraylndexOutOfBoundsExcept ion
If index is less than 0 or greater than getltemCountO 1.
A
В
sle also deselectO. getSel ectedltemO. i slndexSelectedO
java,1ang.ArraylndexOutOfBoundsExcepti on.
C
D
E
H
G
H
I
.1
К
M
N
()
P
0
R
exampi e This example creates a list component that has
every other item selected. See f igure 249.
import java.awt."’:
class Main {
static final int ITEMS - 10;
static public void main(String[j args) {
Frame f = new Frame();
list 1 = new Li st(ITEMS, true);
for (int 1 - 0; i < ITEMS; i+f) {
1.addItem(“item “+i);
if (i % 2 -- 0) {
1.seiect(i);
}
}
f.add(l, BorderLayout-CENTER);
f.pack();
f.show();
}
}
setMultipleMode()
purpose Sets this list's selection mode.
FIGURE 249:
List.seiect().
syntax public synchronized void setMuitipl eMode(boolean on)
description If on is true, this method sets this list in multi-selection mode: otherwise, it
sets this list in single-selection mode.
PARAMEI ERS
on Specifies the new selection mode of the list.
see also isMultipleMode().
w
X
Y
Z
1008
sctMultipleSelectionsi
exam pl л. This example creates a frame containing a list
and a checkbox control, l he checkbox control
is used to toggle the multiple-selection model
of the list control. See Figure 250.
import java.awt.-;
import java.awt.event.*;
class Main extends Frame implements ItemListener {
static final int ITEMS - 10;
static list 1 = new List(TTFMS. false);
static Checkbox b =
new Checkbox (‘‘Mui tipi e selection Mode”,
null, false);
FIGURE 250: Turning Multiple
Mode On and Off in List.
Main() {
superC'Selection Mode Example”);
for (int i - 0; i < ITEMS; i + O {
1 . addltemC'item “+i);
}
add(l, BorderLayout.CENTER);
add(b, Borderlayout.SOUTH);
b.addltemLi stener(thi s);
pack();
show();
}
public void itemStateChanged(ItemFvent evt) {
1. setMul ti pleMode(evt. getStateChangeO — ItemEvent.SELECTED);
System.out.println(“multiple mode: “ * 1.isMultipleMode());
}
static public void main(Stringargs) {
new Main();
}
}
setMultipleSelections() deprecated
PURPOSE Replaced by setMul ti pleModeQ.
SYNTAX public synchronized void setMultipleSelections(boolean on)
PARAMETERS on Specifies the new selection mode of this list.
DEPRECATION Replace the usage of this deprecated method, as in setMult i pleSelecti ons(on); with setMultipleMode(on);
java.awt.peer
ListPeer
.2—,,..........:...□ '
l! • V-—.... j
c ..................>
n <, - >
E ! :)
г \ _ J
a • L ...._..........J
H ' 'sJXJ-........ ....>
i ’ ;—)
j ‘ : " \2__-----—J
к
M Syntax
public interface ListPeer extends ComponentPeer
M
N Description
О The list component (see the List class) in the AWT uses the platform's native implementation
of a list. So that the AWT list behaves the same on all platforms, the list is assigned a peer,
whose task is to translate the behavior of the platform's native list to the bcha\ ior of the AWT
Q list.
K AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
$ their peers. Only someone who is porting the AWT to another platform should be concerned
T with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
See Component and Toolkit for additional information about component peers.
V
W
X
Y
Z
1010
add()
member summary
Peer Methods
add O Adds an hem to the list.
delltems() Deletes a range of items from the list.
deselectO Deselects an item in lhe list.
getMinimumSizeO Calculates the minimum dimensions of the list.
getPreferredSizeO Calculates the preferred dimensions of the list.
getSelectedlndexesО Retrieves the indexes of the selected items.
makeVi sibleO Scrolls the list so that an item is \ isible.
removeAl!() Removes all items from the list.
selectO Selects an item in the list. i
setMul ti pl eModeO Sets the selection mode of the list.
Deprecated Methods
addltemO Replaced by add О
clearO Replaced by removeAl 1 ().
minimumSizeO Replaced by getMi nimumSize().
preferredSizeO Replaced by getPreferredsize().
setMulti pleSe1ect i ons() Replaced by setMul ti pleModeO. _ J
See Also
java.awt.Component, java.awt.List, java.awt.Toolkit.
add()
— ’ — — — —
Pl ’RPOSE Adds an item to the list.
SYMAX void addfString item, int index)
PARAMETERS item index The item to be added. The position in the list at which to add the item.
SEE At.so java.awt.Li st.add О.
add Item() DEPRECATED
Pt'RP( >SL Replaced by add().
SYMAX void addltemfString item, int index)
java.awt.peer
ListPeer
clear()
F
G
H
I
J
К
M
N
О
P
Q
R
S
T
PARAMETERS
item index The item to be added. Fhe position in the list at which to add the item.
DEPRECATION Replace the usage of this deprecated method, as in peer.addltem(item, index); with peer.add(item, index);
clear() DEPRECATED
PURPOSE Replaced by removeAl 1 ().
SYNTAX void clear().
DEPRECATION Replace the usage of this deprecated method, as in peer.clearO ; with peer,removeAl1();
delltemsf)
PURPOSE Deletes a range of items from the lisL
SYNTAX void delltems(int start, int end)
PARAMETERS end start The ()-based index of the last item in the range. The ()-based index of the first item in the range.
SEE A I.SO java.awt.Li st.delItems().
deselect)
U purpose Deselects an item in the list.
void deselect^ nt index)
PARAML I ERS
index The О-based index of the item to deselect.
see also java.awt. Li st. deselectO-
1012
getMinimumSize
getMinimumSize()
PURPOSE Calculates the minimum dimensions of the list.
SYNTAX Dimension getMinimumSize(int rows)
parameters rows The number of rows the list must accommodate.
RETURNS The minimum dimensions of the list.
see: also java,awt,Li st.getMinimumSize().
getPreferredSize()
purpose Calculates the preferred dimensions of the list.
SYNTAX Dimension getPreferredSize(int rows)
PARAMETERS rows The number of rows the list must accommodate.
RETURNS The preferred dimensions of the list.
SEES ALSO java.awt. List .getPreferredSizeO.
getSelectcdlndexesf)
PURPOSE* Retrieves the indices of the selected items.
SYNTAX intf] getSelectedlndexesO
RETURNS An array containing the list of indices.
Stl£ ALSO java.awt. List .getSelectedlndexesO.
makeVisible()
PURPOSE Scrolls the list so that an item is visible.
SYNTAX void makeVisi ble(int index)
PARAMETERS index The ()-based index of the item to make visible.
SEE ALSO java.awt.Li st.makeVisi ble().
java.awt.peer
IJstPeer
minimumSizeO
minimumSize()
DEPRECATED
PURPOSE Replaced by getMi nimumSi ze ().
Л SYNTAX PARAMETERS Dimension minimumSize(int rows)
в rows The number of rows the list must accommodate.
c RETURNS The minimum dimensions of the list.
D DEPRECATION Replace the usage of this deprecated method» as in
E Dimension min = peer.minimumSizeO: with
F Dimension min = peer.getMinimumSizeO;
G
DEPRECATED
н preferredSize()
1 PURPOSE Replaced by getPreferredSizeO.
J SYNTAX Dimension preferredSize(int rows)
К PARAMETERS rows The number of rows the list must accommodate.
M RETURNS The preferred dimensions of the list.
N DEPRECATION Replace the usage of this deprecated method, as in
0 Dimension pref = peer.minimumSizeO ;
P with Dimension pref = peer.getMinimumSize();
Q
remove All()
PURPOSE Removes ail items from the list.
SYNTAX void removeAl1().
SEE ALSO j ava.awt.Li st.removeAl1().
W
X
Y
Z
1014
select!)
select()
purpose Selects an item in the list.
SYNTAX void select(int index)
PARAMETERS
i ndex The index of the item to select.
SEEalso java.awt.L i st .select().
setMultipleMode()
PURPOSE Sets the selection mode of the list.
SYNTAX void setMultipi eMode(boolean on)
PARAMETERS on true means set the list control in multiple-selection mode: false means set the list in single-selection mode.
SEE ALSO java.awt.List.setMu1tipleSelections().
setMultipleSelections()
DEPRECATED
PURPOSE Replaced by setMultipleMode().
SYNTAX void setMultipleSelections(boolean on)
PARAMETERS on true means set the list control in multiple-selection mode; false means set the list in single-selection mode.
DEPRECATION Replace the usage of this deprecated method, as in peer.setMulti pl eSelect ions(on); with peer.setMulti pl eMode(on);
java.awt
MediaTracker
c Syntax
О public class MediaTracker implements Serializable
E
Г
G
H
I
J
К
L
X
О
p
Q
R
M
Description
The imaging routines in lhe AWT are designed to allow images to he used before they're com-
pletely loaded or generated. However in some cases, you may want or need to wait until all of
the pixels of an image are available before rendering the image. For example, an application
may w ish to display an image for the user to view, while in the background it loads another
image. Once the other image is loaded, the application replaces the currently displayed image.
The media tracker is used to manage the loading of images. It makes it convenient to
determine when all of the pixels have been received or if an error occurred.
The media tracker also makes it convenient to track the loading status of a set of images. It
does this by allowing you to choose an arbitrary integer called the id and then associating all of
the images in the set with the id. By using the id. you can have the entire set of images treated
as one image. For example, you can start the loading of all of the images in the set. or you can
check if any image in the set has encountered an error, or you can wait until all of the images
have been loaded and then determine if every image loaded successfully.
Media tracker ids are often used w ith an animation frame, which consists of man) images
that need lo be loaded or generated. Typically, all of the images must be complete; otherwise,
none of the images can be used. That is. if any one of the images in the set encounters an error
during its construction, then the whole set should be considered invalid.
и MEMBER SUMMARY
V (’(instructor
w MediaTrackerО Constructs a MediaTracker object.
X Status Flag Constants
Y ABORTED Specifies that the image loading process was aborted.
COMPLETE Specifics that lhe image loading process was completed successful 1).
Z FRRORED Specifies that the image loading process encountered an error.
LOADING Specifies that the image loading process is in progress.
1016
MEMBER SUMMARY
Status Methods
checkAl1()
checklDQ
getErrorsAnyO
getErrorsIDO
i sErrorAnyO
i sErrorlDO
statusAl1()
statusIDO
Determines il all images have been loaded.
Determines if all images lagged with an id have been loaded.
Retrieves a list of all images that have encountered an error.
Retrieves a list of all images tagged with an id that have encountered an
error.
Determines if any image encountered an error during loading.
Determines if any image tagged with an id encountered an error during
loading.
Determines the combined status of all images.
Determines the combined status of all images tagged with ids.
Image Methods
addlmageO
imageUpdateO
removelmagef)
wai tforAl1()
wai tForlDO
.Adds a scaled image to the list of images being tracked.
Should not be used.
Removes an image from the list of images being tracked.
Waits tor all images to be loaded
Waits for all images lagged w ith an id to be loaded.
See Also
java. io. Seri al i zabl e.
Example
This example implements a slide show program.
See Figure 251. ‘I'he program is invoked with a list
of files that contain images. The images are dis-
played in the order in which they appear in the list.
They also arc loaded in the same order: that is. an
image does not begin loading until the previous
image has been completely loaded.
The program provides two buttons — Next and
Previous — for mov ing through the slides. The Next
button displays the next image in the list. However,
it is enabled only if the next image has been com-
pletely loaded.
A thread is used to successively load each
image in order. So while the user views an image
Medial*racker Example В0И
Next
I IGl RE 251: Medi aTracker .
the piogiam is busily loading the next
image. If an crioi oecuis in the loading of an image, the image appears as a red rectangle. After
all of the images have been loaded, the program prints status information about each image.
MediaTracker
jina.au l
To implement the enabling and disabling of lhe two buttons, the program uses sta-
tusIDQ instead of checkIDO. This is because checkIDO returns true if an id has not been
used (i.e., no image has been added using it к whereas status ID О returns 0 if the id has not
been used. Using statusIDQ makes it eas\ to disable lhe buttons for the id that precede the
A first image and follow the last image. It might have been clearer simpK to test for (cur Im-
age-1 < 0) or (curlmage+l > images. length), but we uanted to demonstrate the difference
between statusIDQ and checkIDO.
C
import java.awt.*;
import java. awt. image. ;
import java.awt.event.x;
class ^ain extends Frame implements Runnable, ActionListener {
MediaTracker tracker;
ImageJ images;
ImageCanvas icv ~ new IrrageCanvasO ;
Button btnkext - new Button("Next”):
Button btnPrevious = new Button(“Previous”);
Main(String Г1 files) {
super(“Medi aTracker Fxample");
tracker = new Medialracker(icv);
images *- new Image[fi 1 es. 1 ength! ;
for (int i=0; i<images.length; i+*) {
images- getToolkit().getImage(files[i]);
tracker.addlmage(images[i] , i);
}
// First image is progressively rendered,
if (images.length > 0) {
i cv.setImage(images[0]);
add(icv, Border! ayout .( FNTER) ;
add(btnPrevious, BorderLayout.NORTH);
add(btnkext, BorderLayout.SOUTH);
btnPrevious.addActionListener(this) ;
btnNext.addActionLi stener(thi s);
setSize(460, 250);
show();
(new Ihread(this)) .startO;
// Print overall status information,
try {
// We don't use waitForAllQ because it forces
// all images to start loading: we want to load
// images one at a time.
// tracker.waitForAl1();
while (*tracker.checkAl1()) {
Thread.sieep(1000);
}
} catch (Exception e) {
e.pri ntStackT race();
System.exit(l);
1018
}
it (tracker.isErrorAny()) {
System, out. pri nt 1 n(*'Not all images have been successfully loaded.");
Object[J list = t racket.get ErrorsAnyO ;
for (int i=0; i <1 i st. length; i++) {
Sy stem, out.println(l istj.il) ;
} else {
System.out.println("Al1 images have been successfully loaded");
}
for (int i-0; i<images.length; i++) {
int s = tracker.statuslD(i, false);
System.out.print(filesZiJ + ");
if ((s & .Medial racket. ABORTED) !- 0) System. out. pr i nt ("ABORTED ");
if ((s & MediaTracker.COMPLETE) 0) System.out.print("COMPLETE ");
if ((s & MediaTracker.ERRORFD) != 0) System.out.print("ERRORED ");
if ((s & MediaTracker.! OADING) !- 0) System.out.print("LOADING ");
System,out.pri ntln();
}
}
int curlmage;
final int DO\E - (Medial racket.ABORTED I MediaTracker.FRRORED
1 MediaTracker.COMPLETE);
public void paint(Graphics q) {
if (tracker.isErrorlD(curlmage)) {
icv.setlmage(nul1);
} else {
icv.setlmage(imagesZcurlmageJ);
}
btnNext.setEnabled((tracker.statuslD(curImage*1, false)&DONF) != 0);
btnPrevious.setEnabled(
(tracker.status!D(curImage 1, false)&DONE) :=0);
/* See example description for explanation:
btnNext.setEnabled(tracker.checkID(curImage+l));
btnPrevi ous.setEnabled(tracker.checkID(curimage-1));
V
}
public void actionPerformed(ActionEvent evt) {
String arg = evt .getActionCorirand();
if ("Next”.equals(arg)) {
if (curlmage < images.length-1) {
++cu rImage;
repai nt();
}
} else if ("Previous”.equals(arg)) {
if (curlmage > 0) {
--curlmage;
repai nt ();
}
}
}
public void run() {
for (int i--0; i<images.length; i++) {
//tracker.checkID(i);//, true);
try {
MediaTracker
java.awt
ABORTED
tracker.wai tForID(i);
} catch (Exception e) {
e.printStacklrace() ;
}
repai nt();
}
Л }
В static public void main(St ri ng[J arqs) {
new Main(args);
C }
}
D
class ImageCanvas extends Canvas {
E Image image;
boolean clear;
E
public void setlmage(lmage image) {
G this.image * image;
clear = true;
H repaintO;
}
public void update(Graphics g) {
J paint(g);
К } public void paint(Graphics g) {
L if (image == null) { g.setColor(Co lor.red);
g,fillRect(0, 0, getSizeO.width, getSize().height); } else {
N if (clear) { g.clearRect(0, 0, getSize().width, getSize().height):
() clear * false; }
P int w - image.getwidth(this); int h = image.getHeight(this);
Q if (w 0 && h >= 0) { g.drawlmage(image, (getSizeO,width-w)/2,
R (getSizeO . height-h)/2 , this); }
S T u v } } } ABORTED _
w purpose Specifies that the image loading process was aborted.
X syntax public static final int ABORTED
Y description This field is a status flag that specifies that the image loading process was
aborted. Its value is 2.
SEE ALSO statusAllO, statusIDO. example See the class example.
1020
add I mi
addlmage()
PURPOSE; Adds a scaled image to the list of images being tracked.
SYNTAX public void addimage(Image image, int id) public synchronized void addimage(Image image, int id, int w, int h)
DESCRIPTION This method associates an image with lhe media tracker id id. Several images can be associated with id. The image will eventually be rendered at the indi- cated size.
PARAMETERS h id image w The height in pixels at which the image will be rendered. The identifier used to later track this image. The non-null image to he tracked. The width in pixels at which the image will be rendered.
EXAMPLE See the class example.
checkAlif)
PURPOSE Determines if all images have been loaded.
SYNTAX public boolean checkAllO public boolean checkAl1(boolean load)
DESCRIPTION This method returns true if all of the images have been loaded. An image is defined to be loaded if either the image successfully loaded or it encountered an error. In other words, this method returns true if none of the images will receive more pixels. The method isErrorAnyO can be used to determine if an error occurred during the loading of at least one image in the media tracker. If load is true and not all of the images have started loading, the loading pro- cess is started for all images. If load is not specified, it defaults to false.
PARAMEI ERS load If true, the loading process is started for all images.
RETURNS true if all images are loaded.
SEE ALSO checkIDO, IsErrorAnyO, statusAll().
example See the class example.
java.awt
MediaTracker
check! D()
checkID()
PL RPOSE SYNTAX A Determines if all images tagged with an id have been loaded. public boolean checkID(int id) public boolean checkID(int id, boolean load)
В DESCRIP Г ION This method returns true if all of the images tagged with id have been loaded.
C An image is defined to be loaded if either it successfully loaded or ir encoun- tered an error. In other words, this method returns true if no image tagged
D with id will receive more pixels. The method isErrorlDQ can be used to
t determine it an error occurred during lhe loading of at least one of the images
p tagged with id.
G If load is true and the images tagged with id have not started loading, the loading process is started for these images. If load is not specified, it defaults
H to fal se.
I check ID О calls Component. checklmageO on the images to obtain their
status in order to construct the result.
J If no images are associated with id. this method returns true.
К PARAMETERS
L id The media tracker id.
load If true, the loading process is started for all images tagged with id.
N verify If true, call Component.checklmageO on the tagged images when generat- ing the status; if fal se. Component. checklmageO is not called.
() RE-TERNS true if all images tagged with id are loaded.
P SEE. ALSO checkTDO , i sErrorlDO , statusIDO.
COMPLETE
pi rpose. Specifies that rhe image loading process was completed successfully.
swi ax public static final int COMPLETE
description This field is a status flag that specifies that the image loading process was
completed successfully, hs value is 8.
sll also statusAllQ, statusIDO.
example See rhe class example.
1022
ERRORE
errorkd_____________________________________________
PURPOSE Specifies (hat the image loading process encountered an error.
SYNTAX public static final int ERRORED
DESCRIPTION This field is a status flag that specifies that the image loading process encoun- tered an error Its value is 4.
SEEALSO statusAllQ , statusIDQ.
example See the class example.
getErrorsAnyf)
PURPOSE Retrieves a list of all images that have encountered an error.
SYNTAX public synchronized Object[] getErrorsAnyQ
description This method returns a list of all images that have encountered errors so far.
RETURNS null if there are no errors or an array of all images that have encountered errors.
SEE ALSO getErrorsIDO » isErrorAnyO.
EXAMPLE See the class example.
getErrorsIDf)
PURPOSE Retrieves a list of all images tagged with an id that have encountered an error.
SYNTAX public synchronized Objectf] getErrorsID(int id)
DESCRIPTION This method returns a list of images tagged with id that have encountered errors so far.
PARAMETERS id The media tracker id.
RETURNS null if there are no errors or an array of all images that have encountered errors.
SEE ALSO i sE rror ID О , i sErrorAnyQ.
EXAMPLE See the class example.
java.awt
Medi aTracke г
imageUpdatet)
imageLpdate()
PURPOSE This method should not be used.
SYNTAX public boolean 1mageUpdate(Image img, int infoflags, int x, int
A y, int w, int h)
В DESCRIPTION The MediaTracker class implements this method as part of the ImageOb-
C server interface. It should not be used.
n PARAMETERS
и h Depends on the status bits enabled in infoflags.
E i mg The non-nul 1 image being updated.
E i nfoflags Л set of status bits.
G w Depends on the status bits enabled in infoflags.
X Depends on the status bits enabled in infoflags.
H У Depends on the status bits enabled in i nfoflags.
1 RETURNS true if no further calls to the imageUpdateO are needed.
isErrorAnyO
L
purpose Determines it any images encountered an error during loading.
м
T el rpose:
U
v SYNTAX
... PARAMETERS
W
id
X
RETURNS
Y
Z SEE: Al SO
EXAMPLE
syntax public synchronized boolean isErrorAnyO
returns true if any images encountered an error during loading: fal se otherwise.
see also getErrorsAnyO , isErrorID().
P
example See the class example.
Q
R
s isErrorlDC)
Determines if any images tagged with an id encountered an error during load*
ing.
public synchronized boolean isErrorID(int id)
The media tracker id.
true if any of the images tagged with i d encountered an error during loading;
false otherwise.
getErrorsIDO » isErrorAnyO.
See the class example.
1024
LOADIN
loading___________________
PURPOSE Specifies that the image loading process is in progress.
SYNTAX public static final int LOADING
description This field is a status flag that specifies that the image loading process is in progress. Its value is 1.
SEE ALSO statusAll () , statusIDO.
example See the class example.
MediaTracker()
purpose Constructs a MediaTracker object.
SYNTAX public MediaTracker(Component comp)
DESCRIPTION Constructs a new MediaTracker object for the component comp. Hie media tracker will register comp with the image producers of the images it maintains (see ImageProducer) and will process the imageUpdateO notifications from the image producers: these notifications are not passed on to comp. However, even if the media tracker has registered comp, comp is free to register itself with the same image producer if it also desires update notifications. The comp object is used only in a call to comp.preparelmageO to start the loading of the image pixels.
PARAMETERS comp The non-null component on which the images will eventually be drawn.
EXAMPLE See the class example.
removelmage()
PURPOSE Removes an image from the list of images being tracked.
SYNTAX public synchronized void removelmage(lmage image) public synchronized void removelmageflmage image, int id) public synchronized void removelmageCImage image, int id, int w, int h)
DESCRIPTION This method removes an image from the list of images being tracked. If only image is supplied, all instances of image are removed from the list. If the tracking id id is supplied, only instances of the image with id are removed. If width w and height h are specifi££^fift&Jn stances of the image with id and the
java.awt
MediaTracker
status/Mlf)
specified width and height are removed. Images with id but a different width
and height are not removed.
PARAMETERS h A id В image w C SEE Al,SO The height in pixels of the image to he removed from the tracking list, l he media tracking identifier of the images. The non-nul 1 image to be removed from the tracking list. The width in pixels of the image to be removed from the tracking list. addlmageO-
D
statusAII()
G PURPOSE Determines the combined status of all images.
II SYNTAX public int statusAll(boolean load)
1 DESCRIPTION This method determines the status of all images in the media tracker and com-
J bines them into one status. For example, if some image is still in the process of being loaded, this method returns a status with the LOADING Hag set. The status
К for an image that has not started loading is 0.
L If load is true and the images have not started loading, the loading process is
started for these images.
N PARAML 1 ERS
О load If true, lhe loading process is started for all images.
p RETTRNS The bitwise “or" of the status of all images.
pi SEE Al SO ABORTED, COMPLETE, ERRORED, LOADING, statusIDO.
R EX AMPLE See the class example.
s
T statuslD()
- — — — — — — — —
V PURPOSE Determines the combined status of all images tagged with an id.
V SYNTAX public int statusID(int id, boolean load)
W DESCRIPTION This method determines the status of all images tagged with id and combines
X them into one status. For example, if one of the images lagged with id is still ;
Y in the process of being loaded, this method returns a status with the LOADING ’ flag set. The status for an image that has not started loading is 0.
Z If load is true and the images lagged with id have not started loading, the loading process is started for these images.
1026
waitForAll(
statusIDQ calls Component .checkimageQ on lhe images to obtain their statuses in order to construct lhe result.
PARAMETERS id load The media tracker id. If true» the loading process is started for all images tagged with i d.
RETURNS The bitwise “or** of the status of all images tagged with id.
SEE ALSO ABORTED. checkIDO. C0MP1 FTE. LRRORFD, LOADING, statusAl 1().
exampi л: See the class example.
waitForAIK)
PURPOSE Waits for all images to be loaded.
SYNTAX public void waitForAllQ throws InterruptedException public synchronized boolean waitForAll(long ms) throws InterruptedException
DESCRIFI ION This method returns only when all of the images have been loaded or when ms milliseconds have expired. If ms is 0 or not specified, this method blocks until all of the images have been loaded. An image is defined to be loaded if either it successfully loaded or it encoun- tered an error. In other words, this method returns true if no image will receive more pixels. The method isErrorAnyO can be used to determine if an error occurred during the loading of at least one image in the media tracker. This method starts the loading process for any images that have not been loaded. If ms is not specified, this method does not return until ail images have been loaded.
PARAMETERS ms The non-negative length of time in milliseconds to wait for the loading to com- plete.
RETURNS true if all images were successfully loaded.
ЕХСТИ IONS
InterruptedException
If another thread interrupted this thread.
SEE ALSO IsErrorAnyO, waitForlDO.
EXAMPLE See the class example.
java.awt
MediaTracker
waitForlDf)
waitForID()
PI'RPOSE Waits for all images tagged with an id to be loaded.
SYNTAX public void waitForID(int id) throws TnterruptedException public synchronized boolean waitForlDfint id, long ms) throws InterruptedException
DESCRIPTION This method returns only when all of the images tagged with id have been loaded or when ms milliseconds have expired. If ms is 0 or not specified, this method blocks until the images identified have been loaded. An image is defined to be loaded if either it successfully loaded or it encoun- tered an error. In other words, this method returns true if no image will receive more pixels. The method i sErrorlDO can be used to determine if an error occurred during the loading of at least one image in the media tracker. T'his method starts the loading process for any images lagged w ith i d that have not been loaded.
PARAMETERS id The media tracker id.
ms I'he length of time in milliseconds to wait for the loading to complete.
Rl-Tl RN'S true if all images tagged with id were successfully loaded.
EXCEPTIONS
InterruptedExcepti on
If another thread interrupted this thread.
SEE ALSO i sErrorlDO , wai t For All () .
EXAMPLE See the class example.
1028
java.awt. I mage
Memory ImageSource
j
Syntax
public class MemorylmageSource implements ImageProducer
Description
The MemorylmageSource class is used to create an image producer that delivers pixels from a
buffer in memory. The pixel buffer can be a set of 24-bit RGB values or a set of 8-bit values
and a color map. This class is most often used when an image is generated in memory using an
algorithm and then needs to be converted into an image.
For a description of the image consumer and image producer framework, see the Image-
Consumer interface.
Single-frame and Multiframe Modes
The MemorylmageSource class is also capable of creating a muhiframe image. A multiframe
image is an image whose set of pixels can change over time. An example of a multi frame
image is an animated GIF. To create a multiframe image with an memory image source, you
first set lhe memory image source in multiframe (see set Am* mated ()). Once one set of pixels
(a frame) has been created, you next call newPixelsQ to deliver the current frame to the
image consumers. Then you can start creating the next frame.
MEMBER SUMMARY
Constructor MemorylmageSourceО Constructs a new MemorylmageSource instance.
Image Producer Methods addConsumerO i sConsumerO removeconsumerО requestTopDownLeftRi ghtResend() startProductionO Registers an image consumer with this image pro- ducer. Determines if an image consumer is registered with this image producer. Removes a registered image consumer from this image producer. Request by an image consumer to retransmit pixels in top-down, left-right order. Triggers the delivery of image data to an image con- sumer.
Continued
Memory I mageSource
java.awt. image
0
MEMBER SUMMARY
Animation Methods
newPi xels ()
setAni mated()
setFul1BufferUpdates О
A
R
C
Sends pixels to image consumers.
Sets this memory image source to nnilliltame or sin-
gle-frame mode.
Sets whether this memory image source will update |
using complete pixel buffers.
I)
F
G
II
I
j
К
I
Example
This example generates the Mandel-
brot set in a pixel buffer and uses the
MemorylmageSource image pro-
ducer to create an image pixel
buffer. A 16-color index color model
is used to represent the pixel values.
Sec Figure 252.
M
N
О
import java.awt. *;
import java.awt.image.*;
import java.net. •;
import java.uti1. •;
FIGURE 252: MemorylmageSource.
P class Main extends Frame {
Main() {
Q super(“MemorylmageSource Example”);
try {
R add (new MandelbrotCanvas(), BorderLayout.CENI ER);
} catch (Exception e) {
S e . pri ntStackTraceO ;
}
I setSize(300, 200);
show();
l' }
V static public void main(String[] args) {
new Mai n();
\\ }
}
X
class MandelbrotCanvas extends Component {
Image image;
f public void paint(Graphics g) {
if (image == null ) {
image = getToolkit().createlmage(
new MemoryImageSource(300, 200,
1030
JU va.awi.li Iidgu
generateColorModelО, generatePixels(300, 200), 0, 300)
}
g.drawlmage(image, 0, 0, this);
}
IndexColorModel generateColorModel() {
byte[] r ~ new byte[16J;
byte[] g = new byte[16];
byte[] b = new byte[161;
r[0] =0; g[0] - 0; b[0] - 0;
r[l] = O; g[l] = 0; b[l] = (byte)192;
r[2] = 0; g[2J = 0; b[2] - (byte)255;
r[3] = 0; gLBJ = (byte)192; b[3] - 0;
r[4] = 0; g[41 = (byte)255; b[4] = 0;
r[5] = 0; g[5] - (byte)192; b[5] = (byte)192;
r[6] = 0; g[6J = (byte)255; b[6] = (byte)2S5;
r[7] = (byte)192; g[7] - 0; b[71 - 0;
r[8] - (byte)255; g[8Z -= 0; b[8] - 0;
r[9] = (byte)192; g[9J = 0; bL9J = (byte)192;
r[10J = (byte)255; g[10] - 0; b[10] = (byte)255;
r[ll] - (byte)192; g[ll] = (byte)192; b[ll] = 0;
r[12] зг (byte)255; gfl21 = (byte)255; b[12J - 0;
r[13J = (byte)80; g[13] = (byte)80; b[13] = (byte)80;
r[14] = (byte)192; g[14J = (byte)192; b[14] = (byte)192;
r[15] - (byte)255; g[151 = (byte)255; b[15] - (byte)255;
return new IndexColorModel(4, 16, r, g, b);
}
final float xmin = -2.0f;
final float xmax = 1.2f;
final float ymin = -1.2f;
final float ymax - 1.2f;
byte[] generatePixels(int w, int h) {
byte[] pixels = new byte[w * h];
int plx = 0;
float Г] p = new float [w];
float q = ymin;
float dp = (xmax-xmin)/w;
float dq - (ymax-ymin)/h;
p[0] = xmin;
for (int i=l; i<w; i++) {
p[i] = pH-lJ + dp;
}
for (int r=0; r<h; r++) {
for (int c=0; c<w; c+*) {
int color 1;
float x = 0.0f;
float у = 0.0f;
float xsqr - 0.0f;
float ysqr = 0.0f;
do {
xsqr x 'x;
ysqr = y*y;
у = 2*x*y + q;
x = xsqr ysqr + рГс] ;
С01ОГЧ-+ ;
java.awi.image
MemorylmageSource
addConsurneix)
} while (color < 512 && xsqr * ysqr < 4);
pixels[plx++] - (byte)(color % 16);
}
q »= dq;
}
return pixels;
addConsumer()
PER POSE Registers an image consumer with this image producer.
SYNTAX public synchronized void addConsumer(ImageConsumer ic)
DESCRIPTION This method registers the image consumer i c to receive pixels from this image producer. If i c is already one of its consumers, this method does nothing. Sec ImageProducer.addConsumerO for details on how an image consumer should use this method.
PARAMETERS ic The non-nul 1 image consumer to register.
SEE ALSO ImageConsumer.
EXAMPLE See ImageProducer.addConsume r().
isConsumer()
PURPOSE Determines if an image consumer is registered with this image producer.
SYNTAX public synchronized boolean isConsumer(ImageConsumer ic)
DESCRIPTION See ImageProducer.isConsumer0 for details on how an image consumer should use this method.
PARAMETERS ic 1'he possibly null image consumer to check if registered.
REIVRNS true if i c has been registered; fal se otherwise.
SEE ALSO ImageConsumer
exam pit: See ImageProducer. i sConsumerO.
1032
1*1 V <1.41 v> I, III .MVIHVIJ lIUUpAJVUI V
Memory I mage Sou reel
MemorylmageSource()
PURPOSE Constructs a new MemorylmageSource instance.
SYNTAX public MemoryImageSource(int width, int height, int[] pixels, int offset, int scansize) public MemorylmageSourcefint width, int height, intfl pixels, int offset, int scansize, Hashtable props) public MemorylmageSource(int width, int height, ColorModel cm, byte[] pixels, int offset, int scansize) public MemoryTmageSourcefint width, int height, ColorModel cm, int[] pixels, int offset, int scansize) public MemoryImageSource(int width, int height, ColorModel cm, byte[] pixels, int offset, int scansize, Hashtable props) public MemoryTmageSource(int w, int h, ColorModel cm, int[] pixels, int offset, int scansize, Hashtable props)
DESCRIPTION This constructor constructs a memory image source (image producer) that delivers pixels from a memory buffer. The memory image source is in single- frame mode by default. width and height specify the width and height of the image. pixels contains the pixel values of the image. The first pixel value is located at pixels [offset] and each row of pixel values in pix occupies scansize elements. In summary, lhe pixel (x. y) (the top-left corner pixel of the image) is stored in the pix array at [x - у * scansize + offset). cm specifies the color model in which the pixel values in pixels are encoded. If cm is not specified, the default color model is used (see the ColorModel class). props is a hash table of image properties (see ImageConsumer) that the new image producer should deliver to the image consumer. If props is not speci- fied or is null, an empty hash table is delivered to the image consumer.
PARAMETF RS cm height offset pixels props scansize width l he non-nul 1 color model. The height of the image in pixels. The index of the first pixel value in pixels. The buffer of pixel values. The possibly null hash table of image properties. The width to use when extracting pixels from the pi xel s array. The w idth of (he image in pixels.
see: also ColorModel.getRGBdefau1t().
example- See the class example.
ja\a.awt, image
M emory ImageSou rce
newPixclsf)
newPixels()
Pl RPOSl- Sends new pixels to image consumers.
SYNTAX public void newPixelsQ
A public synchronized void newPixels(byte[J pixels, ColorModel cm, int offset, int scanSize)
ti public synchronized void newPixels(int[1 pixels, ColorModel cm,
C int offset, int scanSize) public synchronized void newPixels(int x, int y, int width, int
D height)
public synchronized void newPixe1s(int xT int у, int width, int
E height, boolean frameNotify)
F DESCRIPTION This method sends a new sei of pixels to its image consumers. It is effective
G only if this memory image source is in multiframe (animated) mode: other-
H u ise. it is ignored. The first three forms of this method send pixels from the complete image.
1 When an array of pixels pixels is supplied, this method first updates this
J memory image source’s pixels, color model, offset, and scansize using the
К r arguments specified before sending the complete image. The last two forms of this method send pixels from a rectangle within the
L memory image source, frameNotify specifies whether to send a SINGLE-
FRAMTDONE notification with the pixels. If frameNotifу is unspecified, it
N defaults to true.
() PAR AMFTFRS
cm The non-null color model.
P f rameNoti fy If true, sends consumers a SINGl EFRAMEDONE notification; if fal se. does not
Q send SINGLEFRAMEDONE notification to consumers.
p height The height of the rectangle of pixels to send.
lx offset The index of the first pixel value in pixels.
s pi xels The buffer of pixel values.
T scansize The width to use when extracting pixels from the pixel s arrax.
i; width The w idth of lhe rectangle of pixels to send.
X The t-coordinate of the northwest corner of the rectangle of pixels to send.
V У The v-coordinate of the northwest corner of the rectangle of pixels to send.
w SI I- Al SO addConsumerO, setAnimated(), setFullBufferUpdates().
X EXAMPLE See setAnimated().
removeConsumerf)
pi rpose Removes a registered image consumer from this image producer.
1034
ja> Cl.aw I. Illidge
req ucs tTopDown Left Right Re sen d()
SYNTAX public synchronized void removeConsumer(ImageConsumer ic)
DESCRIPTION See ImageProducer.removeConsumerQ for details on how an image con- sumer should use this method.
PARAMI-II-RS ic The non-nul 1 image consumer to be removed.
EXAMPLE- See ImageProducer.removeConsumerQ.
requestTopDownLeftRightResendl)
purpose: Requests by an image consumer to retransmit pixels in top-down, left-right order.
SYNTAX public void requestTopDownLeftRightResend(TmageConsuTer ic)
DESCRIPTION See ImageProducer.requestTopDownl eftRightResendQ for details on how an image consumer should use this method. The implementation of this method for MemorylmageSource does nothing because a single-frame image is already in top-down, left-right format, and top down, left right format is not relevant fora multiframe image.
PARAMETERS i c The non-null image consumer requesting the retransmission.
SEEALSO ImageConsumer.
EXAMPLE See ImageProducer. request TopDownLeftRi ghtResendQ.
set A ni ma ted ()
purpose: Sets this memory image source to multi frame or single-frame mode.
SYNTAX public synchronized void setAnimated(boolean animated)
description If this method is used, it must be called immediately after the Memoryimage- Source instance is created to ensure that all image consumers receive the cor- rect data. If an image consumer is added after this Gag has been set. the image consumer may see only a snapshot of the data. If the memory image source is being set to single-frame mode (animated is false}. STAIICIMAGEDONE is sent to all existing consumers and lhe list of consumers is cleared.
Memory ImageSource
setAnimatcd()
jax a.aw (.image
A
В
C
I)
E
F
G
II
I
.1
К
I.
N
()
P
Q
R
S
1'
u
V
w
X
Y
Z
FIGI RE 253: Animator.
M
PARAMETERS
animated If’true, seis image to mulliframe mode: if false, sets image to single-iiame
mode.
shi- also setFul 1 Buf ferUpdates ().
ex .am pi i This example demon-
strates how to use the
memor\ image source to
create an animated
image. I'he program first
reads in an image and
then uses a pixel grabber
to extract the pixels.
The Animator class is a
thread that selectively
copies portions of the
image's pixels into a
blank pixel buffer. Each
time some pixels are copied into the pixel buffer, the thread notifies the image
consumers. The resulting effect is that the image appears in a progressive lash-
ion instead of all at once. See Figure 253.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.л;
class Main extends Frame {
Image image;
Main(String filename) {
super(“setAnimate Example”);
image = new Animator() . getlmage(getlool к i t (I. gctlmaget.fi 1 ename) );
// Set the initial frame size and show the image.
setSize(300, 390);
show();
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
g.drawlmage(image, getlnsets(). 1 eft, get Insets О.top, this);
}
public static void main(String[J args) {
if (args.length == 1) {
new Mai n(args[0]);
} else {
System.err.print 1n(“Usage: java Main <.image Filo"):
}
}
1036
set Animate*
}
class Animator extends Thread {
PixelGrabber pg;
MemorylmageSource mis;
bytef] oldPixels;
bytef] newPixels;
Animator^ {
}
Image getlmage(lmage image) {
pg - new PixelGrabber(image, 0* 0, -1, -1, false);
try {
pg.grabPixels();
} catch (Exception e) {
e. pri ntStackl raceQ ;
}
// We only handle 8-bit images.
if (! (pg. getPixelsO instanceof bytef])) {
return null;
}
oldPixels - (bytef])pg.getPixels();
// Start the animation.
start();
newPixels = new byte[oldPixels.1ength];
mis = new MemoryTmageSource(pg.getWidth(), pg.getHeightO,
pg.getColorModel (), newPixels, 0, pg.getWidthO);
mis.setAnimated(true);
mis.setTullBufferUpdates(true);
return Toolkit.getDefaultToolki t().createlmage(mis);
}
int random(int r) {
return (int)Math.floor(Math.random()*r);
}
public void run() {
int w = pg.getWidthO;
int h = pg.getHeight ();
int[] x - new intfh];
int inc - w/20;
boolean done = false;
try {
while (Idone) {
done - true;
// Modify buffer.
for (int i^0; i<h; i-»--♦-) {
if (x[i ] < w/2 && random(3) — 0) {
// From the left.
int count - Math.min(inc, w-inc);
System.arraycopy(оIdPixels, i*w+xf i ],
newPixels, i*w+x[i], count);
// From the right.
Memory ImageSource
setFull Buffer!’pdates()
java.awt.image
count - Math.min(inc, w-inc);
System.arraycopy(oldPixels, (i+l)*w-x[i2 count,
newPixels, (i+1)*w-x[ij-count, count);
x [i] += inc;
}
if (xfi] < w/2) {
A done = false;
}
В }
C // Send the new pixels to the consumers.
mis.newPixels(0, 0, pg.getwidth(), pg.getHeight());
1) Thread. sleep(33);
}
h } catch (Exception e) {
e.printStackTraceO ;
F }
}
G }
H
J setFullBufferUpdatesC)
к PVRPOSE Sets whether this memory image source will update using complete pixel buff-
L ers.
SYNTAX public synchronized void setFul1BufferUpdatesfboolean full)
KI DESCRIPTION This method is effective only if this memory’ image source is in multiframe
mode; otherwise, this method does nothing.
() If this method is used, it should be called immediately after the Memoryimage-
p Source instance has been created to ensure that all image consumers receive
Q the correct pixel delivery hints.
PAR.AMEI ERS
к full If true, complete pixel buffers will be sent during updates: if false, only
S' updated pixels will be sent.
I see: also newPixels(), setAnimatedO.
i; EXAMPLE See setAnimatedO.
V
w startProductionf)
X Y PI’RK JSE Triggers the delivery of image data to an image consumer.
z SYNTAX public void startProduction(ImageConsumer ic)
DESCRIPTION See ImageProducer. startProductionQ for details on how- an image con-
sumer should use this method.
1038
start Prod и с
parameters ic The non-null image consumer ready to receive pixels.
SEEALSO ImageConsumer.
EXAMPLE. Sec ImageProducer,startProduction().
java.awt
Menu
Syntax
public class Menu extends Menuitem implements Menucontainer
Description
A menu is an object that is inserted
into a menu bar. Sec also Menu Bar.
Menus contain menu items. Figure
254 shows a menu bar with two
menus: File and Edit, l he File menu
is active: it contains two menu items:
New and Open... .
Menu Bar
Menu hems
The Label Property HGl RE 254: The Three Kinds of Menu Components.
A menu has a label, which is used
when inserted into a menu bar. The
menu bar normally displays only the menu’s label. When the user clicks the menu’s label, (he
menu appears.
T The Tear-off Property
Some platforms support the menu icar-ofl property. If this property is supported and enabled,
(he user can make a user interface gesture to clone lhe menu as a top-lexel window. When a
menu is lorn off. both the original menu on the menu bar and the torn-off menu can be used to
W select menu items. The torn-off menu can be deleted b\ the user when it is no longer needed.
X
Cascading Menus
Y A cascading menu is created by adding a menu within another menu. There is no limit to the
У level of nesting of menus within another menu (see the add() example). When a menu dis-
plays its menu items, it typically shows menus differently that it does terminal menu items. For
1040
java.awt
example, on the Windows platform, menus have an arrow beside them. The visual indication
for menu items that are menus is platform-dependent.
Keyboard Shortcuts
The user can select an enabled menu item within a menu by either using mouse actions or by
pressing the menu item's keyboard shortcut. Keyboard shortcuts for menu items inside cascad-
ing menus work in the same way they do for those inside noncascading menus. See MenuTtem
for details on keyboard shortcuts.
Events
When a menu item within a menu is selected, the menu item fires an action event (see Menu-
Item). The AWT does not require the programmer to enable action events for each menu item
in a menu by adding action listeners to each menu item. Instead, it allows action listeners to be
added to a menu. If a selected menu item does not have action events enabled but its parent
menu does, the action event is passed up to the menu. Consequently, although a menu does not
actually generate any events, it can be used to forward events fired by its menu items. In this
way, a program needs only to enable action events for a menu and not individually for each
menu item. When such an event is passed up. the event source of lhe event is the menu and not
the menu item that was selected.
Note that such forwarding of action events is done only for one level of the menu contain-
ment hierarchy. More specifically, action events fired by a cascaded menu's menu items are
not passed up to the cascaded menu's parent menu. Consequently, to handle action events tired
by a cascaded menu's menu items, you need to add action listeners to the cascaded menu or to
the cascaded menu's menu items. See the add О example.
MEMBER SUMMARY
Constructor
Menu() Constructs a new' Menu instance.
Menu Item Methods
add О
addSeparatorO
i nsertO
InsertSeparatorO
getltemO
getltemCountO
removeО
removeAl1()
Appends a menu item to this menu.
Appends a menu item separator to this menu.
Inserts a menu item to this menu at a specified position.
Inserts a menu item separator to this menu al a specified position.
Retrieves a menu item from this menu.
Retrieves the number of menu items in this menu.
Removes a menu item from this menu.
Removes all menu items from this menu.
Continued
.Menu
java.aw l
MEMBER SUMMARY
Property Method i sTearOff() Determines if this menu is a tear-off menu.
\ Peer Methods
в addNoti fy() Creates this menu's peer hierarchy.
removeNoti fy() Destroys this menu's peer hierarchy
Debugging Method i
paramString О Generates a string representing this menu's stale.
к Deprecated Method
1- countitems() Replaced by getltemCountO.
(i
See Also
java.awt.event.ActionEvent, java.awt.event.Acti onLi stener, MenuBar,
MenuComponent, MenuContainer, Menuitem.
Example
This example implements a menu whose menu
items are always changing. (For a simpler example
using a menu, see the Menu constructor example.)
See Figure 255. It creates a Command menu that
maintains a fixed list of commands. Each time a
command is executed, it gets added to the top of
the menu. If a command already appears in the
menu, it is moxed to the top of the menu. The
menu can hold only ten commands, so if the menu
is full, the menu item al the bottom of the list is
first removed before a new command is added.
import java.awt.';
import java.awt.event.*;
import java. uti 1 . ;
class Main extends Frame implements
ActionListener {
Vector commands - new Vector();
Menu m = new Menu(“Commands");
Main() {
super(“Menu Example”);
MenuBar mb = new MenuBarO;
Menu Example ВЕЭЕЗ
Commands
appletviewer index, html
dir
explorer c:\autoexec.bat
hotjava www.sun.corn
dir/s Main.java
delx. class
javac Main, java
java Main
vi Main, java
copy a:x.x c:\temp
appletviewei index htrtil|
1 IGl RI< 255: Ih iiuiiiicalh tpdated Menu.
1042
javii.avH
// Add menu to menu bar.
mb.add(m);
// Set the menu bar on the frame.
setMenuBar(mb);
TextField tf = new TextFieldO;
add(tf, BorderLayout.SOUTH);
tf.addActionListener(thi s);
setSize(100, 100);
showO :
}
void updateMenu(Menu m) {
// First remove all the menu items.
m.removeAl1 О;
// Then add them back in.
for (int i^0: i<commands.sizeO ; i+*) {
m.add((Stri ng)commands.e1ementAt(i));
}
}
public void addCommand(String cmd) {
for (int i=0; i<m.getltemCountO; ii*) {
Menuitem mi - (Menultem)rr. getltem( i);
if (mi.getLabel().equals(cmd)) {
// Move command to top of list,
commands.removeElementAt(i);
commands.insertElementAt(cmd, 0);
updateMenu(m);
return;
}
}
if (m.getltemCountO >= 10) {
// Remove last command from list.
commands.removeElementAt(commands.si ze()-1
}
commands.insertElementAt(cmd, 0);
updateMenu(m);
}
// Action handler for text field
public void actionPerformed(ActionEvent evt) {
String what ~ evt. getActionCommandO;
if (!what .equalsC")) {
addCommand(what);
((TextField)evt.getSourceO).setText("“);
}
static public void main(String[j arqs) {
new Main();
}
Menu
add()
jax a.aw I
add()
n rpose Appends a menu item io this menu.
sym-w public synchronized Menuitem add(MenuItem menuitem)
public void addfString label)
В DI.SCRIP! I()\ This method adds the menu item menuitem to the cud of this menu. If lhe
string label is specified instead of a menu item, a menu item with the label
c label is automatical!) created and added to the menu. If label is ” a sepa-
II rator is added to the menu. If the menu item ahead) has a parent, il is Him
Г- I- removed from its parent before being added to this menu. Since Menu is a subclass of Menuitem, menuitem can be a Menu, in which ease
it would create a cascading menu off of this menu.
V 1 PARAMETERS
H 1 abel The non-null siring specif) ing the label of the menu item.
I menuitem The non-null menu item.
The first form of add() returns the menu item added (menuitem).
addSeparator(), insertQ, remove().
This example creates a cou-
ple of cascading menus
(menus with submenus).
See Figure 25b. An action
listener is added to each of
the menus because action
exents do not propagate
more than one ancestor
lex el.
< Cascading Example И0Е
New ►
Import ►! Format ►
Save
Exit
File Paragraph
FIGI RE 256: Cascading Menus.
import java.awt.-;
import java.awt.event.'-;
class Main extends Frame implements ActionListener {
Main() {
super(“Cascading Example");
MenuBar mb = new MenuBarO;
Menu m new Menu(“Fi1e");
Menu newMenu = new Menu(“New");
Menuitem mi = newMenu.add(
new MenuItem(“Directory", new MenuShortcut(KeyEvent.VK_D)));
mi.setAc ti onCommand(“Directory");
mi = newMenu.add(
new MenuItem(“Fi1e", new MenuShortcut(KeyEvent.VK_F)));
mi.setActionCommand(“Fi1e”);
m.add(newMenu);
1044
add Notify
Menu imp = new MenuC'Import’1);
Menu format = new Menu(“Format");
format.addCCharacter") ;
format.add(“Paragraph");
format.add(“Variable Definition");
imp.add(format);
imp.addC'File");
m.add(imp);
m.add(“Save");
m.addSeparator();
m.add(“Exi t”);
mb.add(m);
// Add action listener for main menu and submenus
m.addActionLi stener(this);
newMenu.addActi onLi stener(thi s);
imp.addActionLi stener(thi s);
format.addActionLi stener(thi s);
// Set the menu bar on the frame.
setMenuBar(mb);
setSize(100, 100);
show();
}
public void actionPerformed(ActionEvent evt) {
System, out. pri ntl n(evt .getActionCommandO);
static public void main(String[] args) {
new Main();
}
}
addNotify()
Pl RPOSE Creates this menu’s peer hierarchy.
SYNTAX public void addNotifyO
DESCRIPTION This method creates the menu s peer hierarchy if it does not yet exist. The menu's peer is created by calling the Tool kit. createMenuO method. 'This method should never be called directly. It is normally called by the menu com- ponent's container.
OVERRIDES MenuItem.addNotifyO.
SEE ALSO Toolkit.
EXAMPLE The usage of addNotifyO is similar to Component.addNotify(). See the class example of MenuContainer for the usage of Component. addNotifyO.
add Separator )
Menu
ja\ a.aw l
addSeparator()
Pl'RPOSt
Appends a menu item separator to the menu.
public void addSeparator()
A
DESCRIP I ION
В
This method creates a menu item with the label and adds it to the end of
the menu.
D
F.
F
К
M
N
()
P
Q
R
V
X
see al.so
EXAMPLE
i mport
add(), insertSeparatorQ•
This example creates a menu with three
menu items, one enabled and two disabled.
A separator is added after the first two
menu items. See Figure 257.
java.awt
class Main extends Frame {
Main() {
super(“addSeparator Example”);
MenuBar mb = new MenuBarO;
Menu m = new Menu(“Fi1e”);
Menuitem mi = m.add(new MenuItem(“New”));
mi.setEnabled(false);
m.add(“Open...”);
m.addSeparator();
m.add(“Exi t”);
mb.add(m);
// Set the menu bar on the frame.
setMenuBar(mb);
setSize(100, 100);
showO ;
static public void mai n(St ri ng [] args) {
new Mai n();
countltems()
PURPOSE
Replaced by getltemCountO.
public int countltemsO
RETURNS
The number of menu items in the menu.
DEPRECATION
FIGI RE 257:
Menu.addSeparator().
l)I PRi:( \ TE1
Replace the usage of this deprecated method, as in
int count = menu.countitems О;
with
int count = menu.getltemCountO;
1046
getlteinf
getltem() — ..
PURPOSE Retrieves a menu item from this menu.
SYNTAX public Menuitem getltemfint pos)
description This method retrieves the menu item at index pos in this menu.
returns The menu item at the index pos.
parameters pos The zero-based index of the menu item in this menu.
exceptions
ArraylndexOutOfBoundsExcept!on
If pos is greater than getltemCountO-1.
SEE: ALSO getltemCountO. java.lang.ArraylndexOutOfBoundsException.
EXAMPLE: See the class example.
getItemCount()
PURPOSE Retrieves the number of menu items in this menu.
SYNTAX public int getltemCountO
DESCRIPTION This method retrieves the number of menu items in this menu, including any menu item separators.
RETURNS The number of menu items in this menu.
EXAMPLE: See the class example.
insert()
PURPOSE Inserts a menu item to this menu at a specified position.
SYNTAX public synchronized void insert(Menuitem menuitem, int pos) public void insert(String label, pos)
DESCRIPTION 'This method adds the menu item menuitem to this menu at position pos. All menu items at position pos or greater prior to the addition are shifted up one position in the menu. If lhe string label is specified instead of a menu item, a menu item with the label label is automatically created and added to the menu. If label is a separator is added to the menu. If the menu item already has a parent, it is first removed from its parent before being added to lhe menu.
Menu
insert()
java.awt
PARAMETERS
1 abel
menuitem
pos
The non-null string specifying the label of the menu item.
The non-null menu item.
The zero-based index in this menu to insert lhe menu item.
EXCEPTIONS
В II legalArgumentException
If pos is negative.
seealso add(), insertSeparatorQ, java.1ang.Il 1egalArgumentException,
remove О.
E
F
G
H
1
J
К
E
M
N
example This example accepts words from a text field
and adds each word as a menu item to the top
of the menu. Each set of words is separated
by a separator. See Figure 258.
import java.awt.-';
import java.awt.event.-';
import java.util.StringTokenizer;
class Main extends Frame implements ActionListener
{
Menu m = new Menu(“Words”);
boolean first = true;
Main() {
super(“insert Example”);
MenuBar mb = new MenuBarO;
« insert Example
Г <
load
save
Insert
delete
add
load save
FIGURE 258: Menu . insert () .
()
P
Q
R
S
T
LI
V
W
X
Y
Z
// Add menu to menu bar.
mb.add(m);
// Set the menu bar on the frame.
setMenuBar(mb);
TextField tf = new TextFieldO;
add(tf, BorderLayout.SOUTH);
tf.addActionLi stener(thi s);
setSize(100, 100);
show() ;
}
void addWords(String sentence) {
StringTokenizer parser = new StringTokenizer(sentence);
int i ;
for (i = 0; parser.hasMoreTokens(); i++) {
m.insert((String)parser.nextElement(), i);
}
if (’first) {
m.i nsertSeparator(i);
} else {
first = false;
}
I
1048
java.awt
insert Separator
// Action handler for text field
public void actionPerformed(ActionEvent evt) {
String what - evt .getActionCommandO;
if (’what. equal s(k“‘) ) {
addWords(what);
((TextFi eld) evt. getSourceO). set Text ("“) ;
}
}
static public void main(String[] args) {
new Main();
}
}
insertSeparator()
PURPOSE Inserts a menu item separator to the menu at a specified position.
SY VI AX public void insertSeparator(int pos)
DESCRIPTION This method creates a menu item with the label and adds it to this menu at position pos. All menu items at position pos or greater prior to lhe addition are shifted up one position in the menu.
PARA ME I ERS
pos The zero-based index in this menu to insert the menu item.
EXCEPTIONS
IllegalArgumentException
If pos is negative.
SEE ALSO addSeparatorO, insertO.
EXAMPLE See 1nsert().
isTearOfff)
PURPOSE Determines if the menu is a tear-off menu.
SYNTAX public boolean isTearOff()
DESCRIPTION If a menu is a tear-off menu, the user can make a user interface gesture to clone the menu as a top-level window. See the class description for more information about tear-off menus.
RETURNS true if the menu is a tear-off menu: fal se otherwise.
Menu
Menu! )
jax a.aw t
Menu()
in rposi Constructs a new Menu instance.
sy\i w publ i c Menu()
A public Menu(String label)
public Menu(String label, boolean tearOff)
В
di si ripiios This constructor creates a new menu w ith the label label. II no label is speci-
I'ied. it defaults to an empt\ label If tearOff is true, then the menu can
I) be torn off. If tearOff is not specified, it defaults to false. See the class
P description for details on tear-off menus. If an AWT implementation does not
support :ear-off menus. tearOff is ignored.
F
P \R Wil П-RS
<‘I label The non-null string specif} ing the menu's label.
H tearOff Specifies whether the menu can be lorn off.
I J IX W1PI 1. This example creates a menu bar that has a single menu, which has a single menu item. It demonstrates how to process action Menu Example B|"1E3|
^^tenu
к 1. exents tired b\ the menu item within the menu. See Figure 259. Menuitem
N i mport i mport j ava . awt. * ; java, awt. event.; ! IGl RI 259: Menu.Menu().
() public class Main extends Frame implements ActionListener {
Menu rn = new Menu (“Menu”);
P
Main О {
Q super(“Menu Example”);
MenuBar mb = new MenuBarO;
R
// Add item to menu.
S m.add(“MenuItem”);
T // Add listener for menu
m.addAct i onLi stener(this);
Li
// Add menu to menu bar
V mb.add(m);
\\ // Set menu bar on frame.
setMenuBar(mb) ;
X
set S i ze(100, 100);
Y showO;
}
Z
// Action handler for menu
public void actionPerformed(ActionEvent evt) {
System.out.pri ntln(evt.getActi onCommand());
1050
paramStringt
}
static public void main($trinq[] args) {
new Mai n();
}
}
paramStringf)
PURPOSE Generates a string representation of this menu's state.
syntax public String paramStringO
DESCRIPTION The returned string includes an indication of whether the menu is a tear-off menu or a Help menu, plus that menu's menu item string representation. This method is called by the toString() method and is typically used for debug- ging.
RETURNS A non-nul 1 string representing lhe menu item's state.
OVERRIDES venultem. paramStri ngQ.
SEE ALSO MenuComponent.toStri ng О, java.1ang.Object.toString().
EXAMPLE See Component.paramStri ng().
remove()
PURPOSE Removes a menu item from this menu.
SYNTAX public synchronized void remove(int pos) public synchronized void remove(MenuComponent menuitem)
DESCRIPTION This method removes the menu item menuitem from this menu. If menuitem is not in the menu, this method call is ignored. If pos is specified instead of menu Item, then the menu item at index pos is removed.
parameters menuitem The non-null menu item in the menu.
pos The /его based index of the menu item in lhe menu.
SEE Al,SO add(), addSeparatorQ , insertO, insertSeparator() , removeAl1().
Menu
java.awl
remove AIR )
example This example creates a menu that has five
items. Pressing lhe Rotate but ton brings the top
menu item to lhe bottom. See Figure 260.
A
В
c
D
E
I
G
H
I
J
import java.awt.--';
import java.awt.event;
class Main extends Frame implements ActionListener!
Menu m = new Menu(“Menu”);
Main() {
super(“remove Example”);
MenuBar mb = new MenuBarO;
// Add 5 menu items
for (int i =0; i < 5; i++) {
m.add(“i tem “ + i) ;
}
К
I.
M
N
IK,ERE 2<»(): Rotating Menu
Items.
// Add increment button.
Button b;
add(b = new Button(“Rotate”), BorderLayout.SOUTH);
b.addActi onLi stener(thi s) ;
// Set the menu bar on the frame,
mb.add(m);
setMenuBar(mb);
setSi ze(100, 100);
showO ;
// Action hardier for button
public void actionPerformed(ActionEvent evt) {
Menuitem top = m.getltem(0);
” m.remove(0);
m.add(top);
R static public void main(String[] args) {
new Main!);
s }
V removeAll()
w PURPOSE Removes all menu items from this menu.
X
Y SYNTAX public synchronized void removeAll()
SEI ALSO removeQ.
7. LX \MPLE See the class example.
1052
java.dWL Л1«1
removeNoti fy(
removeNotifyO
PURPOSE Destroys this menu's peer hierarchy.
SYNTAX public void removeNotifyO
DESCRIPTION This method should never be called directly. It is normally called by the com- ponent's container.
OVERRIDES MenuComponent.removeNoti fу().
EXAMPLE The usage of removeNotifyO is like that of Component.removeNotify(). See Component.setVisi ble() for a usage example of Compo- nent ,removeNoti fy().
java.awt
MenuBar
A
В
C
D
Syntax
public class MenuBar extends MenuComponent implements MenuContainer
Description
The menu bar is a strip across the lop
of a frame. If the frame has a title bar.
the menu bar is located directly under
lhe title bar. On some platforms, the
menu bar appears al lhe top of lhe
screen. The menu bar contains menus.
Normally, only the menu labels are
displayed. If the user clicks a menu
label, lhe menu associated with the
Menu
Menu Bar
Menu Items
FIGI RI' 261: l he three Kinds of Menu Components.
label appears.
Figure 261 shows a frame with both a title bar and a menu bar. I’hc menu bar contain^ two
menus: File and Fdit. The File menu is being displayed; it contains two menu items: New and
Open....
l he list of menus in a menu bar can be modified at any time, regardless of whether the
menu bar is installed. However, a menu can be inserted in only one menu bar al a time.
The only valid parent for a menu bar is a Frame instance.
The Help Menu
There is a special menu designated the Help menu. The only thing special about the Help
V menu is that on some platforms, it appears at the right edge of the menu bar.
w Keyboard Shortcut
X The user can access menu items contained w ithin a menu in lhe menu bar by entering the menu
item's keyboard shortcut. See the Menultem's class description for details. The menu bat class
contains methods for finding and deleting menu short cuts within its hierarchy, as well as a
/ method for enumerating all shortcuts.
1054
Events
A menu bar does not fire any events.1
ДЬдьпмг» SUMMARY
Constructor MenuBarO i Constructs a new MenuBar instance. ;
Menu Methods addO getMenuO getMenuCountO remove() ?\dds a menu to this menu bar. | Retrieves a menu on this menu bar. i Retrieves the number of menus on this menu bar. । Removes a menu from this menu bar.
Help Menu Methods getHelpMenuO setHelpMenuO Retrieves this menu bar's Help menu. Replaces this menu bar's Help menu.
Keyboard Shortcut Methods
deleteShortcutO getShortcutMenuItemO Deletes a keyboard shortcut from menu items in this menu bar. Retr ieves the menu item in this menu bar that has the specified keyboard shortcut.
shortcutsO Lists the keyboard shortcuts of menu items in this menu bar.
Peer Methods
addNoti fyO
removeNotifyO
Deprecated Method
countMenusO
Creates this menu bar's peer.
Destroys this menu bar s peer.
Replaced by getMenuCountO
See Also
Frame.getMenuBarQ, Frame.setMenuBarО, Menu, MenuComponent,
MenuContainer, Menuitem, MenuShortcut.
I - In the deprecated Java 1.0 event model (Event), events fired by menu items contained in the
menu bar can be passed up to the menu bar. These events are automatically passed on to the
menu bar's frame. You can handle these events by overriding the frame’s handl eEventО
method.
MenuBar
java.aw I
A
В
Example
This example creates a menu bar with three menus. See
Figure 262. To keep it short, onl\ the File menu con-
tains two menu items: New and Open... . This example
also shows how to catch action events fired by menu
items. For details on these events, see the Menultem
Щ MenuBar Example BEE
File
| Edit Help
New
Open...
D
import java.awt.
import java.awt.event
FKJVRE 262: MenuBar.
E
F
class Main extends Frame implements ActionListener {
MainQ {
super(“MenuBar Example”);
MenuBar mb = new MenuBarQ;
Menu m = new Menu(“Fi1e”);
H
m.add(“New”) ;
m.add(“Open...”);
m.addActi onLi stener(thi s);
mb.add(m);
К
L
// To keep it short, these menus don’t have
mb.add(new Menu(“Edi t”)) ;
mb.setHelpMenu(new Menu(“Help”));
menu items.
M
// Set the menu bar on the frame.
setMenuBar(mb);
N
()
setSize(200, 100);
show() ;
P
Q
R
public void actionPerformed(ActionEvent evt)
String what = evt. getActi onCommandQ ;
if (“New”.equals(what)) {
// do new
System.out.println(“action performed
} else if (“Open...”.equals(what)) {
// do open
System.out.pri ntln(“acti on performed
on
on
New”);
Open ...”);
U
V
public void mai n(Stri ng[] args) {
stati c
new Mai n () ;
W
1056
add()
add(£
purpose Adds a menu to this menu bar.
SYNTAX public synchronized Menu add(Menu menu)
description This method adds a menu to the end of the menu bar. If the menu already has a
parent, it is first removed from its parent before being added to the menu ban
This means that the same menu cannot be inserted into more than one menu
bar.
There is currently no way to insert a menu in the middle of a menu bar. To
work around this, you need to remove all of the menus and reinsert them, plac-
ing the new menu in the desired spot.
PARAMEl'ERS
menu The non-null menu to be added to the menu bar.
SEEALSO Menu.
example This example creates a frame that has a checkbox.
Only when the checkbox is checked does the Edit
menu appear on the menu bar. See Figure 263.
Figure 264 shows the Edit menu present.
import java.awt.*;
import java, awt .event ;
class Main extends Frame implements ItemListener {
Menu editMenu - new Menu(“Edit”);
Checkbox editMenuCheckbox =
new Checkbox(“Edit Menu”);
FIGURE 265: Before
MenuBar.addО •
FIGURE 264: After
MenuBar.add().
Main() {
super(“add Example”);
MenuBar mb = new MenuBarO;
mb.add(new MenuC'File”));
setMenuBar(mb);
add(edi tMenuCheckbox, Bordert ayout.NORTH);
editMenuCheckbox.addlteml i stener(this);
setSize(100, 100);
show();
}
static public void main(String[2 args) {
Mai n m = new Mai nO ;
}
// Item handler for checkbox
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChangeO ItemEvent.SELECTED) {
getMenuBarO .add(edi tMenu) ;
1ЛС-Т
java.awt
MenuBar
addNotifyf)
} else {
getMenuBarO.removefedi tMenu);
}
В
addNotify()
D 14 RPOSF (’reales this menu bar's peer hierarchy.
E SYNTAX public, void addNotifyO
F DESCRIPTION This method creates the menu bar's peer hierarchy, if it does not exist. The
Ci menu bar's peer is created by calling the Toolkit.createMenuBarQ method. Phis method should never be called directly. It is normally called by
H I SEE /ALSO the menu component's parent. Component, Toolkit.
DEPRECATED
к countMenusf)
L PURPOSE Replaced by getMenuCount().
SYNTAX public int countMenusO
N RETURNS 4’he number of menus on the menu bar.
О DEPRECATION Replace the usage of this deprecated method, as in
P int count = menubar.countMenusO ;
with
Q R int count = menubar.getMenuCountО;
S *T' dcleteShortcuti)
и pi rposl Deletes a keyboard shortcut from menu items in this menu bar.
V syntax public void deleteShortcut(MenuShortcut shortcut)
w descrihion See the class description of Menuitem for details on keyboard shortcuts. This
method deletes the keyboard shortcut shortcut from all menu items in menus
X on this menu bar. Menu items vs ith other keyboard shortcuts are not affected.
Y Nole: In Java 1.1.2, deleteShortcut() deletes all shortcuts from all menus
Z in this menu bar. not just shortcut. This is a bug.
PARAMETERS
shortcut l he keyboard shortcut to delete.
1058
dcIclcShortcuti )
see \i so
getShortcutMenuItemO, Menuitem.deleteShortCut(),
Menuitem.getShortcut(), Menuitem.setShortcut() MenuShortcut
shortcuts().
example
This example creates a menu bar that has a
menu, which has three menu items, each
containing a menu shortcut. See Figure
265. Using the checkboxes and text field at
lhe bottom of the frame, you can find or
delete menu shortcuts.
Note: Due to a bug in Java 1.1.2. checking
Delete deletes all shortcuts, regardless of
what is entered in the text field.
* deleteS hortcu B0E3
New Ctrl+N
Open... Ctrl+O
Exit Ctrl+E
□------------------
C Deleted Find
import java.awt."';
import java.awt.event.*;
import java.uti1.Enumeration;
HGI RE 265: Menu Shortcuts in
a Menu Bar.
class Main extends Frame implements ActionListener, ItemListener {
MenuBar mb = new MenuBarQ;
boolean delsc = false;
Main() {
super(“deleteShortcut Example");
Menu m = new MenuC’Fi le”);
Menuitem mi;
mi = new MenuItemC’New” , new' MenuShortcut (KeyEvent. VK_N));
mi.setActionCommandC'New”); // required for shortcut
m.add(mi);
mi = new MenuItemC’Open...", new MenuShortcut(KeyEvent.VK_O));
mi.setActionCommand(“Open"); // required for shortcut
m. add(mi);
m.add(“-") ;
m.add(mi = new MenuItem(‘Exi t” . new MenuShortcut ('KeyEvent. VK_E;); ;
mi.setActionCommand(“Exit"); // required for shortcut
mb.add(m);
// Add listener for menu (and its menu items;
m.addActionLi stener(thi s);
// Set the menu bar on the frame.
setMenuBarfmb);
// Add controls for viewing and deleting shortcuts
Panel p = new PaneHnew Gri dLayout'T, O;;;
CneckboxGroup eg = new CheckboxGroupO;
Checkbox del = new Checkbox("Delete", false, eg;;
Checkbox find = new Checkboxf“Find", true, eg;;
del.add1temL i stener C th i s;:
find.addItemLi stenertthis;;
java.awt
MenuBar
deletcShortcut()
TextField tf = new TextField(“");
p.add(del);
p.add(fi nd):
p.add(tf);
tf.addActionListener(this);
add(new TextArea(‘‘Text area1'), BorderLayout.CENTER);
add(p, BorderLayout.SOUTH);
setSize(100, 100);
showO;
void printShortcuts(String msg, MenuBar mb) {
System.out.print(msg);
for (Enumeration sc = mb. shortcutsO;
sc. hasMoreElementsO ;
) {
System .out. pri nt (sc. nextEl ementO + “ “);
}
System.out.println(n”);
}
public void actionPerformed(ActionF vent evt) {
if (evt .getSourceO instanceof Menuitem) {
System.out.print 1 n(evt,getActionCommandO) ;
} else if (evt.getSourceO instanceof lextField) {
String sc = evt .getActionCommandO ;
MenuShortcut target = new MenuShortcut(sc.charAt(0));
if (delsc) {
pri ntShortcutsC’Before delete: ”, mb);
mb.deleteShortcut(target);
printShortcuts(“After delete: ”, mb);
} else {
System.out.pri ntln{mb.getShortcutMenu!tem(target)'
}
}
public void itemStateChanged(ItemEvent evt) {
delsc = (evt.getltemO .equals(”Delete”));
}
static public void mai n(Stri ng [] args) {
new Mai n();
}
1060
java.dWl
JV1C11UD
getllelpMeni
getHelpMenu()
purpose Retrieves thi» menu bar’s Help menu.
SYNTAX public Menu getHelpMenuQ
description A menu bar can have a special menu designated the Help menu. The only thing
special about lhe Help menu is that on some platforms, it appears at the right
edge of the menu bar.
returns This menu bar’s Help menu. /X return value of null means a Help menu has
not been set.
see also setHelpMenu О.
example This method removes the Help menu from the menu bar.
void removeHelpMenu(MenuBar menubar) {
Menu hm = menubar .getHelpMenuQ;
if (hm ! — null) {
menubar.remove(hm);
}
}
getMenuO
purpose Retrieves a menu on this menu bar.
syntax public Menu getMenu(int pos)
PARAMETERS
pos The zero-based index of the menu on the menu bar,
returns The non-nul 1 menu al the zero-based index pos.
exceptions
ArraylndexOutOfBoundsException
If pos is beyond the size of this menu.
seealso addMenuO, getHelpMenuQ.
example This method prints lhe labels of all of the menus on a menu bar.
void printMenuLabels(MenuBar menubar) {
for (int i=0; i<menubar.getMenuCount(); i++) {
System.out.println(menubar.getMenu(i).getLabel());
}
}
MenuBar
getMenuCountt )
jaxa.aw t
getMenuCount()
pi rposi- Rctrie\es the number of menus on this menu bar.
s>\t\x public int getMenuCount()
di s( rii’I i<)\ This method retrieves the number of menus on this menu bar. including the
Help menu.
Rl. I l R\S
The number of menus on this menu bar.
i \ win I
1'his example enables or disables all menu items in all of the menus in the
menu bar. See Figures 266 and 267.
I
G
H
I
.1
К
L
I Kil RK 266: Enabled Menu Items.
< getMenuCount ... №E3
JH Edit нв^вн
Enable i Disable
I IGl RE 267: Disabled Menu Items.
A
В
M
N
()
import java.awt.'';
P import java.awt.event;
Q class Main extends Frame implements ActionListener {
R MainfString title) {
s super(title);
MenuBar mb = new MenuBarO;
j- Menu menu = new Menu(“Fi 1 e”) ;
l' menu.add(“New”);
menu.add(“Open...”);
v mb.add(menu);
menu = new Menu(“Edi t”) ;
x menu.add(“Copy”);
menu.add(“Paste”);
у mb.add(menu);
/ setMenuBar(mb);
Button b;
add(b=new Button(“Enable”), BorderLayout.WEST);
1062
java.awt
мепига
getS hortcu t M en u I tem
b.addActionLi stener(thi s);
add(b=new Button(“Disable"), BorderLayout.LAST);
b.addActi onLi stene r(thi s);
setSi ze(100, 100);
show();
}
static public void main(String[] args) {
Main m = new Main(“getMenuCount Example’’);
}
void enableMenuItems(boolean enable) {
for (int i=0; i<getMenuBar() .getMenuCountO ; i++) {
Menu menu = getMenuBar().getMenu(i);
for (int j=0; jcmenu.getltemCountO; j*+) {
Menuitem menuitem = menu.getltem(j);
menuitem.setEnabled(enable);
}
}
}
// Button action listener
public void actionPerformed(ActionEvent evt) {
String what - evt .getActionCommandO;
boolean enable = "Enable".equals(what);
if (enable I I “Disable".equals(what)) {
enableMenuitems(enable);
}
}
}
PURPOSE Retrieves the menu item in this menu bar that has the specified shortcut.
SYNTAX public Menuitem getShortcutMenuTtem(MenuShortcut shortcut)
DESCRIPTION See the class description of Menuitem for a description of keyboard shortcuts. This method finds the tirst menu item in the menus on this menu bar that has the keyboard shortcut shortcut.
PARAMETERS shortcut The non-null shortcut for which to search.
RETURNS Л menu item that has keyboard shortcut shortcut; null if no menu item has that shortcut.
SEE ALSO deleteShortcut(), MenuShortcut, Menuitem.setshortcut(), shortcutsO.
EXAMPLE See de 1eteMenuShortcut().
MenuBar
Menu Bail )
jax a.aw 1
MenuBar()
pi rposi Constructs a new MenuBar instance.
public MenuBarO
A
В
C
I)
I
I
G
H
1
J
К
L
DLSCRIPI l()\
SEE \l so
I \ WIPI.I
This constructor creates a new MenuBar instance, which must be installed in a
frame before it can be used bx the user. A frame is the only xalid parent that a
MenuBar can ha\e. The MenuBar instance can be assigned to onlx one frame.
I- rame . setMenuBar ().
This example creates a frame that has a menu
bar with a single menu File. The File menu is set
to use a large font but its menu items do not
inherit the font usage. See Figure 268.
Save
M
N
()
P
Q
R
S
1
11
V
w
X
Y
Z
i mport j ava . awt . ’;
class Main {
static public void main(St гing[] args) {
Frame f ~ new Frame(“MenuBar Example”);
MenuBar menubar = new MenuBarO;
l l(a RI MenuBar with
Large Font Menu.
f.setMenuBar(menubar);
Menu menu = new Menu(“Fi1e”);
menu.setFont(new Font(“Monospaced”, Font.PLAIN, 32));
menu.add(“Edi t”);
menu.add(“Save”);
menubar.add(menu);
f.setSize(100, 100);
f. showQ ;
}
remove()
purpose Removes a menu from this menu bar.
syntax public synchronized void remove(int pos)
public synchronized void remove(MenuComponent menu)
description This method removes a menu from this menu bar. The menu can be specified
either by its index in the menu (pos) or bx lhe menu component menu itself.
All remaining menus that have indexes greater than the index of the remoxed
menu are decreased bx one. If the menu has a peer, lhe peer is destroyed
1064
rcmovcNotifv
parami н rs
menu The non-null menu to he removed. If menu is not in this menu bar. this method does nothing.
pos The /его-based index of the menu in the menu bar.
SEE ALSO add().
example See add().
removeNotifyf)
PURPOSE Destroys this menu bar's peer.
SYNTAX public void removeNotifyO
DESCRIP 1 ION This method should never be called directly. It is normally called by the com- ponent's container.
OVERRIDES MenuComponent.removeNoti fy ().
see: also MenuComponent.
EX AM Pl J: See Component.setVi si ble().
setHelpMenu()
purpose Replaces this menu bar's Help menu. syntax public synchronized void setHelpMenufMenu menu) (Л [« 42 Г'D t D’T'l f \ К 1 1л i < tXA»» t lx <\r I t lx»_m/Xnii j ,ii
iJi.sv к11 i в >\ 1 ins inniiou seis те ihliiu menu io oe ... ЯРЕ!
this menu bar's Help menu. If a Help menu already exists, the current Help menu is remoxed from the menu bar and Help Topics... menu becomes the new Help menu. Search...
PARAMETERS About..
menu The non-null menu to be set.
ex xmpll This example creates a frame ith a Help . f О HGIRE 269: menu that contains thice menu items. See MenuBar.setHelpMenuO • Figure 269. import java.awt.’":
class Main extends Frame {
^ainCString title; {
super(ti 11ej;
MenuBar mb = new MenuBarl);
MenuBar
shortcutst)
java.awt
Menu menu - new Menu("Help") ;
menu. add(‘‘Hel p Topics../’):
menu.add("Search...’’);
menu.addSeparator();
menu. add ("About...’’);
mb.setHelpMenu(menu);
// Set the menu bar on the frame.
setMenuBar(mb);
setSize(200, 200);
show();
}
static public void mai n(St ri ng[] args) {
Main m = new Vain("setHelpMenu Example’’);
}
}
shortcuts!)
Pl RP( )Sl Lists the keyboard shortcuts associated with menu items in this menu bar
SWT XX public synchronized Enumeration shortcutsO
RL 'I I RXS /X non null enumeration of the keyboard shortcuts associated with all menu items in all menus on this menubar.
SET. ALSO deleteShortcut0 > getShortcutMenuItemO, Menuitem.getShortcut()T Menushortcut.
EXAMPLE' See deleteMenuShortcutO-
1066
java, aw l. pee г
MenuBarPeer
Syntax
public interface MenuBarPeer extends MenuComponentPeer
Description
The menu bar component (see lhe MenuBar class) in the AWT uses the platform's native
implementation of a menu bar. So that the AWT menu bar behaves the same on all platforms,
the menu bar is assigned a peen whose task is io translate the behavior of lhe platform's native
menu bar to the behavior of the AWT menu bar.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting lhe AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
Menu component peers serve the same role as component peers. See Component and
Toolkit for additional information about component peers.
MEMBER SUMMARY
Peer Methods
addHelpMenu()
addMenuO
del Menu()
Replaces the Help menu.
Adds a menu to the menu bar.
Removes a menu from the menu bar.
See Also
java.awt.Component, java,awt.MenuBar, java.awt.MenuComponent,
java.awt.Tool kit.
MenuBarPeer
java.awt.реет
addHelpMenuO
addHelpMenu()
PURPOSE SYNTAX Replaces (he Help menu. void addHelpMenu(Menu menu)
Л PARAMETERS
в menu The non-nul 1 menu to be set.
c SEE ALSO java.awt.MenuBar. setHelpMenu().
D
i: add.\lenu()
F G PURPOSE Adds a menu to the menu bar.
H SYNTAX PARAMEIERS void addMenu(Menu menu)
1 menu The non-nul 1 menu to be added to the menu bar.
J SEE: ALSO java.awt.MenuBar.add().
к
L delMenu()
\1 M
N PLRP( >SE Removes a menu from the menu bar.
О SYMAX PARAMETERS void delMenu(int pos)
P pos The zero-based index of the menu in the menu bar
Q SEI: Al SO java.awt.MenuBar.remove ().
R
S
T
C
V
W
X
Y
Z
1068
java.avvi
MenuComponent
Syntax
public abstract class MenuComponent implements Serializable
Description
Component
FlGl’RE 270: Component and MenuComponent.
The MenuComponent class is similar to lhe Component class in that it is the superclass of all
other AWT components. See Figure 270. Menu-related components do not extend from Com-
ponent because menu components do not have most of the capabilities available to compo-
nents. For example, you can't paint on menu components, control their layout (only their
ordering), make them invisible, or change their colors. Moreover, no other events are fired by
menu components, other than lhe action event fired by a menu item when it is selected.
This class serves as the super-
class of all menu-related components.
There are presently three kinds of
menu components in the AWT pack
age, as shown in Figure 271.
Events
Menu Bar
Menu Items
HGt RK 271: I’he Three Kinds of Menu Components.
Among menu components, only the
menu item fires events. In particular,
a menu item fires only action events.
For convenience, action events not
processed by menu items are forwarded to their parent (a menu). This allows action listeners to
be added to the menu instead of to individual menu items. Menu bars do not lire any events.
MenuComponent
java.awt
A
В
C
D
E
F
G
11
I
J
К
L
M
N
Menu components participate in the AWT event flow in a similar way that Component
objects do. The main difference between the two is that menu components can pass up their
events to their menu component parents, while components do not pass up their events.1 As
described previously, selecting a menu item fires an action event, which may be passed up to
its parent (a menu) if the parent is a menu component with action events enabled.
For a complete discussion on events, event handlers, and event flow; see the AWTEvent
class.
The Name
bach instance of a menu component has a name associated with it. This is a string that is b\
default initialized to a unique identifier by its AWT class constructor. For example, the
MenuBar class assigns a name of the form “menubar" concatenated w ith the value of a counter
that it increments for each instance of MenuBar created (e.g,. "menubarO"). The program can
overwrite this default, by using setNameO. to set it to a program-specific string.
A menu component’s name is a placeholder for the program to record a locale-indepen-
dent identifier for the component. Instead of using a possibly localized string, such as menu
item’s label, you would use the menu component’s name for comparison when checking fora
menu component’s identity (see the getNameO method, for example). Subclasses of Menu-
Item can also use the item's action command for similar purposes when dealing with the
item's action events (sec Menuitem).
In addition to obvious debugging uses, the menu component's name can be used, for
example, by a GUI builder to allow the user to assign an identifier to each menu component
instance ihe user creates.
О
P
Q
R 1 MEMBER SUMMARY
S Font Methods
T getFontO Retrieves this menu component’s font.
I setFontO Name Methods Sets this menu component’s font.
V getNameO Retriescs this menu component’s name.
w setNameO Sets this menu component's name.
X Parent Method
Y getParentQ Retrieves this menu component's parent.
z
I Components that use (he deprecated event model (Event j still pass up their events 10 their parents
1070
I cl V d. tl w I
1 v aval м i^viiifsvii
IfEMBER SUMMARY
Event Methods
di spatchEventO
processEventO
Dispatches an event to this menu component.
Processes an event enabled for this menu component.
Peer Method
removeNotifyO
Destroys this menu component's peer hierarchy.
Debugging Methods
paramStringO
toStringO
Generates a string representation of this menu component's state.
Generates a string representation of this menu component's state.
Deprecated Methods
getPeerО
postEventO
Should not manipulate peers directly.
Replaced by dispatchEventO.
See Also
AWTEvent, java.io.Serializable, Menu, Menuitem.
Example
This example creates a frame that has the three kinds of menu components. See f igure 271.
import java.awt.*;
class Main extends frame {
MainO {
superC'Menu Components'’);
MenuBar mb new MenuBarO;
Menu m = new Menu(HFi1e”);
// Add items to file menu
m.addCNew”) ;
m.add(“Open...”);
// Add File and Edit menus to menubar
mb.add(m);
mb.add(new MenufEdi t")) ;
// Set the menu bar on the frame.
setMenuBar(mb);
setSize(200, 100);
show();
static public void main(String[1 args) {
new MainO;
java.awt
MenuComponent
dispatchEventt)
dispatchEvent()
A
В
C
D
E
F
Ci
H
I
.1
К
L
pprposi. Dispatches an event to this menu component.
syntax public final void dispatchEvent(AWTEvent evt)
description This method dispatches the event evt to this menu component or its parent If
evt is one of’the event types that have been enabled for this menu component,
it is processed using processEventO. If evt’s event tv pc is not enabled for
this menu component and evt is an action event, it is passed on to this menu
component’s parent if its parent has events enabled. For example, a menu item
would pass up its action event to its parent (a menu).
PARAMETERS
evt
SI I Al SO
EXAMPLE
The non-null AWTEvent.
AWTEvent. processEventO.
M
N
()
P
Q
R
Г
U
V'
w
X
Y
Z
This example
creates a menu
that has menu
items that fire a
user-defined
type of event --
SetFontEvent.
When the menu
item receives an
action event to
< dispatch... вив
Size МЦ
FIGI RE 272: Supporting User-defined Event Types in
Menu C omponent.
change to font size, it fires a corresponding SetFontEvent to each of the
menu items in the menu by calling di spatchEvent О on the menu items. See
Figure 272.
The MainMenuItem class subclasses Menultem and overrides processEv-
entO l<> handle the new type of event. Note that SetFontEvent is a subclass
of ActionEvent and uses ActionEvent. ACTION-PERFORMED in order to
allow the user-defined event type to be dispatched.
import java.awtc;
import java. awt. event. ;
class Main extends Frame implements ActionListener {
Menu menu = new Menu(‘‘Font Size’’);
Main() {
super("d i spatchEvent Exampie”);
setLayout(new FlowLayout());
Menuitem b;
menu.add(b = new MainMenuItem("Smal 1 Font’’));
b.addActionLi stener(this);
1072
J<1 Vd.dW I
dispatchlivenU
menu.add(b = new MainMenuItem(“LargeFont”));
b.addActionLi stener(thi s);
MenuBar mb - new MenuBarO;
mb.add(menu);
setMenuBar(mb):
setSize(200, 200);
showO;
}
public void actionPerformed(ActionFvent evt) {
String arg = evt.getActionCommandO ;
Font f = nul1;
if (“SmallFont”.equals(arg)) {
f = new Font(“Serif”, Font.PLAIN, 12);
} else if (“LargeFont'’. equal s(arg)) {
f ~ new Font(“Serif", Font.PLAIN, 30);
}
if (f ’= null) {
SetFontEvent fevt = new SetFontEvent(this, f) ;
for (int i=0; i<menu.getltemCountO; i++) {
MainMenuItem c = (MainMenuItem)menu.getltem(i):
c.di spatchFvent(fevt);
}
}
}
public static void main(StringL] args) {
new Mai n();
}
}
// Define new event for setting font of menu item
// Must be subclass of ActionEvent to get past dispatchEvent*s filter
class SetFontEvent extends ActionEvent {
Font font;
public SetFontEvent(Object source, Font f) {
// Must use ACTION PERFORMED to get event pass
// dispatchEvent’s filter
super(source, ActionEvent.ACTION PERFORMED, null);
font = f;
}
public Font getFontO {
return font;
}
}
class MainMenuItem extends Menuitem {
MainMenuItem(String label) {
super(label);
}
// Override to handle special new event (SetFontEvent)
protected void processEvent(AWTEvent evt) {
if (evt instanceof SetFontFvent) {
// Change font as requested
processSetFontEvent((SetFontEvent) evt);
MenuComponent
izetFonU )
|a\ a.aw i
} else {
super.processEvent(evt);
}
A
В
('
protected void processSetFontEvent(SetFontEvent evt) {
// perform font change on this menu item
setFont (evt. getFontO) ;
}
}
i: getFont()
i 14 RPOSL Retriexes this menu component's font.
G SX \ I \\ public Font getFontO
11 i RI П R\S This menu component's font. The return xalue max be null, which means that neither lhe menu component nor any of its ancestors have been assigned a font.
j SI 1 \l SO Font, setFontQ-
к 1 \ WIPI 1 Sec set Font О.
M
N () Pl RPOSI Retriexes this menu component s name.
p SX \ I \\ public String getNameO
<2 1)1 -.SCRIP IIOX A menu component's name is a placeholder for the program to record a locale- independent identifier for the component. Sec lhe class description for details.
R RI. 11 R\S This menu component's name.
S SI.I XI.SO setNameO.
T 1 \ WIPI 1. This example creates a menu of menu items with localized labels and locale-neutral names. See Figure 273. Because these are menu items, a similar effect could have been achieved
• get Name ... ДИЕЗ II
11 V un
vv using lhe menu items' action commands. See Menu Item. setActi onCommandO.
X trois 1
X i mport i mport import i mport j ava. awt. ••; j ava.awt.event.*; java.util ResourceBundle; java.util.Locale; 1 IGl RI 273: Localized Menu.
public class Main extends Frame {
1074
java.awt
IVirilUV^VIll puuc
get N am»
MainO {
super(“getName Example”);
}
void init(ActionListener 1) {
// Get localized labels for menu items
ResourceBundle rb = ResourceBundle.getBundle(“MyBundle”, getLocaleO);
String one = rb.getString(“menuitemOne”);
String two - rb.getString(“menuitemTwo”);
String three = rb.getString(“menuitemThree”);
String heading = rb.getStringC'menuHeadi ng”) ;
// Create checkboxes
Menu menu - new Menu(heading);
Menuitem ml - new MenuTtem(one);
Menuitem m2 = new Menultem(two);
Menuitem m3 = new MenuTtem(three);
// Set internationalized identifiers for menu and menuitems
menu.setName(“number”);
ml.setName(“one”);
m2.setName(“two“);
m3.setName(“three”);
// Add listener for menu and menu items
menu.addActionLi stener(1);
ml.addActionli stener(1);
m2.addActionListener(l);
m3.addActionListenerQ) ;
// Add menu items to menu
menu.add(ml);
menu.add(m2);
menu.add(m3);
MenuBar mb - new MenuBarO;
mb.add(menu);
setMenuBar(mb);
setSize(100, 100);
show();
}
static public void main(String[] args) {
Main m = new Main();
// Set locale of component
m.setLocale(Locale.FRANCE);
m.init(new ActionFventHandlerQ);
}
}
class ActionEventHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
MenuComponent src - (MenuComponent)evt.getSourceO;
String target - src .getNameO ;
int number - 0;
if (target .equal s(“one'*)) {
number - 1;
MenuComponent java.awt
getPiirentt) } if (target, equal sC'two”)) { number - 2; } if (target.equals(“three”)) { number = 3; } String label -= (src.getParentQ instanceof MenuComponent ? ((MenuComponent)(src.getParent())).getName() : *'?”):
} } System .out . pri ntln(label “ + number);
getParent()
PURPOSE Retrieves this menu component's parent.
SYNTAX public MenuContainer getParentO
RETl’RNS This menu component's parent. The return value mas be null, which means that the menu component does not yet have a parent.
EXAMPLE See get Name О.
getPeer() deprecated
PCRPOSI: Should not be manipulating peers directly.
SYNTAX public MenuComponentPeer getPeerO
RETl’RNS The menu component's peer. The return value ma> be null, which means that the menu component does not >et have a peer.
paramStringt)
Pl • RPOSE: Generates a string representation of this menu component ’s state.
SYNTAX protected String paramStringO
DESCRIPTION A menu component's state consists of its name. Л subclass of this class should override this method and return a concatenation of its state with the results of super.paramString(). This method is called b} the toStringO method and is typically used for debugging.
RETURNS A non-nul 1 string representing the menu component's state.
SEE Al SO toStringO.
EXAMPLE Component.paramSt r i ng().
1076
postEvent
pOStEventf) DEPRECATED
PURPOSE Replaced by dispatchEventO.
SYNTAX public boolean postFvent(Event evt)
PARAMETERS evt The non-nul 1 event to be posted.
RETURNS true if the event was handled by some component; fal se otherwise.
deprecation Replace the usage of this deprecated method, as in postEvent(evt); with dispatchEvent(awtEvt);
SEE ALSO AWTEvent.
processEvent()
PURPOSE Processes an event enabled for this menu component.
SYNTAX protected void processEvent(AWFEvent evt)
DESCRIPTION This method is called (typically by dispatchEventO) to deliver the event evt to this menu component. This method is invoked only if evt is an event type that has been enabled for this component. An event type is enabled auto- matically when a listener of that type is added to this menu component. The default implementation of this method does nothing. /X subclass of Menu- Component overrides this method to add support for event types that it wants to handle.
PARAMETERS evt The non-nul 1 event.
SEE ALSO di spatchEventO.
EXAMPLE See di spatchEventO.
removeNotify()
PURPOSE Destroys this menu component's peer hierarchy.
SYNTAX public void removeNotifyO
DESCRIPTION This method destroys this menu component’s peer hierarchy, if it exists. This method should never be called directly. It is normally called by the menu com- ponent's container.
MenuComponent
setFontt )
ja\ a.awt
see \i so Component.
example See Component. setVi si bl e().
A setFont()
В pirpose Sets this menu comnonent’s font.
C ' Example ДИЕЗII
D syntax public void setFont(Font font) ИМИИ1ИЯИ1
E PARAMETERS M . font The font to be set. The value mav be Honospaced
,, .. Serif
nul 1. in which case the default font is to
Г . , SansSerif be used.
G
see ai so Font, getFontO.
H ьхлмин This example creates a menu that has H(.(R|,;274: cha„uinR a Mvllu
I menu items. It allows you to change the Component's Font.
J font of the items on the menu. See Fig-
ure 274.
К
1 import java.awt.'';
1 z import java.awt.event. *;
class Main extends Frame implements ActionListener {
N Menu menu = new Menu(“Change Font”);
Main() {
super(“setFont Example”);
menu.add(new MenuItem(“Monospaced”));
menu.add(new Menultem(“Seri f ”));
menu.add(new Menuitem(“SansSeri f”));
menu.addActionListener(this);
MenuBar mb = new MenuBarO;
mb.add(menu);
setMenuBar(mb);
setSize(200, 200);
show();
public void actionPerformed(ActionEvent evt) {
System.out.println(evt);
String arg = evt.getActionCommand();
Font f = nul1 ;
f = new Font(arg, Font.PLAIN, 12);
if (f i= null) {
for (int i = 0; i cmenu.getltemCountO; i++) {
Menuitem src = menu.getltemO);
1078
setName(
System. out. pri ntl n("Changi ng font from: “ * src.getFontQ) ; src.setFont(f); }
}
}
public static void main(Stringn args) {
new MainO;
}
}
setNamef)
— —
PURPOSE Sets this menu component’s name.
SYNTAX public void setName(String name)
DESCRIPTION This method sets the name of this component to name. See the class descrip- tion for details.
PARAMETERS name This menu component’s new name.
SEE ALSO getNameO.
EXAMPLE See getNameO.
toString()
- -
PURPOSE Generates the string representation of this menu component’s state.
SYNTAX public String toStringO
DESCRI PHON The result string contains the menu component's class name and the results of calling paramStringO. This method is typically used for debugging.
RETl’RNS A non-nul 1 string representing the menu component's state.
OVERRIDES java.lang.Object.toStri ng().
SEE ALSO paramStri ngO,
EXAMPI 1- See java.1ang.Obj ect.toStri ng О.
1Л'
java.awt.peer
MenuComponentPeer
A
В
C
D
E
Г
G
H
I
J
К
L
VI
N
О
P
Q
R
S
I
L'
V
W
X
Y
Z
Syntax
public interface MenuComponentPeer
Description
The menu component (see the MenuComponent class) in the AWT uses the platform's native
implementation of a menu component. So that the AWT menu component behaves (he same
on all platforms, the menu component is assigned a peer. whose task is to translate the behav-
ior of the platform's native menu component to the behavior of the AWT menu component.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java. awt counterparts.
Menu component peers serve the same role as component peers. See Component and
Tool ki t for additional information about component peers.
MEMBER SUMMARY~
Peer Method
di spose() Destroys the peer.
1080
java.awLpeer
Menuuomponentree
dispose!
See Also
j ava.awt.Component, j ava.awt-MenuComponent, j ava.awt.Tool kit.
dispose()
PURPOSE Destroys the peer.
SYNTAX void disposeO
SEE ALSO java.awt.MenuComponent.removeNotifyO.
java.awt
MenuContainer
’ \ 7 ~ ~ J
A i : Г
B .....~ . i
C ^ ; J ’ ......... j
D
e Syntax
public interface MenuContainer
G Description
H This interface is implemented by classes that contain menu components. l he AWT package
I has several menu component containers: Menu, MenuBar, Frame (a frame can have a menu
bar), and Component (and its subclasses). A component can have popup menus and therefore
J is a menu container.
К
L • MEMBER SUMMARY
N 0 P Q Menu Container Methods getFontO Retrieves this menu container's font. removeO Removes a menu component from this menu container. Deprecated Method postEvent О Replaced by MenuComponent. di spatchEventO.
R
S ri Al
T MenuContainer Ex
и Component, Menu, MenuBar, Frame. File
Mew
V Example Open,,, J
w This example implements a new type of menu con- _ Edit
V tainer. Menu Frame, which accepts menus and displays Cut . J
A them all in one frame. See Figure 275. Each menu PaeW ' 1
Y label and menu item label is displayed one per line. .1
Z When the user clicks a menu item, an action event is
fired for that menu item. FKJl RE 275: MenuFrame.
1082
Note: In Java LL2. a subclass outside the java.awt package cannot enable its self-
defined action events. Therefore, the program calls processEventO instead of dispatch-
EventO to dispatch the event.
import java.awt.";
import java.awt.event.*;
import java, uti 1.5r;
public class Main implements ActionListener {
Main () {
MenuFrame mf = new MenuFrareO ;
// Now create a few menus.
Menu menul = new MenuC'Fi le”);
menul.addC'New”);
menul.addC'Open...”);
mf,add(menu1);
Menu menu2 = new Menu(“Edit”);
menu2.add(“Cut”) ;
menu2.addC'Paste”);
mf,add(menu2);
// Add self as listener
mf.addActioni istener(this) ;
// Display menu
mf.setVi si ble(true);
}
// Action Listener for Menu frame
public void actionPerformed(ActionEvent evt) {
System.out.println(“action performed “ + evt);
}
static public void main(String[J args) {
new Mai n();
}
}
class MenuFrame extends Frame implements MenuContainer {
Font font = new Font(“Monospaced”, font.PLATN, 14);
FontMetrics fontM;
transient ActionListener actionListener;
// Contains all the menu in this container.
Vector menus = new VectorO;
// Contains all the menu iteirs in this container.
Vector menuitems = nul 1;
MenuFrameO {
super(“MenuContainer Example”);
this.menus = menus;
fontM getFontMetrics(font);
setResizable(false);
// Add listener for handling mouse clicks
MenuContainer
java.awt
addMouseListener(new MouseEventHandler());
// Enable mask for action events
enableEvents(ActionEvent.ACTION-EVENTJ4ASK);
}
// Override show() to get MenuFrame size first
public void setVisi ble(boolean show) {
if (!show) {
super.setVi sible(false);
}
// Create the peers so that getlnsetsO returns correct value
addNotifyO;
Dimension dim = getPreferredSizeO;
Insets insets = getlnsetsO;
setSize(insets.left+dim.width, insets.top+dim.height);
super.showO ; // calls Frame. showO
}
// Override to calculate size of frame based on menu items
public Dimension getPreferredSize() {
Vector labels = getLabelsO;
int width = 0;
for (int i=0; idabels.size() ; i++) {
width = Math.max(width,
fontM.stri ngwidth((String)1abels.elementAtC
}
return new Dimension(width, labels.size() * fontM.getHeight());
public Font getFontO {
return font;
}
// Generates a vector of labels. The menu item labels are indented.
Vector getLabelsO {
Vector result - new VectorO;
menuitems - new VectorO;
for (int i=0; icmenus. sizeO; i++) {
Menu menu = (Menu)menus.elementAt(i);
result.addElement(menu.getLabel());
menuitems.addElement(nul1);
for (int j=0; jcmenu.getltemCountO; j++) {
resul t. addEl ement (“ "+menu.getltem(j).getLabel());
menuitems.addElement(menu.getltem(j));
}
1
return result;
// Paints the labels.
public void paint(Graphics g) {
Vector labels = getLabelsO;
int у = fontM.getAscentO;
g.setFont(font);
1084
java.awt
ivienuvoni
Insets insets = getlnsetsO;
for (int i-0; i<labels.size(); i++) {
String label * (String)labels.elementAt(i);
// Paint menu label blue
if (label.charAt(0) !=. ‘ J) {
g.setCol or(Col or.bl ue):
}
g.drawString(label, insets.left, insets.top+y);
у += fontM.getHeight();
g.setColor(Col or.black);
}
}
public void add(MenuComponent mcomp) {
menus.addElement(mcomp);
menuitems = null; // invalidate old list
1
public void remove(MenuComponent mcomp) {
menus.removeElement(mcomp);
menuitems ~ null; // invalidate old list
}
// ActionEvent methods
public void addActionListener(ActionListener 1) {
actionListener = AWFEventMu1ticaster.add(actionListenert 1);
}
protected void processEvent(AWTEvent evt) {
if (evt instanceof ActionEvent) {
processActionEventC(ActionEvent) evt);
} else {
super.processEvent(evt);
}
}
protected void processActionEvent(ActionEvent evt) {
if (actionListener !- null) {
actionLi stener.actionPerformed(evt);
}
}
// Mouse Event Listener
class MouseEventHandler extends MouseAdapter {
// Determines which item was clicked on and fire an event for that item,
public void mousePressed(MouseEvent evt) {
Vector labels = getLabels();
Insets insets - getlnsetsO;
int item = (evt.getY()-insets.top) / fontM.getHeightO;
// Don’t generate events when the click it not on a label,
if (item < labels.size()) {
String label - ((String)labels.elementAt(item));
//Don’t generate event for menu labels.
if (label.charAt(0) == ‘ ‘) {
ActionEvent action =
new ActionEvent(menuItems.elementAt(item),
ActionEvent.ACTIONPERFORMED,
MenuContainer
getHonU )
java.awt
1 abel. trimQ) ;
System.out.println(‘‘cHspatched: “ 4 action):
// dispatchEvent(action);
processEvent(action);
}
\ }
}
В }
c
D
E r- getl'ontf)
PVRPOSE Retrieves this menu container’s font.
G SVN1AX Font getFontO
H | RE ITRNS The menu container’s font. A result value of null means neither (he menu container nor any of its ancestors have been assigned a font.
J EXAM PI F See the class example.
к
L
M
N
()
P
Q
R
s
I
L
V
pOStEveilt() DEPRECATED
pvrpose Replaced by MenuComponent .dispatchEventO.
syntax public boolean postEvent(Event evt)
di scription This method posts the event evt to this menu container.
PARAMETERS
evt The non-nul 1 event to post.
Rt-.n rns true if the event was handled by some menu component or Component
object; false otherwise.
deprecation Replace the usage of this deprecated method, as in
postEvent(evt);
w ith
di spatchEvent(awtEvt);
see ai so AWIEvent.
W
1086
removef
removef)
PURPOSE Removes a menu component from this menu container.
SYNTAX parameters mcomp void remove(MenuComponent mcomp) The non-null menu component to remove from this menu container.
exampit. See the class example.
java.awt
Menuitem
В '—| МнппТГ.еп-i J
c • .. ......J
» -ZZ..................... J
1 — ~............ I
F
G Syntax
u public class Menuitem extends MenuComponent
I
J
К
L
N
()
P
Q
R
M
Description
A menu item is a menu component that
must exist in a menu. A menu item is
typically used to invoke commands in
the applications. Menu items are simi-
lar to buttons in function and use.
except that they take up less screen
space, l he trade-off is that they are not
as convenient to activate as buttons.
Figure 276 shows the three menu
components in the AWT package. The
displayed File menu contains two
menu items: New and Open... .
Menu
FIGl'RE 276: l he Three Kinds of Menu C omponents.
The Enabled Property
1 A menu item can be either enabled or disabled. When
Li enabled, it can be selected by the user, and when selected, it
will fire an action event. A disabled menu item cannot be
v
selected and so cannot tire events. Enabled menu items look
W different from disabled menu items so that both can be \ isti-
x ally distinguished.
Figure 277 shows a menu that has two enabled menu
Y items (Open... and Exit) and one disabled menu item (New).
FIGURE 277: Menuitem.
1088
The Label Property and the Separator
The label of a menu item can be any string. There is one particular label, which is treated
specially* This label causes the menu item to become a separator. Separators are used to visu-
ally separate groups of menu items. This is useful if the menu has many menu items.
Separators are always disabled and never fire events. Figure 277 shows a menu with a sep-
arator between the Open... and Fxit menu items.
Keyboard Shortcut
The user can select an enabled menu item either by using mouse actions or by pressing the
menu item's keyboard shortcut. A keyboard shortcut is a sequence of key strokes that can be
associated with a menu item. The keyboard shortcut can be installed, deleted, and changed at
anytime. A menu item that has a keyboard shortcut typically displays its shortcut beside the
menu item's label. How the shortcut is displayed is platform-dependent.
Note: In Java 1.1.2, you must use set Act ionCommandO on a menu item in order for its
shortcut to work. Otherwise, the action event it fires as a result of a shortcut contains a null
action command.
Events
An action event is fired when an enabled menu item is selected. See the ActionEvent class
for details. The action event contains an action command indicating the command issued by
this menu item. By default, the action command is the label of the menu item, unless it is set
using setActionCommandO-
If the action event type is not enabled for the menu item itself, the action event fired by
selecting a menu item is passed up to its container (a menu) The event source of such an event
is the menu item's container, not the menu item itself. For example, suppose the menu item A
is in the menu X and A does not have action events enabled. Selecting A causes an action event
to be passed up to X if X has action events enabled. The event source of the resulting action
event will be X, not A. If the menu item's parent is not a menu component or does not have
action events enabled, the action event is not passed up. Notice that this algorithm passes
action events up only one level. /X cascading menu therefore cannot depend on its parent menu
to handle the action events of its menu items. It must take care of adding action listeners for its
own menu items. See Menu for details.
Note that a menu bar does not fire any events and therefore does not have any events
enabled. Action events from a menu bar s menus are not passed up to the menu bar.
1
Menuitem
jav a.awl
MEMBER SUMMARY
A
В
C
D
E
F
G
H
1
J
К
L
Constructor
, MenuItemO
Enable Methods
i stnabled()
setbnabledO
Label Methods
getLabelQ
1 setLabel()
Constructs a new Menuitem instance.
Determines it this menu item is enabled.
Enables and disables this component.
Retrieves this menu item's label.
Sets this menu item's label.
M
N
О
P
Q
R
S
T
L
V
W
X
Y
Z
Keyboard Shortcut Methods deleteShortcutQ getShortcut() setShortcutO Deletes this menu item's keyboard shortcut. Retrieves this menu item's keyboard shortcut. Sets this menu item's keyboard shortcut.
Event Methods addActionLi stenerO enabl eEventsO di sableEventsQ ’ getActionCommandQ • processActionEventQ processEvent 0 removeActionLi stenerO set Act i onCommandO Adds a listener to receive action events from this menu item. Enables event types for this menu item. Disables event ty pes for this men item. Retrieves the command name of action events fired by this menu item. Processes an action event enabled for this menu item. Processes an event enabled for this menu item. Removes a listener from receiving action events from this menu item. Sets the command name of action events fired by this menu item.
Peer Method addNot i fyO Creates this menu item's peer.
Debugging Method paramStri nq() Generates a string representing this menu item's state.
Deprecated Methods disableO enableO Replaced by setEnabled(). Replaced by setEnabled().
See Also
java.awt.event.ActionEvent, java.awt.event.ActionListener, MenuComponent.
1090
add Л ct ion Listen
Example
This example creates a menu that has two menu items—one enabled and one disabled. The
menu is installed in a menu bar, which in turn is installed in a frame. This example also shows
you how to handle action events fired by menu items. See Figure 277.
import java.awt.*;
import java.awt.event,*;
class Main extends Frame implements ActionListener {
Main О {
superC'MenuItem Example1’);
MenuBar mb = new MenuBarO;
Menu m new MenuC'Fi 1 e");
Menuitem mi;
mi = new MenuTtem(“New”);
mi,setEnabled(false);
m.add(mi);
m.add(“Open.. ;
m. addC*-”);
m.add(“Exi t”);
mb.add(m);
m.addActionListener(thi s);
// Set the menu bar on the frame.
setMenuBar(mb);
setSize(100, 100);
showO ;
}
// Action handler for menu
public void actionPerformed(ActionEvent evt) {
String what = evt.getActionCommandO;
if (“New”.equals(what)) {
// do new
System.out.pri nt In(“doing new”);
} else if (“Open...’’.equals(what)) {
// do open
System.out.println(“doing open”);
}
}
static public void main(String[] args) {
new MainО;
}
}
addActionListenerf)
PURPOSE Adds a listener to receive action events fired by this menu item.
Syntax public synchronized void addActionListener(ActionListener
listener)
Menuitem
addNotify()
jin a.aw t
/X DESCRIPTION PARAMETERS An action event is fired uhen this menu item is selected. See ActionEvent and the class description for more details. After this method is called, the action listener listener will receive action events fired by this menu item. If listener is null, this method does nothing.
в 11stener The possibly null action listener to add.
c SEE Al.SO java.awt.event.ActionEvent, java.awt.event.ActionListener. removeAct ionLi stenerO.
D E EXAMPLE See the class example.
F G addNotifyO
К PL RPOSE Creates this menu item’s peer.
I SYNTAX public void addNotifyO
J К 1. DESCRIPTION This method creates this menu items peer if it does not exist, l he peer is cre- ated by calling the Toolkit.createMenuItemO method. This method should ne\er be called directly. It is normally called by the menu component's parent.
SEE ALSO MenuComponent.removeNoti fy().
N 0 P EXAMPLE The usage of addNotifyO is similar to that of Component.addNotifyO. See the class example of MenuContainer for a usage of Component. addNo- tifyO.
Q
p deleteShortcut()
S Pl ’RPOSE Deletes this menu item's keyboard shortcut.
T SYNTAX public void deleteShortcutQ
U DESCRIPTION The user can select an enabled menu item either by using mouse actions or by
V pressing the menu item's keyboard shortcut. See the class description for
w SEE Al.SO details on keyboard shortcuts. getShortcutQ , setShortcut().
X Y EXAMPLE See setShortcut().
1092
disable
disable()
ih:i’ri:chi:i)
Pl RPOSI Replaced by setEnabled().
SYNTAX public void synchronized disableO
deprecation Replace the usage of this deprecated method, as in menui tem.di sablef); vv i th menui tem.setEnabled(false);
disableEvents()
pi rposi; Disables event types for this menu item.
syntax protected final void disableEvents(long eventTypes)
description An event type is enabled when a listener for that type is added to this menu
item or when enableEvents() is invoked on this menu item with the event
type's mask. This method disables the event types specified by the mask
eventTypes. It is used by subclasses ol Menuitem to undo the effects of
enableEvents(). If a menu item has listeners corresponding to the event
type, events will always be delivered to its processEventO method, inde-
pendent of the effects of enabl eEvents() or di sabl eEvents 0.
PARAMETERS
eventTypes The event mask specifying the event types to disable. Event mask values are
defined in AWTEvent.
SEE also AWTEvent, enableEvents(), processEvent
example This example defines a subclass of Menu-
Item—OnOffMenuItem—that allows action
events fired from it to be switched on and off.
The subclass does not support multiple listen-
ers. When the checkbox is selected, the New
menu item fires action events as normal.
When the checkbox is deselected, the New
menu item does not tire any action events.
See Figure 27S.
import java.awt. ’;
import java.awt.event. ';
import java.util.TooYanyListenersException;
Menuitem ...
New
p7 Enable action event
EIGl RE 278: Disable and
Enable events in a Menuitem.
class Main extends Frame implements Acti onL'’stener, ItemListener {
OnOffMenuItem mi;
Menuitem
java.awt
disableEveniM 1
Main() {
super(“4enultem Example");
MenuBar mb = new MenuBarO;
Menu m = new Menu(“File");
mi - new OnOffMenuitem(“New");
m.add(mi);
try {
mi.addMyActionLi stenerCthi s);
} catch (TooManyListenersException e) {
e.printStackTraceQ ;
System.exi t(1);
}
mb.add(m);
// Set the menu bar on the frame.
setMenuBar(mb);
Checkbox cb = new Checkbox(“Enable action event",
cb.addltemLi stenerCthi s);
add(cb, BorderLayout.SOUTH);
setSize(100, 100);
showO ;
}
// Action handler for menu item
public void actionPerformedCActionEvent evt) {
System.out .println(evt.getActionCommandQ) ;
}
// Item handler for checkbox
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChangeQ == ItemEvent.SELECTED) {
mi.on();
} el se {
mi.offО;
}
}
static public void mainCString[] args) {
new MainQ ;
}
}
class OnOffMenuItem extends Menuitem {
ActionListener myListener;
OnOffMenuItem(String label) {
superClabel);
}
void onQ {
enableEvents(AWTFvent.ACTION EVENT-MASK);
addActionLi stenerCmyl i stener);
}
void offQ {
1094
java.awt
Menu iter
enable!
di sableEvents(AWTEvent.ACTION_EVFNT_MASK);
removeActionLi stелег(туListener);
}
public synchronized void addMyActionListener(ActionListener 1)
throws TooManyListenersFxception {
if (myListener 1= null) {
throw new TooManyListenersExceptionC’OnOffMenuItem”);
}
myListener = 1;
addActionl istener(t);
}
}
enable() DEPRECATED
PURPOSE- Replaced by setEnabledO.
SYNTAX public synchronized void enable О public void enable(boolean on)
PARAMETERS
on If true, the menu item is enabled; otherwise, the menu item is disabled.
DEPRECATION Replace the usage of this deprecated method, as in menui tem. enableO ; menuitem.enable(fal se); with menui tem.setEnabled(true); menuitem.setEnabled(false);
enable E ven ts()
purpose: Enables event types for this menu item.
SYNTAX protected final void enableLventsflong eventTypes)
DESCRIPTION An event type is enabled when a listener for that type is added to this menu item. This method is used by subclasses of Menuitem io always deliver events of the specified type to its processEventO method, regardless of whether it has any listeners. This method enables the event types specified by the mask eventTypes.
PARAMETERS eventTypes The event mask specifying the event types to enable. Event mask values are defined in AWTEvent. Note: In Java 1,1.2, only ActionEvent can be enabled. Enabling other event types has no effect.
Menuitem
java.awt
get Act ionComman d()
SEE A1SO EXAM Pl F AWT Event. di sableFvents О , processEventO. See di sabl eEvents О.
A getActionCommandO
В PURPOSE Retrieves the command name of action events fired by this menu item.
C
SYNTAX public String getActionCommandO
D DESCRIPTION An action event is fired when this menu item is selected. Thai action event
V. contains an action command indicating the command issued by this menu
1 item. By default, (he action command is the label of the menu item. The com-
Cl mand action can be modified using setActionCommandO.
11 RETURNS The possibly null command name of action events fired by this menu item. If
1 SEE Al SO no command name was set. the menu item's label is returned. getLabel О , setActionCommandO.
J EX AM Pl I Sec setActionCommandO.
к L ge t Label ()
N PURPOSE Retrieves this menu item's label.
О S\N'IAX public String gettabel()
P RETURNS This menu item's label. I'he return value may be null.
Q EXAMPLE This example prints all of the menu item labels in a menu:
R void printLabels(Menu m) {
S for (int i-0; i<m.getltemCountO ; i++) {
7 System.out.print 1n(m.getltem(i).get L abel0);
T U f }
V getShortcutf)
w
PURPC )SE Retrieves this menu item's keyboard shortcut.
X S'l M A A public MenuShortcut getShortcutO
Y DESCRIPTION This menu item's keyboard shortcut is set by its constructor and can be
Z changed al anytime using setShortcutO and deleteShortcut().
RETURNS This menu item's keyboard shortcut. The return value may be null, which
1096
isEnabled()
means this menu item has no keyboard shortcut.
SEEALSO deleteShortcut(), MenuShortcut, setShortcutO.
example See setShortcutO.
isEnabledf)
purpose Determines the menu item's enabled state.
syntax public boolean isEnabledO
returns true if the menu item is enabled; fal se otherwise.
seealso setEnabled().
example This example prints all enabled states of all of the menu items in a menu:
void printLabels(Menu r) {
for (int i=0; i<m.getltemCountO ; i++) {
System.out.println(m.getlterfi).getLabel() + "
+ frn.getltem(i).isEnabled() ? "enabled" : "disabled"));
}
}
Menultemf)
PURPOSE Creates a new Menuitem instance.
SYNTAX public MenuItemQ public MenuTtemfString label) public MenuItemfString label, MenuShortCut shortcut)
DESCRIPTIOX This constructor creates a new Menuitem instance that has the label label. If no label is specified, an empty label (’*") is used. If label is the menu item becomes a separator. You can associate a keyboard shortcut with this menu item by supplying shortcut. If no shortcut is supplied, the menu item has no keyboard shortcut. The menu item is enabled by default.
PARAMEIERS label shortcut The non-null string specifying the menu item’s label. This menu item’s keyboard shortcut. Note: In Java 1.1.2. you must invoke setActi onCommandQ in order for shortcut to fire the correct ActionEvent.
SEP AESO getShortcutO -
EXAMPEE See the class example.
java.awt
Menuitem
paramStringf)
paramStringf)
Pl’RPOSE Generates a string representation of the menu item's state.
S\ N't ЛХ public String paramString()
A DESCRIPT ION The string includes the menu item's label and enabled state. This method is
В called by the toStringO method and is typically used for debugging.
C RE ItRNS A non-null string representing the menu item's state.
D OVERRIDES MenuComponent. paramStringO.
E SEE ALSO MenuComponent .toStri ngO , java, lang .Object. toStri ngO.
F EXAM Pl.E See Component.paramStri ng О
11 process ActionE vent()
i J Pt RPOSE SYNTAX Processes an action event enabled for this menu item. protected void processActionl-ventfActionEvent evt)
К L N 0 P Q R DLSCRIPHON An action event is fired when this menu item is selected. See ActionEvent and the class description for more details. This method processes action events for this menu item by calling any registered ActionL i stener. This method is invoked only if action events have been enabled for this menu item. This can happen cither when an action listener is added to this component or when action events are explicitly enabled via the use of enableEventsO. Typically, a program controls how action events for a menu item are processed by adding or removing action listeners. It overrides processActionEventO onl> if it needs to do processing in addition to that performed by the registered listeners.
When a subclass does override processActionFvent(). it should call
super.processActionEventO to perform the processing intended by its
base class (such as dispatching the listeners).
PARAMETERS
V evt The event to be processed.
W
X
Y
Z
si т м so java.awt.event.ActionEvent, java.awt.event.Actionl i stener»
processEventO.
example This example is a variation of the one for MenuComponent.dispatch-
EventO. It overrides processActionEventO to support SetFontEvent (a
subclass of ActionEvent). See Figure 279. The rest of the example is the
same as that for dispatchEventO; only MainMenuItem has changed.
Note: In Java 1.1,2. the menu is not properly resized.
1098
proccssEx end )
< processActi... BSE
Snial
I argt
FIGI RE 279: Adding Support for a I'scr-defined
Event Type for Menuitem.
class MainMenuItem extends Menuitem {
MainMenuItem(String label) {
super(1abel);
}
// Override to handle special new event (SetFontEvent)
protected void processActionEvent(ActionEvent evt; {
if (evt instanceof SetFontEvent) {
// Change font as requested
processSetFontFvent((SetFontEvent) evt);
} else {
super.processActionEvent(evt);
}
}
protected void processSetFontEvent(SetFontEvent evt) {
// perform font change on this menu item
set Font(evt.getFont());
}
}
processEvent!)
PI RP()SP Processes an event enabled lor this menu item.
\7 \\ protected void processEvent(AtoTEvent evt;
ORSC riptjox Menu items currently only support action events. This method tan be overrid- den by subclasses to handle new types of event, in which case the subclasses should call super. processEvent () to ensure that action events are handled properly.
PAR Wil. 11 RS
evt The event to be processed
O\ FRRIDI s MenuComponent.processEvent().
Menu I tem
java.awt
removeActionListener()
SEE also AWTEvent, processActionEvent().
lxampli- See MenuComponent .di spatchEventO.
removeActionListenerQ
pcrpose Removes a listener from receiv ing action events from this menu item.
syntax public synchronized void removeActionlistener(ActionListener
1i stener)
description An action event is fired when this menu item is selected. See ActionEvent
and the class description for more details. After this method is called, the
action listener listener will no longer receive action events from this menu
item. If 1 istener is null, this method does nothing.
parameters
listener I'hc possibly null action listener to remove.
see alm.) addActionl istenerf) , java.awt.event.ActionFvent,
java.awt.event.ActionLi stener.
exampi f See disableEventsO.
setActionCommand()
0 PCRPOSI. Sets the command name of action events fired by this menu item.
p SYNTAX public void setActionCommand(String command)
Q DESCRIPTION An action event is fired when this menu item is selected. That action event
R S contains an action command indicating the command issued bv this menu item. By default, the action command is the label of the menu item. This method sets the action command of this menu item to be command. It does not
T и PARAMETERS change the label of this menu item.
V command The command name of rhe action events fired b> this menu item.
w SEE ALSO getActionCommandO, getLabelQ.
x
Y
Z
1100
set Acl ion( 'oniniii
.-win t 'I'his example creates a menu that contains
menu items whose labels can be localized. 'I'he
menu item’s action command is used to store a
nonlocalized siring tor identifying the menu
item. Sec Figure 280.
import java.awt.''';
import java.awt.eventW ;
import java.util.ResourceBundie;
import java.uti1.Locale;
public class Main extends Frame {
Main() {
super(“setActionCommand Example") ;
}
void init(ActionListener 1) {
// Get localized labels for menu items
ResourceBundl e rb = ResourceBundl e.getBundl e(
String one = rb.getString(“menuitemOne") ;
String two = rb.getString(“menuitemTwo");
String three = rb.getString(“menuitemThree");
String heading = rb.getString(“menuHeading"):
// Create checkboxes
Menu menu = new' Menu(heading);
Menuitem ml = new Menuitem(one);
Menuitem m2 = new Menultem(two);
Menuitem m3 = new Menultem(three);
// Set internationalized identifiers for menu
menu. setNameC’number”) ;
ml. setActi onCommand(“one") ;
m2 . setActi onCommandC’two”) ;
m3 . setActi onCommandC’three") ;
' setAction... BHB
пйтёпГ~ВН^^Н|^Н||||
un
deux
trois
I Kit RE 2X0: Menuitem
Localization I sing Action
Commands.
“MyBundle", getLocale());
and menuitems
/7 Add listener for menu and menu items
menu.addActi onLi stener(1);
ml.addActionLi stener(l);
m2.addActionLi stener(1);
m3.addActionLi stener(l);
// Add menu items to menu
menu.add(ml);
menu.add(m2);
menu.add(m3);
MenuBar mb = new MenuBarO :
mb.addfmenu);
setMenuBar(mb);
set Si ze f109, 100 > :
showC; ;
static oublic void mainГ StrinqГ1 arqs)
Mai n m - new Mai n(j ;
Menuitem
set Enabl ed()
java.awt
// Set locale of component
m.setLocale(Locale.FRANCE);
m.init(new ActionEventHandler());
J
}
A class ActionEventHandler implements Action! istener {
public void actionPerformed(ActionEvent evt) {
В String target « evt.getActionCommandQ;
int number = 0;
C
if (target.equals(“one”)) {
D number = 1;
} if (target.equals(“two")) {
[• number - 2;
} if (target.equals(Hthree”)) {
F number = 3;
}
G System.out.println(“number - " * number);
}
H }
J
К
L
setEnabled()
pl rpose Enables or disables the menu item.
M
syntax public synchronized void setEnab1ed(boolean on)
N
О
P
Q
R
S
T
L’
V
W
X
Y
Z
description This method enables or disables this menu item. See lhe class description for
details on a menu item's enabled property. This method call is ignored if the
enabled property of the menu item is not changed.
PARAMETERS
on If true, this menu item is enabled; otherwise, this menu item is disabled.
see. also 1 s Enabl ed().
example This example creates a frame that has two
buttons. One button disables all menu
items in the menu ban and the other
enables them. See Figure 281.
import java.awt.'-;
import java.awt.event.*;
class Main extends Frame
implements ActionListener {
MainO {
superCsetEnabled Example");
MenuBar mb - new MenuBarO;
Menu m = new Menu(“Fi le’’) ;
Hl.I RF 28li Enabling and
Disabling Menuitems.
m.add(“New”);
1102
set Labe U I
JtlVd.tIWI
т.add("Open. ..”);
mb.add(T);
m = new Menu("tdit");
m.add("Cut”);
m.add(*'Paste");
mb.add(m);
A
// Add the two enable/disable buttons.
Button b; E
add(b = new Button(“Enable")t Border!ayout.WEST);
b.addActionListener(this); <
add(b = new Button("Disable"), BorderLayout.EAST);
b.addActionListener(this); I
// Set the menu bar on the frame. I
setMenuBar(mb);
setSize(100, 100); f
showO ;
} (
// Action handler for buttons J
public void actionPerformed(ActionEvent evt) {
String what = evt.getActionCommandO ;
boolean enable - "Enable”.equals(what);
if (enable II "Disable”.equals(what)) {
for (int i=0; i <getMenuBar().getMenuCountO ; i*+) { &
Menu m getMenuBarO.getMenu(i);
for (int j-0; j<qetMenuBar() .getMenu(i) .getltemCountO ; ) + ♦) { M
m.getltem(j).setFnabled(enable); К
}
}
}
} <
static public void main(String;] args) {
new Main();
1 ‘
}
setLabeK)
' — —
PURPOSE Sers the menu item's label.
SYNTAX public synchronized void setLabe1(String label)
DESCRI P'l |()X This method sets the label of this menu item to be the string label.
PAR А МЕЛ E RS label The non-null siring specifying the menu item's new label.
Menu Item
setShortcutf)
Java.awt
i-xample This example creates a menu that has one
menu item and two buttons: One and Two.
Clicking a button sets the label of the menu
item to the label of the button. See Figure 282.
A
В
C
Г)
E
F
G
II
I
J
К
L
import java.awt.ir;
import java.awt.event.*1;
class Main extends Frame implements ActionListener{
MenuTtem mi = new MenuItem(“One’’) ;
N
G
P
Q
HGI RE 282:
Menuitem.setLabelО.
MainO {
super(“setLabel Example");
MenuBar mb - new MenuBarO;
Menu m new Menu("Menu'');
// Add menu item,
m. add(mi);
// Add the two buttons.
Button b;
add(b - new Button(“One’’), Borderlayout.VvFSI) ;
b.addActionListenerCthi s);
add(b - new Button("Two”), BorderLayout.LAST);
b.addActionListenerCthi s);
// Set tne menu bar on the frame,
mb.add(m);
setMenuBarCmb);
setSi?e(100, 100);
show();
}
// Action handler for buttons
public void actionPerformedCActionFvent evt) {
mi . set I aoel (evt. getAct ionCommandO);
}
M
r static public void main(Strinq[] args) {
new Main();
s }
}
T
i:
setShortcut()
w Pl RPOS1 Sets this menu item s keyboard shortcut.
X SYNTAX public void setShortcutfMenuShortcut shortcut)
Y DESCRIPTION Sec (he class description for details on keyboard shortcuts.
7 Note: In Java 1.1.2. setting a non-null shortcut does not update the visual indication that this menu item has a shortcut.
1104
J «Л X d.dv\ I
set Shortcut! )
PARAMI 11 RS
shortcut I'hix menu item's keyboard shortcut. It may be null, which means this menu
item has no keyboard shortcut.
SEEALSO deleteShortcut(), getShortcut().
example This example creates a menu that has one menu
item, which has a menu shortcut. A row of but-
tons controls the addition and deletion of the
shortcut, as well as prints out the shortcut. See
Figure 283.
import java.awt.w। ।
import java.awt.event.Show I Delete I Add
import java, util. Enumeration; —............
1 I, • -j Л I ка RE 283:
class Main extends Frame implements ActionListener
। Menu Item Shortcuts.
MenuBar mb = new MenuBarO;
MenuShortcut shortcut = new MenuShortcut(KeyEvent.VK S);
Menuitem mi;
Button view = new Button(“Show”);
Button delete = new Button(“Delete”);
Button add = new Button(“Add”);
boolean delsc = false;
Main() {
super(“deleteShortcut Example”) ;
Menu m = new Menu(“Fi 1 e’’) ;
mi = new MenuItem(“Save”, shortcut);
mi . setActionCommand(“Save‘’) ; // required for shortcut
m.add(mi);
// Add listener for menu (and its menu items)
m.addActi onListener(this);
// Set the menu bar on the frame
mb.add(m);
setMenuBar(mb) ;
/7 Add controls for viewing, deleting, adding shortcuts
Panel p = new PanelEnew GridLayout(1, 0));
add.setEnabledEfalse);
p.addEvi ew);
p.add(delete) ;
p.add(add);
delete.addActionListener(this) ;
vi ew.addActi onListener<tbis):
add.addActionListenerEthis) ;
addfnew TextAreaГ“Text area”). BorderLayout.CENTER):
addEp, BorderLayout.SOUTH);
setSizeE100, 100);
Menuitem
ja\ u.au t
setShortcut()
show();
1
public void actionPerformed(ActionEvent evt) {
if (evt.getSourceO instanceof Menuitem) {
System.out .println(evt .getActionCommandO) ;
A } else if (evt.getSourceO instanceof Button) {
String sc - evt .getActionCommandO ;
В if (sc.equalsCShow’1)) {
System.out. pri nt In (mi.get Shortcut());
C } else if (sc.equals(“Delete”)) {
mi .del eteShortcutO ;
D delete.setEnabled(false);
add.setEnabled(true);
I- } else if (sc.equals(‘’Add”)) {
rri . setshortcut (shortcut ) :
к add.setlnabled(false);
delete.setEnabled(true);
Cl }
}
H }
I static public void mai n(St ri ng[J args) {
new Mai n();
J J
}
К
I.
M
N
О
P
Q
R
S
T
i:
v
vv
x
Y
7
1106
java.awt.peer
MenuItemPeer
Syntax
public interface MenuItemPeer extends MenuComponentPeer
Description
The menu item (see the Menuitem class) in the AWT uses the platform's native implementa-
tion of a menu item. So that the AWT menu item behaves the same on all platforms, the menu
item is assigned a peer, whose task is to translate the behavior of the platform's native menu
item to the behavior of lhe AWT menu item.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
Menu component peers play lhe same role as component peers. See Component and
Tool ki t for additional information about component peers.
(MEMBER SUMMARY
Peer Methods
setEnabl ed() Enables or disables the menu item.
setLabe 10 Sets the menu item's label.
Deprecated Methods
disable() Replaced by setF.nabled().
enable О Replaced by setEnabled().
I
ja\ a.ava.peer
MenuItemPeer
disable()
See Also
java.awt.Component, java.awt.MenuComponent, java.awt.Menuitem,
java.awt.Toolkit,
Л disable!) DEPRECATED
в c PURPOSE Replaced by setEnabledO.
D SYNTAX void disabled)
H DEPRECATION Replace the usage of this deprecated method, as in
F Ci peer.disable(); with peer.setEnabledCfalse);
H
I enable!) DEPRECATED
J PT RPOSE Replaced by setEnabledO.
К SYNTAX void enableO
L DEPRECATION Replace the usage of this deprecated method, as in
N peer.enableO ; with peer.setEnabled(true);
<)
P setEnabled()
Q Pl RP( >S1. Enables or disables the menu item.
R S T SYNTAX PARAMETERS cond void setEnabled(boolean cond) If true, this menu item is enabled; otherwise. it is disabled.
U sn ALSO java.awt.Menuitem.setFnabled().
V
W setLabel!)
X Y Z PURPOSE SYNTAX PARAMETERS label SEE ALSO Sets the menu item's label, void setLabel(String label) The string specifying the menu item's label. Menuitem.setLabel().
1108
Vd.dVV Lpcir
MenuPeer
Syntax
public interface MenuPeer extends MenuItemPeer
Description
The menu (see the Menu class) in the AWT uses the platform's native implementation of a
menu. So that the AWT menu behaves the same on all platforms, the menu is assigned a peer,
whose task is to translate the behavior of the platform's native menu to the behavior of the
AWT menu.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
Menu component peers play lhe same role as component peers. See Component and
Toolkit for additional information about component peers.
MEMBER SUMMARY
Peer Methods
addltemO Adds a menu item to the menu.
addSeparatorQ Adds a menu item separator to the menu.
delltemO Removes a menu item from the menu. 1
See Also
java.awt.Component, java.awt-Menu, java.awt.Toolkit.
itno
java.awt.peer
MenuPeer
addltem()
addltemO
PURPOSE Adds a menu item to the menu.
A SYNTAX PARAMETERS void addItem(MenuItem menuitem)
В menuitem The non-null menu item.
c D SEE ALSO java, awt .Menu. add().
К addSeparator()
F
G PURPOSE Adds a menu item separator to the menu.
H SYNTAX void addSeparatorO
1 J SEE AI.SO j ava.awt.Menu.addSepa rato r().
К L delltem()
PURPOSE Removes a menu item from the menu.
SYNTAX void delltem(int pos)
N PARAMETERS
o pos The zero-based index of the menu item in the menu.
P SEE ALSO j ava.awt.Menu.remove О.
Q
R
S
T
и
V
w
X
Y
Z
1110
MenuShortcut
Syntax
public class MenuShortcut implements Serializable
Description
The user can select an enabled menu item either by using mouse actions or by pressing the
menu item’s menu shortcut (or keyboard .shortcut). A menu shortcut is a sequence of key
strokes that can be associated with a menu item. The shortcut can be installed, deleted, and
changed at any time. A menu item that has a menu shortcut typically displays its shortcut
beside the menu item’s label. How the shortcut is displayed is platform-dependent.
Note: In Java 1.1.2, you must use setActi onCommandO on a menu item in order for its
shortcut to work. Otherwise, the action event it fires contains a null action command.
Key Sequence
When you create a shortcut, you specify a virtual key code (see KeyEvent). When the key cor-
responding to that key code and a modifier key determined by tool ki t .getMenuShortcut-
KeyMaskQ are pressed simultaneously, the corresponding menu item is selected. By default,
the menu shortcut modifier key is Control (Ctrl). You can specify that a shortcut use the Shift
key modifier as well, so that lo select the menu item, you need to press the key corresponding
to the key code simultaneously with the modifier key and the Shift key.
Member summary ]
Constructor MenuShortcutQ Constructs a new MenuShortcut instance.
Comparison Method equals О Determines if two menu shortcuts are the same. !
Key Methods getKeyQ usesShi ftModi fi er О Retrieves this menu shortcut’s virtual key code. Determines whether this menu shortcut must be invoked with the Shift key. 1
Debugging Methods paramStri ngO toStri ngO Generates a string representation of this menu shortcut. Generates a localized string representation of this menu short- cut. 1
i f 11
MenuShortcut
java.awt
See Also
java.awt.event.KeyEvent, java.io.Seri allzable, Menuitem,
Tool ki t. getMenuShortcutKeyMaskQ.
A Example
3 This example creates a menu with two menu items, each
having a menu shortcut. When the menu item is selected,
C
the action event handler prints out the action command of
D the event, as well as information on the shortcut of the
_ menu item that fired the event. See Figure 284.
p import java.awt.*: EIGl RE 284: MenuShortcut.
import java,awt.event.*;
G
class Main extends Frame implements ActionListener {
H MainQ {
super(“MenuShortcut Example”);
j Menu m = new Menu(‘Ti le”) ;
j // Create menu items with shortcuts
Menuitem mi =-
К new Menultpm(“Edit”, new MenuShortcut(KeyEvent.VK_E));
mi.setActionCommandC'Edit”); // required for shortcut
। mi.addActi onLi stener(thi s);
m.add(mi);
mi « new MenuTtem(“Save”, new MenuShortcut(KeyEvent.VK S));
mi.setActionCommandC'Save”); // required for shortcut
m.add(mi);
О mi.addActionListener(this);
p // Set the menu bar on the frame.
MenuBar mb = new MenuBarO;
q mb.add(r);
setMenuBar(mb);
R
setSize(100, 100);
c show();
}
T
public void actionPerformed(ActionEvent evt) {
U if (evt.getSourceO instanceof Menuitem) {
Menuitem mi = (Menultem)evt.getSourceO;
у System.out.println(“Source - “ + mi.toString());
MenuShortcut ms = mi.getShortcutO;
W if (ms 1= null) {
System.out.println(“\tKey = ° + ms.getKeyO);
X System.out.println(“\tShift = ” + ms.usesShiftModifier());
Y } . .
System.out.println(“Action Command = ” + evt.getActionCommandO);
7. }
static public void mai n(Stri ng[] args) {
new Mai n();
1112
JctVd.dWl
equal s(
equalsO
purpose Determines if two menu shortcuts are the same.
SYNTAX public boolean equals(MenuShortcut shortcut)
description Two menu shortcuts are equal only if both use the same key and both use the Shift key in the same way (either both use or both don't use the Shift key).
PARAMETERS shortcut The possibly nul 1 menu shortcut with which to compare.
RETURNS true if this menu shortcut is equal to shortcut.
OVERRIDES java.lang.Object.equals().
EXAMPLE See java.lang.Object.equals().
getKeyO
PURPOSE Retrieves this menu shortcut's virtual key code.
SYNTAX public int getKeyO
DESCRIPTION This is the key code with which this menu shortcut was created.
RETURNS The key code of this menu shortcut.
SEE ALSO j ava.awt.event.KeyFvent.
EXAMPLE See the class example.
MenuShortcutf)
PURPOSE Constructs a new MenuShortcut instance.
SYNTAX public MenuShortcut(int keyCode) public MenuShortcut(int keyCode, boolean useShift)
DESCRIPTION This constructor creates a new instance of MenuShortcut for the key code keyCode. If useShi ft is true, then when typing in the shortcut the user must press the menu shortcut modifier key (by default Control) and the Shift key along with the key corresponding to keyCode. If useShift is false or
MenuShortcut
MenuShortcuK)
java.awt
- ЯГ“1ЕЭ
ECft Ctrl+E
Save Ctri+SHft+S
FIGURE 2X5: MenuShortcut().
unspecified, only the menu shortcut modifier key must be pressed with the kex
when lhe shortcut is typed.
PARAMETERS
keyCode The virtual key code for this menu shortcut (c.g., KeyEvent .VK A ,.j.
useShift If true, the Shift kc\ must be pressed; if false, the Shift kex must not be
pressed.
ski-also getKeyO, usesShiftModifier(). loolki t.get^enuShortcutKeyVaskC).
example This example creates a menu that has two
menu items, each with a shortcut. One
shortcut uses the Shift modifier: the other
does not. See Figure 285.
import java.awt,";
import java.awt.event.";
class Main extends Frame
implements ActionListener {
Main() {
super(“MenuShortcut Example”);
Menu m = new Menu(‘‘Fi 1 e”) ;
// Create menu items with shortcuts
Menuitem mi -
new MenuItemC‘Edi t” , new MenuShortcut(KeyEvent.VK_E));
mi . setActionCommandC'Fdi t1') ; // required for shortcut
m.addfmi);
mi - new Menultem("Save’\
new MenuShortcut(KeyEvent,VK_S, true)): // Shift
mi.setActionCommand(“Save”); // required for shortcut
m.add(mi);
// Add listener for menu (and its menu items)
m.addActionLi stenerCthis);
// Set the menu bar on the frame.
MenuBar mb = new MenuBarO;
mb.add(m):
setMenuBar(mb);
setSize(100, 100);
showf);
}
public void actionPerformed(ActionEvent evt) {
System.out.println(evt .getActionCommandQ) ;
}
static public void main(String[] args) {
new Mai n();
1
}
1114
paramStringO
paramString()
PCRPOSI; Generates a string representation of this menu shortcut.
SYNTAX protected String paramStringO
DESCRIPTION The string representation consists of the menu shortcut’s key code and an indi- cation of whether the Shift key is used. A subclass of this class should override this method and return a concatenation of its slate with the results of super. paramStringO. This method is typically used for debugging.
RETURNS The non null string representation of this menu shortcut.
SEE A [.SO toStringO.
EXAMPLE See the AWTEvent class example.
toStringO . ~ ~ .... ...
PURPOSE Generates a localized string representation of this menu shortcut.
SYNTAX public String toStringO
DESCRIPTION The localized string representation consists of the menu shortcut’s key code and whether the Shift key is required.
RETURNS A non-null localized string of this menu shortcut.
OVERRIDES java, lang .Object. toStringO.
SEE AL SO paramStringO.
EXAMPLE See the class example.
PURPOSE Determines whether this menu shortcut must be invoked with the Shift key.
SYNTAX public boolean usesShiftModifierQ
RETURNS true if the Shift key must be used; false if the Shift key must not be used.
SEE Al SO MenuShortcutO.
example See the class example.
java.beans
MethodDescriptor
A
15
C
1)
E
F
Ci
H
1
Syntax
public class MethodDescriptor extends FeatureDescriptor
J
К
L
Description
M
N
О
P
Q
R
S
T
L
V
W
X
A method descriptor contains additional information
about a public method in a bean, such as the method's
localized name and whether it is meant for experts.
There is one method descriptor for each public
method. A bean’s method descriptors can be retrieved
through the introspector by calling Introspec-
tor .getBeanlnfoQ .getMethodDescri ptorsO.
Method descriptors are also used by event set
descriptors (see EventSetDescriptor) to represent
the methods that support an event.
For Bean Editors Only
The information contained in a method descriptor is
meant for programs such as bean editors (programs
that help connect together beans into an application):
it is not used by the bean itself. These and other
descriptors essentially help a bean editor to construct
a meaningful user interface for editing the bean.
Introspector
Explicit
Descriptors
Implicit
Descriptors
Bean
Bean Descriptor
Event Set Descriptors !
Method Descriptors
Parameter Descriptors
Property Descriptors j
Bean-Info
FIGI RE 286: MethodDescriptor.
When the bean is actually running in an application, the method descriptors are never used.
Y Implicit and Explicit Method Descriptors
Z When retrieving the method descriptors, the introspector first looks in the bean's bean-info
(see Beaninfo) for any method descriptors that the bean has explicitly supplied. These are
called explicit method descriptors. If none is found, the introspector must use introspection on
1116
javii.ueans
iviciiivuL/v^vi арша
the bean to discover all of the bean's methods and then create implicit method descriptors for
the method. Implicit method descriptors are given default values for some of the method
descriptor attributes. See Figure 286. Table 20 shows the attributes of a method descriptor and
the default values for implicit method descriptors.
Attribute Contents Implicit Default Value
Method The method's Method object. l he method's Method object.
Parameter descriptors The method's parameter descriptors. The method's parameter descriptors.
Name Display name Short description Expert I'he method's nonlocalized name. lhe method's name. The method’s localized name. The method's name. Л localized description of lhe method. The method's name, true if lhe method is considered for fal se. use by experts only.
Hidden true if the method is meant to be used false. by a tool; fal se if is meant to be used by a person.
TABLE 20 Method Descriptor Attributes.
MEMBER SUMMARY
Constructor MethodDescri ptor() Constructs a new MethodDescri ptor instance.
Method Descriptor Method getMethodO Retrieves the method descriptor's Method object.
Parameter Descriptor Method getParameterDescriptorsQ Retrieves the method descriptor's parameter descriptors.
See Also
java.1ang.reflect.Method, ParameterDescri ptor.
Example
This example demonstrates how to construct method and parameter descriptors. A bean is cre-
ated with two methods: one hidden and one expert. The expert method is given a short descrip-
MethodDescriptor
java.beans
tion and includes a parameter descriptor for its single parameter. The parameter descriptor
expert attribute is set to true and is given a short description.
Bean.java
public class Bean {
public void useAtYourOwnRisk(int dangerousParameter) {
public void forToolsOnly() {
}
BeanBeanlnfo.java
import java.beans.*;
import java.1ang.reflect.”;
public class BeanBeanlnfo extends SimpleBeaninfo {
public MethodDescriptor[] getMethodDescri ptorsO {
MethodDescriptor rrd[l - new MethodDescriptor[21 ;
try {
md[0] - new MethodDescriptor(getMethod(Bean.class, "forToolsCnly"));
md[0].setHi dden(true);
ParameterDescriptor[] pd = new ParameterDescriptor[11;
pd[0] = new ParameterDescriptor();
pd[0).setShortDescription(”Never ever set to 34121491839:!'”);
pd[0].setName("dangerousParameter”);
pd[0].setFxpert(true);
md[l] =• new MethodDescriptor(getMethod(Bean.с 1 ass,
"useAtYourOwnRisk”), pd);
mdrLll .setShortDescription(
"ONLY use when Jupiter is aligned with Mars");
md[lj.setExpert(true);
return md;
} catch (IntrospectionException e) {
e.printStackTraceO ;
J
return nul1;
}
Method getMethod(Class cis. String methodName)
throws Introspectionlxception {
Method methods^ cls .get^ethodsO ;
for (int i^0; i<methods.length; i + O {
if (methods [i j .getNameO . equal s(methodName)) {
return methods [i];
1
throw new IntrospectionExceptionC'No method \"” * methodName);
1118
getMethodO
getMethodO
PURPOSE Retrieves the method descriptor‘s Method object.
SYNTAX public Method getMethodO
DESCRIPTION A method descriptor contains one Method object and some attributes for that method. This method returns the Method object.
RETURNS The non-null Method object.
EXAMPLE See the Introspector class example.
getParameterDescriptorsf)
PURPOSE Retrieves the method descriptor’s parameter descriptors.
SYNTAX public ParameterDescriptor[] getParameterDescriptorsO
DESCRIPTION A method descriptor can optionally specify a set of parameter descriptors for any of its parameters (see ParameterDescri ptor). The parameter descriptors must be supplied to the method descriptor constructor. This method returns any specified parameter descriptors. If none have been specified, then null is returned.
RETURNS A possibly nul 1 array containing the method’s parameter descriptors.
EXAMPLE See the Introspector class example.
MethodDescriptor()
PURPOSE Constructs a new MethodDescriptor instance.
SYNTAX public MethodDescriptor(Method method) public MethodDescriptor(Method method, ParameterDescriptor ParameterDescri ptors[])
DESCRIPTION Method descriptors are either implicitly created by the introspector or are explicitly created by a bean. See the class description for more information. This constructor creates a method descriptor for the method method. Parame- terDescri ptors specifies the method’s parameter descriptors. If Parame- terDescri ptors is not specified, it defaults to null. When a method descriptor is created, two attributes are initialized: • Method object • Parameter descriptors
MethodDescriptor
MethodDescriptort)
java, beans
All other attributes are given default values, which can be changed by methods
in the FeatureDescriptor class. The default values for a method descriptor
are shown in Table 20.
PARAMETERS
method A non-nul 1 Method object.
parameterDescriptors
A possibly null array of the method's parameter descriptors.
I-x ample See the class example.
1120
java.awi.cvcni
MouseAdapter
J
Syntax
public abstract class MouseAdapter implements MouseListener
Description
The mouse adapter is a mouse listener in which all callback methods are empty implementa-
tions. fhe purpose of the mouse adapter is to make it more convenient for an object lo listen
for mouse events. In particular, by using the mouse adapter, you can implement only those
callback methods in which you are interested. Without the mouse adapter, you are required to
implement all callback methods, even if (he method is empty.
To use a mouse adapter, you create a subclass of MouseAdapter and override lhe desired
callback methods. You then create an instance of the mouse adapter subclass and call the com-
ponent’s addMouseListener() method with it. The mouse adapter subclass is typically an
inner class.
' • — — ' • SUMMARY to... . ... . ...
Mouse Event Callback Methods
moused ickedQ Called when the user clicks the source component.
mouseEnteredO Called when the cursor enters lhe source component's exposed bounds.
mouseExi tedQ Called when the cursor exits lhe source component’s exposed bounds.
mousePressedO Called when lhe user presses a mouse button in the source com- ponent.
mouseReleased() Called when the user releases a mouse button in the source component.
See Also
java.awt.Component.addMouseListenerO, MouseEvent, MouseListener.
MouseAdapter
java.awt.event
Example
This example demonstrates how to display a short
description of a component in a status bar when the
mouse moves over the component. The example
creates a new type of button that can hold a string
containing a short description of the button. The
frame creates a number of these buttons and then
» MouseAdapter Example
Create | Open | Save j Close J
Create a new document
FIGVRE2S7: MouseAdapter.
listens for MOUSE-ENTERED and MOUSE-EXITED events from them. When a MOUSE-ENTERED
event is received, the frame prints the button's description in its status bar: uhen a
MOUSE-EXITED is receixcd. the frame clears its status bar. Sec Figure 287.
import java.awt.-;
import java.awt.event.*;
class Main extends Frame {
Label statusbar = new Label ('‘Ready");
Main() {
super("MouseAdapter Example");
MainButton b;
MouseEventHandler mhandler - new MouseEventHandler();
Panel toolbar = new Panel(new Flow!ayout());
/7 Create the buttons.
b = new MainButtonC'Create", "Create a new document/');
b.addMouseLi stener(mhandler);
toolbar.add(b);
b - new Mai nButton/'Open", "Open an existing document/'):
b.addMouseLi stener(mhandler);
tool bar.add(b);
b new ^ainButton("Save"T "Save the current document.");
b.addMouseLi stener(mhandler);
tool bar.add(b);
b - new MainButton/'Close", "Close the current document."):
b.addMousel istener(mhandler);
toolbar.add(b);
add(toolbar. Borderlayout.CENTER);
add(statusbar, Border!ayout.SOUTH);
pack():
show();
}
class MouseFventHandler extends MouseAdapter {
public, void mouseEntered(MouseEvent evt) (
stat usbar.setText(
((MainButton)evt .getSourceO) • qetDescriptionO);
}
public void mouseExited(MouseEvent evt) {
statusbar.setText(null);
}
}
1122
moused ickedO
public static void main(Strinq args[J) {
new Mai n():
}
}
// The main purpose of this button subclass is simply to hold
// a description string.
class MainButton extends Button {
String desc;
MainButton(String label, String desc) {
super(label);
this.desc = desc;
}
String getDescription() {
return desc;
}
1
mouseClickedO
purpose Called when the user clicks the source component.
SYNTAX public void mouseClickedfMouseEvent evt)
DESCRIPTION This method is called after the mousePressedO and mouseReleasedO methods are called in the case in which the mouse coordinates of both events are the same (or very close together). See MouseEvent.MOUSt_CLICKED for more details about mouse clicked events. This method by default has an empty implementation.
PARAMETERS evt The non-null mouse event.
EXAMPLE See the MouseEvent class example.
mouseEnteredO
PURPOSE. Called when the cursor enters the source component's exposed bounds.
SYNTAX public void mousefntered(MouseEvent evt)
DESCRIPT ION This method, by default, has an empty implementation, h should be overridden to handle MouseEvent.MOUSE-ENTERED events. For details, see Mouse- Event .MOUSE_FNTERFD.
PARAMETERS evt The non-null mouse event.
EXAMPLE See the MouseEvent class example.
MouseAdapter
mouscExitedt)
ja\ a.aw t.ev ent
mouscExitecU) pi rpoxf Called when lhe cursor exits the source component's exposed bounds.
/X syntax public void mouseExited(MouseEvent evt) descripiion This method is called when the cursor is no longer on the source component's
в exposed bounds. For more details about mouse exited events, see Mouse-
c Event .MOUSE-EXITED.
D E F This method, bx default, has an emptx implementation. PARAMETERS evt l he non-null mouse event. exampi i See the MouseEvent class example.
Ci
H
1 mousePressedf)
.1 pvrposi ('ailed when the user presses a mouse button in the source component.
К syntax public void mousePressed(MouseEvent evt)
L pescripi ion This method is called when a mouse button is pressed. For more details about
mouse pressed events, see MouseEvent .MOUSE-PRESSED.
N This method, by default, has an emptx implementation.
() PARAMETERS evt The non-nul 1 mouse ev ent. MMWVnWVWnWB—Tml—1
P exampi i This example implements a simple
Q game. The component is infested with
R bugs, and your task is to smack them.
S When a bug is smacked, it turns into a J beautiful flower. Un fortunate lx. the
T flowers can shield other bugs from
и beinsi smacked. See Figure 288.
V The mouse clicks are handled bx a * I J mouse event handler. Since onlx lhe
w mouse pressed event is needed, lhe xSl?'7
X program uses the mouse adapter to
Y avoid writing empty implementation for the other mouse events. figure 288: Bugs.
7. The bugs are controlled by a single thread. The thread works in two phases. In (he first phase, it waits a random
1124
mousePressedO
amount of time and then creates a bug. In the second phase, it makes the bug
move until the bug moves off the Held.
The example uses an off-screen image (bbuf) to implement double-buffering
in order to eliminate flickering. The off-screen image is first cleared. Then all
of the characters are painted at their current locations. 1Ъе completed off-
screen image is then painted on the screen,
import java.awt.";
import java.awt.event;
public class Main extends Frame {
InfestedComponent bugs = new InfestedComponentO;
MainQ {
super("mousePressed Example");
// Layout component.
add(bugs, BorderLayout.CENTER);
packO;
showO ;
}
public static void main(String args[]) {
new Main();
}
}
class InfestedComponent extends Canvas implements Runnable {
// Bug and field dimensions. The flower is the same size
// as a bug.
int bugSize - 30;
int fieldsize = 200;
// true iff a bug is visible and running across the field.
boolean bugRunning;
// This field specifies which of the four bug images to use.
int curlmage = 0;
// This field holds the increments that are applied to the
// bug's (x, y) location to make it move across the field.
Point bugOir;
// Rectangles used the the hit detection code.
Rectangle bugRect = new Rectangle(fieldSize, 0, bugSize, bugSize);
Rectangle fieldRect = new Rectangle(0, 0, 200, 200);
Rectangle[] flowers = new Rectangle[100];
// Number of flowers on the field.
int flowerCount;
// Fields used for double-buffering.
Image bbuf;
Graphics bbufG;
// Color of the field.
Color bgColor - new Color(204, 255, 204);
MouseAdapter
mouse Pressed ()
java.awt.event
Image bugimages[] = new Image[4];
Image fl owerimage;
InfestedComponentO {
// Load images.
flowerimage = getToolkitО-getlmage(”flower.gif*');
for (int i=0; i<4; i++) {
bugimages [i] = getTool ki t() .getlmage(,,bug’1+i +" .gi f") ;
}
// Listen for mouse events.
addMouseListener(new MouseEventHandlerO);
// Start thread.
(new Thread(this)) .startO ;
setSize(fieldSize, fieldsize);
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
// Create the double-buffer if necessary.
if (bbuf === null) {
bbuf = createlmage(fieldSize, fieldsize);
bbufG bbuf .getGraphics() ;
}
// Clear the field.
bbufG.setColor(bgColor);
bbufG.fi1lRect(0, 0, fieldsize, fieldSize);
// Paint the bug.
if (bugRunning) {
bbufG.setColor(Col or.black);
bbufG.drawlmage(bugimages[curlmage], bugRect.x, bugRect.y, this;
}
// Paint flowers.
bbufG.setColor(Color.yellow);
for (int i=0; i<flowerCount; i+ч) {
bbufG.drawlmage(f1owerlmage, flowers[i].x, flowers[i].y, this);
}
// Paint double-buffer on screen.
g.drawlmage(bbuf, 0, 0, this);
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
i nt x = evt.getXO ;
int у = evt.getY();
// Check if bug is hit.
if (bugRect.contains(x, y)) {
// First check that it's not on a flower.
for (int i=0; i<flowerCount; i++) {
1126
mousePressedO
if (flowers[i].contains(x, y)) {
return;
}
}
// Bug is hit now turn it into a flower.
flowers[flowerCount++] - new Rectangle(bugRect);
bugRunning -- false;
repai nt():
}
}
}
// Convenient integer random number generator.
int rand(int r) {
return (int)Math.floor(Math. randomQ * r);
}
public void run() {
int steps = 15;
int delay = 60;
while (true) {
try {
// Wait a little while before the next bug.
Th read.sieep(rand(5000));
// Create a bug.
bugRect.x = rand(fieldSize-bug5ize);
bugRect.y - rand(fieldSize -bugSize);
// Pick a direction.
curlmage = rand(4);
switch (curlmage) {
case 0: // from north
bugRect.y = 0;
bugDir = new Point(0, steps);
break;
case 1: // from west
bugRect.x = 0;
bugDir = new Point(steps, 0);
break;
case 2: // from south
bugRect.y - fieldSize;
bugDir =- new Point(0, steps);
break:
case 3: // from east
bugRect.x = fieldSize;
bugDir - new Point(-steps, 0);
break:
}
// Start the bug running.
bugRunning ~ true;
while (bugRunning) {
// Move the bug.
bugRect.x += bugDir.x;
bugRect.y +^= bugDir. у;
112*
MouseAdapter
mouseReleasedO
java. awl. event
// Is the bug still on the field?
if (!fioldRect.intersects(bugRect)) {
bugRunning = false:
}
repai nt();
Thread.sieep(delay);
A }
} catch (Exception e) {
В e.printStackTraceO;
}
C }
}
D }
E
F
Ci
H
J
J
К
L
M
N
()
mouseRcleasedf)
purpose Called when the user releases a mouse button in the source component.
syntax public void mouseReleased(Mousetvent evt)
dfscriptiox This method is called when a mouse button is released. For more details aboi
mouse released events, see MouseEvent .MOUSE_RFLEASED.
This method, by default, has an empty implementation.
PARAMETERS
evt The non-null mouse event.
ex ample See the MouseEvent class example.
P
Q
R
S
I
II
V
w
X
Y
Z
1128
j ava. aw i.c vein
MouseEvent
Syntax
public class MouseEvent extends InputEvent
Description
Mouse events are fired by a component (see Component) when the user interacts with the
component using the mouse. For example, when the cursor enters the component bounds, a
MOUSE_ENTERED event is fired and when the user clicks a mouse button, a MOUSE_PRESSED
event is fired. For more general information about events, see AWTEvent.
Listening for Mouse Events
To listen for mouse events from a component, the listener must implement the Mouse-
Li stener interface. After that, the listener must be registered with the component. It becomes
registered by calling the component’s addMouseLi stener() method.
An alternative, and possibly more convenient, way of receiving mouse events is to use a
mouse adapter. See MouseAdapter for more details.
Unlike with most events, mouse events are delivered to a component's listeners before the
operation takes place. This gives the listeners an opportunity to consume the event. See
InputEvent.consume О formore details.
Mouse Event Elow
Figure 289 shows how mouse events typically flow through the sy stem. First, the event is fired
by a component peer in response to the user’s interacting with the mouse. This event is posted
on the event queue (see EventQueue). When the event makes its way to the front of the queue,
it is given to the component via its di spatchEventO method. The main purpose of this
method is to forward the event directly back to the component peer if the mouse event type is
not enabled or if there are no mouse listeners. Otherwise, di spatchEventO calls pro-
cessEventO, which in turn calls different methods depending on the event type. Since this is
a mouse event, processMouseEventO is called. The main purpose of this method is to notify
in
MouseEvent
java.awt.event
the mouse event listeners. Finally. if the event has not been consumed (see InputEvent). it is
forwarded back to the originating component peer.
A component can override processMouseEventQ to process mouse events betorc they
are delivered to its listeners. The overridden method should call super.processMouse-
Event() to ensure that events are dispatched to the component's listeners.
Component Peer
MouseEvent
System
Event
Queue
di spatchEventO
Component
processEventO
MouseMotionl. i stener
MouseLi stener
processVouseMot ionEventO i—►
processMouseEventO
О
0^
consumeO
ComponentPeer handleFventО
FIGI’RE 289; Mouse Event Flow.
Simulating Mouse Events
Mouse events are normally created by lhe AWT system when the user interacts with the
mouse. However, it is possible for any object to create key events in the same way. f or exam-
ple. a program designed to test a scroll bar can create various mouse events and deliver them to
the scroll bar. The scroll bar will treat a mouse event exactly as if it came from the AWT sys-
tem.
A created mouse event can be delivered to a component in one of two ways, blither by
posting the event to the event queue (as in Figure 2X9) or by calling the component4*
di spatchEventO method directly.
Mouse Buttons and Modifier Keys
The AWT .system supports a three-button mouse- Button I, Button!, and Button?—and four
modifier keys—Ah, Control, Mela, and Shift. The mapping between rhe four modifier keys
and lhe actual keys on the keyboard is platform-dependent. Support for platforms that support
fewer than three mouse buttons (e.g., lhe Macintosh mouse has only one button) involves
using modifier keys to simulate extra mouse burtons. For example, when a mouse exent is
fired when the Meta modifier key pressed, it is considered to be from Button?. The modifier
keys used to simulate a three-button mouse are shown in Table 21.
Modifier Keys Mouse Button
No modifiers Alt Button 1 Burton!
Meta Button?
TABLE 21; Using Modifier Keys to Simulate a Three-button Mouse.
Mouse buttons are treated like modifier keys rather than like keys, as in key events. Therefore,
to detect which mouse button has been pressed, you must apply one of the burton masks to the
modifier key slate. Sometimes, more than one button may appear in lhe modifier key state. For
example, if the user presses Button? along with the Alt modifier key, both Button! and
Button? will appear in the modifier key state. The best way to determine which mouse button
was pressed is to apply the masks in descending order: BUTTONS MASK, BUTT0N2_MASK, and
then BUTTON1J4ASK.
When the mouse really has two or three buttons, pressing Button! or Button? will fire a
mouse event with the appropriate modifier key set. regardless of whether the modifier key was
really pressed. For example, pressing Button? on a three-button mouse will fire a mouse event
whose modifier key state contains BUTTON3.MASK and META„MA5K.
The exact behavior of lhe modifier keys is not well-defined at this point (Java 1.1.2), so
it may be platform-dependent. It is best not to build a user interface that uses Alt- or Meta-
modified mouse gestures. Shift- and Control-modified mouse gestures are fine.
Because a mouse button is treated like a modifier key. you cannot determine which button
was pressed when another was already down, in this case, you must remember the button that
was previously pressed. By the same token, it is difficult to determine which button was
released when more than one w as down, especially if the state of the Ait or Meta modifier keys
changed in the meantime.
For now, it is better to define simple behavior when a mouse button is pressed while
another one is still down. l or example, you could ignore the second mouse button event or
perhaps interpret it as canceling the first.
113
MouseEvent
java. awt.event
Coordinates
Mouse coordinates are relative to rhe component (called the source component) that fired the
mouse event. Mouse coordinates are bounds-relative, which means that mouse location (0. 0)
coincides with the (0, 0) point of the component's bounds.
A
The Click Count
В
The click count indicates the number of quick, consecutive clicks of a mouse button. Il is typi-
C cally used to detect double- and triple-elick gestures. For example, a click count properly \ alue
p of 2 indicates a double-click. The click count is valid only for three mouse events:
MOUSE—CLICKED, MOUSE-PRESSED, and MOUSE-RELEASED. For these, the click count is al least
1. For all other mouse events, the click count is 0.
F
The Popup Trigger Property
G On some platforms, a certain type of mousing gesture can cause a popup menu to appear. For
H example, in Windows 95 this is done by clicking the right mouse button. On other platforms, it
I may be done by holding down a set of modifier clicks while clicking the mouse. So that pro-
grammers need not have to write platform-dependent AWT code, the AWT system determines
J when the user makes the special gesture and then informs the code via a specially marked
K mouse event. In particular, MOUSE-PRESSED and MOUSE-RELEASED events have a popup trig-
ger property that indicates whether the user has made the gesture to show a popup menu.
\1
N
О
P
Q
R
S
T
L‘
V
Guaranteed Event Sequences
The AWT system provides certain guarantees to the ordering of mouse events. Lor example, a
MOUSE-ENTERED event to a component is guaranteed to precede a MOUSE-EXIT event. Also,
every MOUSE-ENTERED event is guaranteed to be eventually followed by a MOUSE-EXIT event
(unless the process is destroyed).
These guaranteed sequences simplify the process of programming components. For exam-
ple, suppose you want to build a component that turns red whenever the cursor is over the
component. All that the component needs to do is turn itself red when it receives a
MOUSE-ENTERED event and restore its original color when it receives a MOUSE-EXIT event. It
does not need to handle the cases in which either it might receive a MOUSE-EXIT event before
the MOUSE-ENTERED event or it might miss the MOUSE-EXIT event.
The set of guaranteed sequences has not been fully specified as of Java 1.1.2. Some of the
known guarantees are described in the mouse event descriptions.
w
X
Y
Z
1132
MEMBER SUMMARY
Constructor MouseEventO Constructs a MouseEvent instance.
Coordinate Methods getPointO getXQ getYO translatePoi nt() Retrieves the mouse event's location. । Retrieves the mouse event s .r-coordinate. Retrieves the mouse event's v-coordinate. Translates the mouse event's coordinates.
Property Methods getCli ckCountO isPopupTriggerO i Retrieves the mouse event's click count. Retrieves the mouse event's popup trigger property.
Mouse Event Ids Constants
M0USE_ClICKED MOUSE-DRAGGED Event id indicating that a mouse button was pressed and released. ! Ел ent id indicating that the mouse moved while a mouse button was pressed.
MOUSE-ENTERED Event id indicating that the cursor entered a component's exposed bounds.
MOUSE.-FXI FFD Event id indicating that the cursor exited a component's exposed hounds.
MOUSE_FIRS7 MOU5E„.IAST MOUSE-MOVED Constant specifying the first id in the range of mouse event ids. । Constant specifying the last id in (he range of mouse event ids. Event id indicating that lhe mouse moved while in a component's exposed hounds.
MOUSE.PRESSED MOUSF_RELFASLD Event id indicating that a mouse button was pressed. Event id indicating that a mouse button was released.
Debugging Method paramStringO Generates a string representing the mouse event's state. 1 ' _ i
See Also
java.awt.AWTEvent, InputEvent, MouseAdapter, MouseListener,
MouseMotionAdapter, MouseMotionListener.
i
MouseEvent
java.awt.event
A
В
C
D
I:
F
Ci
H
Example This example demonstrates how to get mouse events from a component that fires them. The example creates a frame that lis- tens for mouse events on itself. In response to a mouse event, the specifics of the event are printed. When the frame fires a MOUSE_PRESSED event, an arrow is drawn at the coordinates of the event. Also drawn are the mouse coordinates, and the identities of the pressed mouse button and any modifier keys. 1 MouseEv Ж pl p -
^csb1 (5,23)
FIGURE: 290: MouseEvent.
Figure 290 shows that mouse button one (bl) was pressed at coordinate (5. 23). The Con-
trol and Shift modifier keys were down at the time the first mouse button was pressed. Notice
that the northwest comer of the frame’s drawable area is not (0, 0). This is because the frame
has nonzero insets and mouse coordinates are always relative to a component's bounds. See
Container for more information about insets.
import java.awt.4;
import java.awt.event;
class Main extends Frame implements MouseListener {
// The point where the mouse button was pressed.
Point curPoint;
// The current button.
String curButton;
Main О {
superC’MouseEvent Example’1);
addMouseListener(thi s);
setSize(150, 150);
showO;
// Paint an arrow and the coordinates.
public void paint(Graphics g) {
if (curPoint != null) {
FontMetrics fm = g.getFontMetrics();
Insets insets - getlnsetsO;
// Build the arrow.
Polygon arrow = new PolygonO;
arrow.addPoint(curPoint.x, curPoint.y);
arrow.addPoint(curPoint. x+9, curPoint.y+18);
arrow.addPoint(curPoint.x+18, curPoint.y+9);
g.fi11 Polygon(arrow);
g.drawStri ng(curButton+“(,’+curPoi nt. xf »4 tcurPoi nt. y+'’)”.
curPoint. x+12, curPoi nt.у + 14+fm.getAscentO) ;
}
public void mouseClicked(MouseEvent evt) {
pri nt (’’MOUSE-CLICKED’', evt);
}
1134
public void mouseEntered(MouseEvent evt) {
print("MOUSE—ENTERED", evt);
}
public void mouseExited(MouseEvent evt) {
print("MOUSE-EXITED", evt);
}
public void mousePressed(MouseEvent evt) {
curPoint ' evt .getPointO;
curButton = getCurButton(evt);
print C1MOUSE_PRESSFD", evt);
repaintO;
}
public void mouseReleased(MouseEvent evt) {
print("MOU5E-RELEASED", evt) ;
// Returns a string representing the mouse button that was pressed.
String getCurButton(MouseEvent evt) {
String result = "";
int m = evt .getModifiersO;
if ((m & InputEvent.CTRL^MASK) != 0) {
result "c”;
}
if ((m & InputEvent.SHIFT-MASK) != 0) {
result += "s";
}
if ((m & InputEvent.BUTT0N3_MASK) ’= 0) {
result += "b3";
} else if ((m & InputEvent.BUTT0N2 .MASK) !- 0) {
result += "b2";
} else if ((m & InputEvent,BUTTON 1_MASK) ’*= 0) {
result += "bl";
}
return result;
}
// Prints out the details of the mouse event.
void print(String eventName, MouseEvent evt) {
String[] modNames » {"alt", "ctl", "meta", "shift", "bl”, "b2", "b3"};
int[] modMasks == {InputEvent.ALT_MASK,
InputEvent.CTRL-MASK, InputEvent.META-MASK,
InputEvent.SHIFT-MASK, InputEvent.BUTT0N1..MASK,
InputEvent.BUTTON2J4ASK, InputEvent,BUTTON3-MASK};
int m = evt.getModifiersO;
System.out,print(eventName + ” (");
for (int i=0; i<modMasks.length; i++) {
if ((m & modMasks(11) != 0) {
System.out.print(modNames[i]+",’’) ;
}
}
System.out.print(") ");
System.out. printC" poi nt="+evt. getX() + " , "+evt .getYO) ;
System.out,print(" clickCount="+evt.getClickCountO) I
if (evt.isPopupTrigger()) {
System.out.printC' isPopupTrigger") ;
}
System.out.pri ntln();
}
MouseEvent
java.awt.event
getClickCountO
public static void main(String argsfl) {
new Main();
}
}
Л
в getClickCountO
c Pl RPOSE Retrieves the mouse event's click count.
D SYNTAX public int getClickCountO
E DESC RIPTION The click count indicates the number of quick, consecutive clicks of a mouse
F button. It is typically used to detect double* and triple-click gestures. For
example, a click count property value of 2 indicates a double-click.The click
G count is valid only for three mouse events: MOUSE-CLICKED, MOUSE-PRESSED,
H and MOUSE-RELEASED. For these, lhe click count is al least 1. For all other
I mouse events, the click count is 0.
J SEE: A I.SO MOUSE-CLICKED, MOUSE PRESSED, MOUSF_RFLEASED.
К EXAMPLE See the class example.
I.
getPointf)
N PURPOSE Retrieves the mouse event's location.
0 SYNTAX public Point getPointO
P DESCRIPTION The returned point is the location of the cursor relative to the source compo-
Q nent's bounds when the mouse button was pressed. See the class description
R for more details about mouse event coordinates.
S RETURNS A non-nul 1 point indicating the mouse event's location.
T EXAMPLE See the class example.
u
V getXQ
w PURPOSE Retrieves the mouse event's .t-coordinate.
X SYNIAX public int getXQ
Y DESC RIPTION For more details about the mouse coordinates, see the class description.
Z RETTRNS The mouse event's л-coordinate.
EXAMPLE See the class example.
1136
JU» Ц.ЦО l.L t Llll gel
getYO
purpose Retrieves the mouse event's v-coordinate.
SYNTAX public int getY()
description For more details about the mouse coordinates, see the class description.
RETl’RNS The mouse event’s v-coordinate.
example See the class example.
isPopupTYiggerO
PURPOSE Retrieves the mouse event's popup trigger properly.
SYNTAX public boolean isPopupfriggerО
DESCRIPTION If the popup menu trigger property for a mouse event is true, it indicates that the user made a mousing gesture to show a popup menu. The popup menu trig- ger property can be true only for MODSEXPRESSED and MOUSE_RELEASED mouse events. See the class description for more details about the popup menu trigger. Sec PopupMenu for information about showing popup menus.
RETURNS true if the event was a popup menu trigger; fal se otherwise.
see: also MOUSE_PRESSED, MOUSE-RELEASED, java.awt.PopupMenu.
EXAMPLE See the java.awt.PopupMenu class example.
MOUSE-CLICKED
PURPOSE Event id indicating that a mouse button was pressed and released.
SYNTAX public static final int MOUSE-CLICKED
DESCRIPTION A mouse event with this id (value 500) is Tired following a MOUSE-PRESSED/ MOUSE-RELEASED event pair in which the mouse coordinates of both events are the same (or very close together). This event is most often used to listen for multiclicking mouse gestures. See getClickCountО for more details. The click count is always 1 or greater.
SEE ALSO MOUSE-.PRESSED, MOUSl _REL EASED.
EXAMPLE See the class example.
java.awt.event
MouseEvent
MOUSE-DRAGGED
MOUSE DRAGGED
A PI’RPOSE. SY VI.AX description; Event id indicating that the mouse moved while a mouse button was pressed, public static final int MOUSE-DRAGGED A mouse event with this id (value 506) is fired when the mouse is moved while
ET C D E. E ( li 1 SEE AE.SO a mouse button is down. A component fires this event onh if the mouse button was pressed while the cursor was inside the component. So. for example, if the mouse button was pressed outside the component and dragged into the compo- nent. the component will not fire a MOUSE_DRAGGED event. Unlike with the MOUSE-MOVED event, a component continues to fire this event until the mouse button is released, regardless of where the cursor is located. This means that the mouse coordinates mas be outside the source component's bounds. This event is most often used for drag-and-drop operations. The click count is always 0. and the popup menu trigger is always fal se. MOUSE.MOVED.
.1 К EXAMPLE See the class example.
M
MOUSE-ENTERED
pi reuse Event id indicating that the cursor entered a component's exposed bounds.
s\max public static final int MOUSE-ENTERED
descripiion A mouse event with this id (value 504) is fired whenever the cursor moves
from a point not on the source component's exposed hounds to a point that is
Q on the component's exposed hounds. One exception to this rule is when a
R popup menu is showing.
MOUSE_FNTERED and MOUSE-EXITED events are alwavs fired in pairs.
MOUSE-ENTERED being first. Therefore a component will never fire two
T MOUSE-ENTERED or two MOUSE-EXITED events in a row.
U The event's coordinates is the point where the system first detected that the
v cursor was on the source component’s exposed bounds. Therefore the close-
ness of the coordinates to the component's edge depends on how fast the cur-
w sor entered the bounds.
X The click count is always 0.
Y SEEALSO MOUSE. EXITED.
EXAMPLE.
See the class example.
1138
MOUSE EXITED
MOUSE-EXITED
PURPOSE Event id indicating that the cursor exited a component's exposed bounds.
SY VI AX public static final int MOUSE-EXIT!D
DESCRIPTION A mouse event with this id (value 505) is fired when the cursor is no longer on the source component's exposed bounds. One exception to this rule is when a popup menu is showing. MOUSE-ENTERED and MOUSE—EXITED events are always fired in pairs, MOUSE-ENTERED being first. Therefore a component will never fire two MOUSE-ENTERED or two MOUSE-EXITED events in a row. The event's coordinates is the point where the system first detected that the cursor was no longer on the source component's exposed bounds. Therefore the closeness of the coordinates to the component's bounds depends on how fast the cursor left the bounds. The click count is always 0.
SEEALSO MOUSE-ENTERED.
EXAMPLE See the class example.
MOUSE FIRST
PURPOSE Constant specifying the first id in the range of mouse event ids.
SYNTAX public static final int MOUSF.FIRST
DESCRIPTION All item event ids must be greater than or equal to MOUSE-FIRST (value 500).
SEI: ALSO MOUSE-LAST.
EXAMPLE See java.awt.Component. processEventO.
MOLSE LAST
PURPOSE Constant specifying the last id in the range of mouse event ids.
SYNTAX public static final int MOUSE LAST
DESCRIPT ION All item event ids must be less than or equal to MOUSE-LAST (value 506).
SEE ALSO MOUSE. FTRSI.
LX AM PI E See java.awt.Component.processEventO.
MouseEvent
java. awt.event
MOUSE MOVED
MOUSE-MOVED
РГ RPOSE Event id indicating that the mouse moved while in a component’s exposed hounds.
A SV N'l AX public static final int MOUSE MOVED
В DESCRIPTION A mouse event with this id (value 503) is tired every time the mouse moves to
C D a new point on lhe source component's exposed bounds. Note that mouse events may not be fired while the cursor is in the insets area of the component. This behavior is platform-dependent.
F The click count is always 0.
F SFF ALSO MOUSE DRAGGED.
G H LX AMPLE See the class example.
I J К MOUSE, PRESSED
PC RPC )SL [A ent id indicating that a mouse button was pressed.
1, SYNTAX public static final int MOUSE_PRESSED
DESCRIPTION /X mouse event with this id (value 501) is fired when a mouse button is pressed. The AWT system guarantees that a MOUSE_RELEASED event will be
N fired for each MOUSE-PRESSED event fired, even if the mouse was released out-
О side the component.
P The event's modifiers contain the state of the modifier keys at the time the mouse button was pressed. The modifier keys can be used to identify which
0 mouse button was pressed. However, just testing the state of the modifier keys
R does not work in the case in which more than one button is down at time. See
s the class description for more details.
T The click count is always 1 or greater.
1 L: SFE ALSO MOUSE.Cl ICKED, MOUSE-RELEASED.
V w EXAMPLE See lhe class example.
X MOUSE. RELEASED _
Y PCRPOSI. Event id indicating that a mouse button was released.
Z SYMAX public static final int MOUSE .RELEASED
1140
MouseEventf)
description A mouse event with this id (value 502) is fired when a mouse button is released. The AWT system guarantees that a MOUSE-RELEASED event will be fired for each MOUSE-PRESSED event fired, even if the mouse was released out- side the component. The event’s modifiers contains the state of the modifier keys at the lime the mouse button was released. However, the state of the modifiers keys cannot reliably be used to determine which mouse button was released. For example, the Meta modifier key may or may not be set when the user releases Button3; whether it is depends on if the user is holding down the Meta key. See the class description for more details about the modifier keys. The click count is always the same as that for the most recent MOUSE-PRESSED event. The click count is always 1 or greater.
SEE ALSO MOUSE-CLICKED, MOUSE-PRESSED.
EXAMPLE See the class example.
MouseEventO
PURPOSE Constructs a MouseEvent instance.
SYNTAX public MouseEvent(Component source, int id, long when, int modifiers,int x, int y, int clickCount, boolean popupTrigger)
DESCRIPTION This constructor creates a mouse event with source as the component that fires this event. See the class description for more information on click counts, modifier keys, and popup triggers. After the mouse event is created, the source object can distribute the event to its listeners by calling the mouse event-related methods in AWTEventMulti- caster. If the event was not created by source, the creator can deliver the event to the source component either by posting the event to the event queue (see EventQueue. post Event О) or by calling the source component's Com- ponent .di spatchEventO method directly.
PARAMETERS clickCount id modifiers The non-negative click count of this event. One of the mouse event ids. The current state of the modifier keys.
popupTriggertrue if this event should cause a popup menu to appear.
source when X The non-null component that is firing this mouse event. The timestamp for this event. See System.currentTimeMi11is(). The event's x-coordinate relative to the source’s bounds.
11c
MouseEvent
java.awt.event
paramStringO
у The event’s y-coordinate relative to the source’s bounds.
seealso getClickCountO, getPointO, getXO, getYO,
InputEvent.getModifiersО, InputEvent.getWhenО,
isPopupTriggerO , java.awt. AWTEvent .getIDO >
A java.awt.Component.di spatchEventO,
java.lang.System.currentTimeMi11s(),
В java.util. EventObject .getSourceO.
D paramStringO
E purpose: Generates a string representing the mouse event’s state.
F SYNTAX public String paramStringO
G DESCRIPTION The returned string contains the name of the mouse event, its coordinate, the
H key modifiers, and the click count. A subclass of this class should override this
J method and return a concatenation of its state with the results of
J super. paramStringO. This method is called by the AWTEvent. toStri ngO method and is typically used for debugging.
К RETURNS A non-null string representing the mouse event’s state.
L OVERRIDES java.awt. AWTEvent.paramStri ng().
SEE ALSO java.awt.AWTEvent.toStringО, java.lang.Object.toStringO.
N EXAMPLE See the java.awt.AWTEvent class example.
о
translatePointO
Q ----------------------
_ PURPOSE к SYNTAX 0 DESCRIPTION Translates the mouse event’s coordinates. public synchronized void translatePoint(int x, int y) This method modifies the coordinates in the mouse event. In particular, x is added to the event’s x-coordinate and у is added to the event’s y-coordinate.
U For more details about mouse coordinates, see the class description.
V PARAMETERS w x x y EXAMPLE V An integer value that is added to the event's x-coordinate. An integer value that is added to the event's y-coordinate. See the MouseMotionListener class example.
1142
j Cl V Cl. cl VV I . v vein
MouseListener
Syntax
public interface MouseListener extends EventListener
Description
When an object (listener) wishes to receive mouse events from a component (rhe source com-
ponent), two things must be done:
1. The listener must implement the MouseLi stener interface and all of the methods it
requires.
2. The listener must be registered with the source component by making a call to the source
component's addMouseli stenerQ method
For information about mouse events, see MouseEvent.
ltd
MouseListcner
java.awt.event
MEMBER SUMMARY
Mouse Event Callback Methods
mouseCI ickedO mouseT ntered() Called when a mouse button i* pressed and released. ('ailed when lhe cursor enter* the source component's exposed bounds
mouse!xi ted() Called when the cursor exits the souicc component** exposed bounds.
mousePressed() I Called when lhe user presses a mouse button in the souice com ponenl.
mouseReleasedO i ('ailed when the user telcase* a mou*e button in the source component.
Sec Also
java.awt.Component.addMouseListenerO, java.uti1.Fvent! istener,
vouseAdapter, vouseEvent, MouseMotionLi stener.
Example
This example implements a lightweight component button. The
button is arrow-shaped with transparent pixels around the
arrow. It overrides the contai ns О method, *o lhe transparent
pixels are also transparent to mouse events.
Since the arrow button fires action events, it needs to pro
vide the listener methods that arc necessarv to support action
event listeners.
.Vo/r: In Java 1.1.2. clicking an arrow button turns it blue.
Dragging outside of the button** outline should return it to red.
However, the but ton doesn't return io red until the cursor is
dragged outside of the whole window.
import java.awt.*;
import java.awt.event. • •;
public class Main extends rrarre i
MainO {
super("MouseListener Example");
(nmponent < ;
set Bat kqround(Color.ye 1 low);
/ Iayout components.
GridBagLayout gbl new GridBagiayout();
set 1ayou t(gbl);
add(c - new ArrowButton(ArrowButton.NORTH)):
I 1(Л RE 291: \rrow Buttons.
1144
setConstraints(gbl, c, 1, 0);
add(c = new ArrowButton(ArrowButton.WFST));
setConstraints(gbl, c, 0, 1);
add(c = new ArrowButton(ArrowButton.SOUTH));
setConstraintsfgbl, c, 1, 2);
add(c = new ArrowButton(ArrowButton.FAST));
setConstraints(gbl, c, 2, 1);
pack();
show();
// Setup the gridbag constraints for a component.
void setConstraints(GridBagLayout gbl, Component comp, int x, ini
GridBagConstraints cbc - new GridBagConstraintsC);
cbc.gridx =. x;
cbc.gridy = y;
cbc.insets = new Inset$(2, 2, 2, 2);
gbl.setConstraints(comp, cbc);
}
public static void main(String args[2) {
new Mai n();
}
}
class ArrowButton extends Component implements MouseListener {
static fi nal i nt NORTH = 0
static final i nt WFST 1;
stati c f i nal int SOUTH = 2
static fi nal int EAST - 3;
// ne, nw, sw r, se к
int[][] corners = {{1, 0}, {0, 0}, {0, 1}, {1, 1}};
double[]F] tips = {{.5, 0], {0, .5}. {.5, 1}, {1, .5}};
int width 30;
int height =- 30;
// The orientation of the button. This value
// is included in the action events this button fires,
int orient;
// If true and down is not true, the button should appear red.
boolean highlight;
// If true and highlight is true, the button should appear blue,
boolean down;
Polygon shape new PolygonO;
ArrowButton(int o) {
orient - o;
// Prepare shape,
int ol - (O4-l)%corners . length;
int o2 = (o+2)%corners.1ength;
int o3 =- (o+3)%corners.length;
int w - width-1;
int h = height-1;
MouseListener
java.awt.event
shape.addPoint((int) (tips[oj [01*w) , (int)(tipsfo] ;
shape.addPoi nt(corners[o2][0]*w, corners[o21[1j *h);
shape.addPoint(cornersГоЗ][0]"w. corners[o3][1]*h);
Л
В
c
D
E
F
Ci
H
I
// Listen for events.
addVouseLi stener(thi s);
}
public void paint(Graphics g) {
if (highlight) {
if (down) {
g.setColor(Col or.blue);
} else {
g.setColor(Color.red);
}
} else {
g.setColor(Col or.white);
}
g. fi 11 Pol ygon(shape);
g.setColоr(Color.black);
g.drawPolygon(shape);
}
J
К
I-
\1
N
<)
P
Q
R
S
T
u
V
w
X
Y
// Mouse event handlers
public void mousedicked(MouseEvent evt) {
// do nothing
}
public void mousePressed(MouseEvent evt) {
down - true;
repai nt();
}
public void mouseReleased(MouseEvent evt) {
if (down) {
// Fire an action event.
processActionEvent(
new ActionEvent(this, ActionEvent.ACTION PERFORM!
""♦orient)) ;
}
down - false;
repai nt();
}
public void mouseEntered(MouseEvent evt) {
highlight - true;
repai nt();
}
public void mouseExited(MouseEvent evt) {
highlight - false;
repaintO ;
}
// Returns true if the coordinate is inside the arrow.
public boolean contains(int x, int y) {
return shape.contains(x, y);
}
Z public Dimension getMinimumSize() {
return new Dimension(width, height);
}
public Dimension getPreferredSizeO {
1146
mouseClicked(
return new Dimension(width, height);
}
// Methods to support listeners of the action event.
transient ActionListener actionListener;
public synchronized void addActionlistener(ActionListener 1) {
actionListener = AWTEventMu1ticaster.add(actionListener, 1);
}
public synchronized void removeActionListener(Actionlistener 1) {
action!istener = AWTtventMulticaster.remove(actionListener, 1);
}
protected void processActionFvent(ActionEvent evt) {
if (actionListener !- null) {
actionli stener.act i onPerformed(evt);
}
}
}
mouseClickedf)
PURPOSE Called when a mouse button is pressed and released.
SYNTAX public void mousedicked(MouseFvent evt)
DESCRIP1 ION This method is called after the mousePressedO and mouseReleased() methods are called and the mouse coordinates of both events are the same (or very close together). See MouseEvent .MOUSE-CLICKED for more details about mouse clicked events.
PARAMETERS evt l he non-null mouse event.
EXAMPLE See the class example.
PURPOSE Called when the cursor enters the source component’s exposed bounds.
SYNTAX public void mouseEntered(MouseEvent evt)
DESCRIPTION This method is called whenever the cursor moves from a point not on the source component’s exposed bounds to a point that is on the component’s exposed bounds. See MouseEvent.MOUSE-ENTERED for more details about mouse entered events.
PARAMET ERS evt The non-null mouse event.
EXAMPLE See the class example.
и.
java.awt.event
Mouse Listen er
mouse ExiledO
mouscExited()
Pl RPOSE SYNTAX Called when the cursor exits the source component's exposed bounds, public void mouseExitedfMouseEvent evt)
A DESCRIPTION This method is called when the cursor is no longer on the source component's
В exposed bounds. See MouseEvent.MOUSE-EXITED for derails about mouse
C exited events.
D PARAMEIERS
i; evt The non-null mouse event.
l X F G EXAMPLE See the class example.
H mousePressedO
1 PL RPOSE Called when the user presses a mouse button in the source component.
J SYMAX public void mousePressed(MouseEvent evt)
К DESCRIPTION' This method is called when a mouse button is pressed. See Mouse-
L Event .MOUSE-PRESSED for more details about mouse pressed events.
parameters
N evt The non-null mouse event.
0 EXAMPLE See the class example.
I’ Q mouseReleasedO
R Pl RPOSE Called when the user releases a mouse button in the source component.
S SYMAX public void mouseReleased(MouseFvent evt)
T DESCRIPTION This method is called when a mouse button is released. See Mouse-
L Event . MOUSE-RELEASED for more details about mouse released events.
V PARAMETERS
w evt The non-nul 1 mouse event.
X EXAMPLE See the class example.
Y
Z
1148
java.awt.event
MouseMotionAdapter
Syntax
public abstract class MouseMotionAdapter implements MouseMotionListener
Description
The mouse motion adapter is a mouse motion listener in which all callback methods are empty
implementations. The purpose of the mouse motion adapter is to make it more convenient for
an object to listen for mouse motion events. In particular, by using the mouse motion adapter,
you can implement only those callback methods in which you are interested. Without the
mouse motion adapter, you must implement all callback methods, even if the method is empty.
To use a mouse motion adapter, you create a subclass of MouseMotionAdapter and over-
ride the desired callback methods. You then create an instance of the mouse motion adapter
subclass and call the component's addMouseMotionLi stenerQ method with it. The mouse
motion adapter subclass is typically an inner class.
MEMBER SUMMARY j
Mouse Motion Event Callback Methods
mouseDragged() Called when the user drags the mouse on the source component.
mouseMovedQ Called when the user moves the mouse over the source component.
See Also
java.awt.Component.addMouseMotionListenerQ, MouseEvent,
MouseMotionLi stener.
Example
This example implements a simple “stamping" program. The user can select an image (called
the stamp) from a palette of images and then copy it anywhere on the stamp canvas. See Figure
292.
When the stamp canvas receives a mouse motion event, it displays the current stamp at
mouse coordinates. When it receives a mouse pressed event, it records the stamp at the current
location. When it receives a mouse exit event, it hides the stamp.
MouseMotion Adapter
java.awt.event
A
В
(.'
I)
I
Г
(i
H
I
J
К
L
N
()
P
Q
R
s
T
IJ
V
w
X
Y
Z.
The stamps are simple components
that paint the stamp image. Thev are dis-
played in a flow layout. The frame listens
for mouse pressed events from the stamp
components and uses them to get lhe
stamp in the stamp canvas.
The stamp canvas uses an off-screen
image (bbuf) lo implement double-buff-
ering in order lo eliminate flickering. I'hc
off-screen image is first cleared and then
all of the slumps are painted at their cur-
rent locations. The complete off-screen
image is then painted on the screen.
Possible additions to this program
would be to highlight the current stamp
and to allow the user to delete and move
around painted stamps.
< MouseMotionListener Example BEE3
HGCRE 292: A Stamping Program.
M
import java.awt.
import java.awt.event.*;
import java.util.*;
public class Main extends Frame {
StampCanvas StampCanvas = new StampCanvasО;
Button startButton = new Button(“Start”);
Panel palette = new Panel(new FlowLayout());
Main() {
super(“MouseMotionAdapter l-xample”);
// Initialize palette with stamps.
Stamp s;
palette.add(s = new Stamp(getToolkit().getlmage(“duke.gif”)));
s.addMouseListener(new MouseEventHandl er());
palette.add(s = new Stamp(getToolkit().getlmage(“bird.gif”)));
s.addMouseli stener(new MouseEventHandler());
palette.add(s = new Stamp(getToolkit().getlmage(“house.gif”)));
s.addMouseLi stener(new MouseEventHandler());
// Layout components
add(palette, BorderLayout.SOUTH);
add(StampCanvas, BorderLayout.CENTER);
setSize(300, 300);
show();
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
Stamp stamp = (Stamp)evt.getSourceO;
StampCanvas.setStamp(stamp.i mage);
}
1150
}
public static void main(String args[]) {
new Mai n();
}
}
class Stamp extends Component {
int width, height;
Image image;
Stamp(Image image) {
MediaTracker tracker = new MediaTracker(this);
this.image « image;
try {
tracker.addlmage(image, 0);
tracker.waitForAl1();
} catch (Exception e) {
e. pri ntStackTraceO 5
}
width = image.getWidth(null);
height = image.getHeight(nul1);
}
public void paint(Graphics g) {
g.drawlmage(i mage,
(getSizeO .width-width)/?, (getSizeO .height-height)/2, thi
public Dimension getPreferredSizeO {
return new Dimension(width, height);
}
class StampCanvas extends Canvas {
// Vector of all stamped images.
Vector stamps = new VectorO;
// Vector of all locations of the stamped images.
Vector stampPts = new VectorO;
// The current stamp. If null, no stamp is set.
Image curStamp;
// The current location of the stamp’s origin.
// If null, don’t display the stamp.
Point curPoint;
// Double buffer variables
Image bbuf;
Graphics bbufG;
StampCanvas() {
// Listen for events.
addMouseListener(new MouseEventHandler());
addMouseMotionListener(new MouseMotionEventHandler());
}
void setStamp(Image stamp) {
MouseMotionAdapter
java.awt.event
curStamp = stamp;
}
A
В
c
D
E
E
G
H
1
J
К
L
M
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
int width - getSizeO .width;
int height = getSizeO .height;
// Create the double buffer if necessary.
// Also make it bigger if necessary,
if (bbuf === null
:| bbuf.getWidth(null) < width
II bbuf.getHeight(nul1) < height) {
bbuf = createlmage(width, height);
if (bbufG 1- null) {
bbufG.di sposeO;
}
bbufG = bbuf .getGraphicsO ;
}
// Clear the background.
bbufG.setColor(Color.lightGray);
bbufG.fi11Rect(0, 0, width, height);
// Paint all the stamps.
for (int i=0; i<stamps.size(); i++) {
Image stamp - (Image)stamps.elementAt(i);
Point pt (Point)stampPts.elementAt(i);
N
О
P
Q
bbufG.drawlmage(stamp, pt.x, pt.y, this);
}
// Paint the current stamp.
if (curStamp 1= null && curPoint null) {
bbufG.drawImage(curStamp, curPoint.x, curPoint.y, this'
}
// Draw the off-screen image to the display,
g.drawlmage(bbuf, 0, 0, this);
T // Handler for mouse move events.
class MouseMotionEventHandler extends MouseMotionAdapter {
U public void mouseMoved(Mouse£vent evt) {
if (curStamp ’ = null) {
V int x = evt.getXO-curStamp.getWidth(null)/2;
int у = evt.getYO-curStamp.qetHeight(nul 1 )/2;
W
// Keep the image with the bounds of the canvas.
X x = Math.max(0, Math.min(
x, getSizeOwidth-curStamp.getWidth(nul1)));
Y У = Math.max(0, Math.min(
у, getSizeO - height-curStamp.getHeight(nul 1))) ;
Z
curPoint new Point(x, y) ;
repaint();
}
1152
mouseDraggedO
// Handler for mouse pressed and exit events.
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
// Save the stamp.
if (curStamp !- null) {
stamps.addElement(curStamp);
stampPts.addElement(new Point(curPoint.x, curPoint.y));
repaintO;
}
}
public void mouseExited(MouseEvent evt) {
curPoi nt = null;
repaintO ;
}
}
}
mouseDraggedO
PURPOSE Called when the user drags the mouse on the source component.
SYNTAX public void mouseDragged(MouseEvent evt)
DESCRIPTION This method, by default, has an empty implementation. It should be overridden to handle MouseEvent. MOUSE-DRAGGED events. See the Mouse- Event .MOUSE-DRAGGED event for details.
PARAMETERS evt The non-null mouse motion event.
EXAMPLE See the MouseMotionListener class example.
mouseMovedf)
PURPOSE Called when the user moves the mouse over the source component.
SYNTAX public void mouseMoved(MouseEvent evt)
description This method, by default, has an empty implementation. It should be overridden to handle MouseEvent .MOUSE-MOVED events. See the Mouse Event.MOUSEJMOVED event for details.
PAR AM HERS evt The non-null mouse motion event.
EXAMPL .E See lhe class example.
1152
java.awt.event
MouseMotionListener
A
В
C
D
E
E
G
H
J
J
К
L
M
N
О
P
Q
R
S
I
L
V
W
X
Y
L
Syntax
public interface MouseMotionListener extends EventListener
Description
When an object (listener) wishes to receive mouse motion events from a component (the
source component), two things must be done:
1. The listener must implement the MouseMotionLi stener interface and all of lhe methods
it requires.
2. The listener must be registered with the source component. It becomes registered by mak-
ing a call to the source component's addMouseMotionLi stener() method.
For information about mouse motion events, see MouseEvent.
MEMBER SUMMARY
Mouse Motion Event Callback Methods
mouseDraggedO Called w hen the user drags the mouse on lhe source component.
mouseMovedO Called when the user moves the mouse over the source component.
1154
See Also
java.awt.Container.getlnsetsO, java.util.EventListener, MouseEvent,
MouseMoti onAdapter.
Example
This example demonstrates how to use mouse
motion events to drag a square around a frame s
inset area. The frame's insets are used to con-
strain the square so that it cannot be outside the
frame’s inset area. See Figure 293.
Notice the addNotifyO call. This is done
to create the peers so that the getlnsetsO call
will return valid results. See Container,get -
Insets О for more details.
The example also changes the cursor when
the cursor is over the box.
* MouseMohonListener Ex...
HGVRE 293: MouseMotionListener,
import java.awt.-;
import java.awt.event.*;
class Main extends Frame implements MouseMotionListener {
Rectangle box - new Rectangle(0, 0, 30, 30);
int curCursor = DEFAULT_CURSOR;
Main() {
super("MouseMotionl1stener Example");
addMouseLi stener(new MouseEventHandlerO);
addMouseMotiont istener(thi s);
setSize(200, 200);
addNotifyO ;
box.x - getlnsetsO. 1 eft;
box.у = getlnsetsO .top;
showO;
}
public void paint(Graphics g) {
g.setColor(tolor.red);
g.fillRect(box.x, box.y, box.width, box.height);
}
public void mouseDragged(MouseEvent evt) {
if (downPt 1 = null) {
Insets insets = getlnsetsO;
// Keep the box inside the frame inset area.
box.x - Math,max(insets.left, Math .mi n(evt .getXO-downPt. x,
getSi 7e().width-box.width-i nsets.right));
box.y - Math.max(insets.top, Math.min(evt.getY()-downPt.у,
getSi zeО.height-box.height-i nsets.bottom));
repai nt();
}
1155
java.awt.evem
Mouse Motion Listener
mouseDraggedO
}
public void mouseMOved(MouseEvent evt) {
int oldCursor =* curCursor;
if (box.contains(evt.getX() , evt.getYO)) {
A curCursor ~ Cursor.HAND .CURSOR;
} else {
R curCursor ~ Cursor.DFFAUlT-CURSOR;
}
C if (oldCursor '= curCursor) {
setCursor(Cursor.getPredefinedCursor(curCursor));
D }
}
E
// Point where the mouse button was pressed relative to the box's origin,
F Point downPt;
class MouseEventHandler extends MouseAdapter {
G public void mousePressed(MouseEvent evt) {
if (curCursor -= Cursor,HAND. CURSOR) {
H evt.translatePoint(-box.x, -box.y);
downPt = evt. getPoi nt() ;
I }
}
J public void mouseReleasedC^ouseEvent evt) {
downPt = null;
К }
}
L
м public static void main(String argsL) {
wM new Mai n() ;
“ }
N }
О
P
Q mouseDraggedf)
R purpose Called when the user drags the mouse on the source component.
S T syntax public void mouseDragged(MouseF.vent evt) description This method is called when the mouse is moved while a mouse button is held
down. See MouseEvent .MOUSF_DRAGCED for more details about mouse
u V dragged events. PARAMETERS
w evt The non null mouse motion event.
X example See the class example.
Y
Z
1156
mouse MovedQ
mouseMovedO
PURPOSE Called when the user moves the mouse over the source component.
SYNTAX public void mouseMovedfMouseEvent evt)
descrifi ION This method is called every time the mouse moves to a new point on the source component's exposed bounds. See MouseEvent.MOUSE_MOVED for details about mouse moved events.
parameters evt The non-null mouse motion event.
EXAMPLE See the class example.
1157
java. awt. event
Pai ntE vent
A
В
C
D
E
F
(j
H
I
j Syntax
public class PaintEvent extends ComponentEvent
К
L Description
M This class is used internally by the AWT system to manage the updating of component display
areas. The AWT system does not provide any listener methods for paint events. Consequently,
this class does not have any examples.
О The event is fired by peer components and translated by a component into Compo-
nent. pai nt () and Component. updateQ method calls. See Component for more details.
Q The Update Area
К The update area is an area on the source component that needs to repainted. For example» if г
component is partially occluded by a window and the window is removed» lhe components
S update area is the newly revealed area.
I
L
V
w
x
Y
Z
MEMBER f e HI
Constructor Pai ntEvent () Constructs a Pai ntEvent instance.
Update Rectangle Methods
getUpdateRectO Retrieves the paint event's update area.
setUpdateRectO Sets the paint event's update area.
1158
getUpdateRecU)
Paint Event Id Constants
PAINT
PAINT_FIRST
PAINT^LAST
UPDATE
Debugging Method
paramStringO
Event id indicating that the update area has been filled and needs to
be repainted.
Constant specifying the first id in the range of paint event ids.
Constant specifying the last id in the range of paint event ids.
Event id indicating that the update area needs to be repainted.
Generates a string representing the paint event's state.
See Also
j ava.awt.Component.pai nt О, j ava.awt.Component.update().
getUpdateRectf)
purpose: Retrieves the paint event's update area.
SYNTAX public Rectangle getUpdateRectO
DESCRIH ION This method retrieves the rectangle representing the area that needs to be repainted in response to this event.
PAINT
PURPOSE Event id indicating that the update area has been filled and needs to be repainted.
SYNTAX public static final int PAINT
description A paint event with this id (value 800) is fired when an area of the source com- ponent needs to be repainted. A PAINT event differs from an UPDATE event in that for a PAINT event, the AWT system automatically fills the update area with the background color, whereas it does not for an UPDATE event.
SEEALSO UPDATE.
PaintEvent PAINT FIRST jaxa.awt.event
PAINT_FIRST
14 RPOSE Constant specifying the first id in the range of paint event ids.
syntax public static final int PAINT_TIRST
DESCRIPTION All paint event ids must be greater than or equal to PAINT_FIRST (value 800).
SEE ALSO PAINT LAST.
EXAMPI Г- See java.awt .Component.processFvent().
PAINT LAST
PCRPOSI. Constant specifying the last id in the range of paint event ids.
SVNTAX public static final int PA1NTJ AST
DESCRIPTION All paint event ids must be less than or equal to PAINT„LAST (value 801).
SLL Al SO PAINT_f 1RST.
EXAMPLL See java.awt.Component .processEvent().
PaintEventO
PERPOSE Constructs a PaintEvent instance.
SYNTAX public PaintEvent(Component source, int id, Rectangle updateRect)
DESCRIPTION This constructor creates a paint exent with source as the component that fires this event. Paint events are normally fired by the AWT system to notify com- ponents of areas that need to be repainted. You should not need to deal with paint events directly. To handle repaints, see Component .paint() and Com- ponent .update().
PARAMETERS source id updateRect The non-null component that is firing this paint event. One of the paint event ids. The non-null update area.
SLL AL SO getUpdateRectf), java.awt.AWTEvent.getID(), java.util.Eventobject. getSourceO.
1160
paramStringO
PURPOSE: Generates a string representing the paint event's state.
SYNTAX public String paramStringO
description The returned string contains the name of (he paint event and the bounds of lhe update area. /X subclass of this class should override this method and return a concatenation of its state with the results of super.paramStringO. This method is called by the AWTEvent. toStri ng О method and is typically used for debugging.
RETURNS A non-null siring representing the paint event's state.
OVERRIDES java.awt .AWT Event. paramStringO.
SEE AbO java.awt.AWTEvent.toStri ng О, java.lang.Object.toString().
EXAMPLE: See the java.awt.AWTEvent class example.
setUpdate Rect()
PURPOSE Sets the paint event's update area.
SYNTAX public void setUpdateRect(Rectangle updateRect)
PARAMETERS updateRect The non-null rectangle update area.
SEEALSO getUpdateRectQ-
UPDATE
purpose: Event id indicating that the update area needs to be repainted.
SYNTAX public static final int UPDATE
description A paint event with this id (value 801) is fired when an area of the source com- ponent needs to be repainted. A PAINT event differs from an UPDATE event in that for a PAINT event, the AWT system automatically fills the update area with the background color, whereas it does not for an UPDATE event.
SEE: ALSO PAINT.
116]
java.awt
Panel
A
В
C
I)
E
E
G
н Syntax
। public class Panel extends Container
Description
A panel is a component and a component container. Since a panel is itself a component, panels
can he freely nested. Panels are typically used in the layout of components in a user interface.
For example, suppose a user interface has two columns of buttons: one on the left and one on
(he right. In between the two columns is a display area that expands as the user expands the
window. This layout would be implemented with three panels: a border layout panel (see Bor-
der! ayout) with two nested grid layout panels (see GridLayout).
A panel has no border or title: hence, its insets are always (0. 0. 0. 0). See the Container
class for more information about insets and layout managers.
Events
The panel fires the same events as a component. See the Component class for detaiF.
Panels and Lightweight Containers
With the introduction of lightweight components and containers (see Component), there is
really no need to subclass the panel container. In fact, since a panel has a native peer and a
lightweight container does not, it is much more efficient to use a lightweight container. If you
are presently using a panel, you should consider changing it to a lightweight containei.
In theory, changing your class from a panel to a lightweight container simply involves
changing the extends from Panel to Container. However, there are a few problems with the
current release that forces you to make a few more modifications before your class will work
exactly the same. For details, see the Contai ner class description on lightweights.
1162
MEMBER SUMMARY
Constructor
Panel О Constructs a new Panel instance.
Peer Method
addNoti fy() Creates this panel's peer hierarchy
Example
This example creates tour panels: "one."
“two.” "three/' and "four/' These four panels
are in turn embedded in another panel with a
card layout manager. Each panel contains
from one to four labels. Four buttons arc pro-
vided on the left side of the frame to control
which of the four panels arc displaced. See
Figure 294.
import java.awt.-;
import java.awt.event.";
Panel Example
one
two
three
four
one two three
I КЛ RI. 294: Panel.
33
class Vain extends Frame implements ActionListener {
CardLayout cardLayout = new CardLayout();
Panel cardPanel = new Panel(cardLayout):
String^] names = {"one", “two", "three’’, "four"};
Main/) {
super("Panel Example";;
Panel p = new Panel(new GridLayout(0, 1);:
Button b;
/7 Put column of buttons on the left
for (int i=0; i <nair.es . 1 engtn ; i+ + ; {
p.addCb = new Button(names[ij)) ;
b.addActionLi stener(this);
}
addLp. BorderLayout.wEST);
// Place card panel in center
for (int i=0; i<names.1ength; i-+) {
addPaneifcardPanel, i-1);
add ГcardPanel, BorderLaуout.GENTER;;
setSizeOOO, 150;;
showf;;
}
// Creates a panel with ‘count' labels
void addPane I (Panel parent, int count; {
Panel p - new PanelQ;
Panel
addNotifyt)
ja\a.awt
A
В
c
D
E
F
G
H
1
J
К
L
M
N
О
Label 1;
for (int i=0; i<count; i++) {
1 « new Label(names[i1, 1abel.CENTER)•
1 .setBackground(Col or.yellow);
p.add(l);
J
parent.add(names[count-L], p);
}
// Action handler for buttons
public void actionPerformed(ActionEvent evt) {
cardl ayout. show( card Panel , evt. getActionCommandO) ;
}
static public void main(String[1 args) {
new Main();
}
}
addNotify()
purpose Creates this panel’s peer hierarchy.
syntax public void addNotifyO
description This method creates this panel's peer hierarchy, it necessary. The panel's peer
is created by calling the Toolkit.createPanel() method. This method
should never be called directly. It is normally called by the panel's parent.
OVERRIDES Contai ner.addNoti fy().
SEE ALSO Component, Toolkit.
EXAMPLE. See Component. setVi si bleQ
Q
R
S
T
и
v
w
x
Y
Z
Panel()
purpose Constructs a new Panel instance.
syntax pub 1i c Panel()
public Panel(IayoutManager layout)
description This constructor creates a new visible Panel instance using the specified lay-
out manager layout. If layout is not specified, the default layout manager is
FlowLayout. All panels created with no layout share this same FlowLayout
instance.
PARAMEIERS
1 ayout The possibly nul 1 layout manager to use for the new ly created panel.
example See the class example.
1164
--Jd I d.cl ц 1.1
PanelPeer
” Panel Pee*
Syntax
public interface PanelPeer extends ContainerPeer
Description
The panel component (see the Panel class) in the AWT uses the platform’s native implemen-
tation of a panel. So that the AWT panel behaves the same on all platforms, the panel is
assigned a peen whose task is to translate the behavior of the platform s native panel to the
behavior of the AWT panel.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
iheir peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
See Component and Toolkit for additional information about component peers.
See Also
java.awt.Component, java.awt.Panel, java.awt.Toolkit.
116'
java.beans
ParameterDescri ptor
в
c
D
E
F
G
H
1
Syntax
public class ParameterDescriptor extends FeatureDescriptor
Description
К A parameter descriptor contains information about a
। method parameter, such as its localized name and
whether it is meant only for experts. A parameter
M descriptor does not presently have any other
N attributes beyond those in a feature descriptor (see
FeatureDescriptor). See Figure 295.
И See Also
Q FeatureDescri ptor.
R
Example
See the MethodDescriptor class example.
T
Introspector
Explicit
Descriptors
Implicit
Descriptors
Bean
0
Bean Descriptor
Event Set Descriptors
Method Descriptors
Parameter Descriptors
Property Descriptors
Bean-Info
FIGI RK 295: Parameter Descriptor.
X
Y
Z
1166
X cl. U \\ I . 1 I I
PixelGrabber
Syntax
public class PixelGrabber implements ImageConsumer
Description
The PixelGrabber class is used to retrieve the pixels in an image or from an image producer.
The retrieved pixel values are colors either in the default color model (see Color-
Model .getRCBdefaul tO) or in the original color model of the source image.
Constructor PixelGrabberQ Constructs a new Pi xelGrabber instance. ,
Pixel Retrieval Methods abortGrabbingO grabPixels() startGrabbingO Aborts retrieval of lhe pixels. f Starts retrieval of the pixels and blocks waiting for the pixels. 1 Starts retrieval of the pixels. * i
Retrieval Information Methods | get Col orModel () Retrieves the color model being used to accumulate the pixels. ( getHei ght О Retrieves the height of the pixel buffer. । getPixelsQ Retrieves the pixel buffer. | getStatus О Determines the current state of the pixels. > getWidthO Retrieves the width of the pixel buffer. |
Image Consumer Method Called by the Image Producer ! imageCompletef) Called to deliver completion status. | setColorModel Q Called to deliver the color model for the source image. j setDi mens ions О Called to deliver the dimensions of the source image. | setHintsO Called to specify how the pixels will be delivered. ( setPi xel sQ Called to deliver pixels. [ setPropertiesO Called to deliver the properties for the source image. I
Deprecated Method status() 1 Replaced by getStatus 0. । J
116
PixelGrabber
java.awt. image
A
В
C
D
E
Г
G
H
I
J
К
L
M
N
О
Example
This example displays an image and retrieves the
pixel values of the image. See Figure 296. The
program displays the color components of the
pixel that is directly under lhe cursor. If you click
lhe pixel, the program colors all identical pixels
in the image red. The program also displays the
number of times that pixel value appears in the
image.
The frame creates a label on the top and an
ImageCanvas object in the center. I'he Image-
Canvas object is created with an image and a label. It displays the image and watches the ci
sor. Using the supplied label, the ImageCanvas object displays the color components oft
pixel that is directly under the cursor.
PixelGrabber Example 1^1* £
2<29: 24844116
.... tol Ai 11 inrmW^iii ift I a iniiiiiiiiitn ........
FIGI RE 296: PixelGrabber.
Q
R
S
T
U
v
w
x
Y
z
import java.awt.*;
import java.awt.image.•;
import java.awt.event.*;
class Main extends Frame {
Main(String filename) {
super("PixelGrabber Example”);
Label label - new Label О;
add(label, BorderLayout,NORTH);
add(new ImageCanvas(getToolkit().qetlmage(filename), label),
BorderL ayout.CFNTFR);
setSize(300, 300);
showO;
}
static public void mai n(Stri ng[] args) {
if (args.length — 1) {
new Main(args[0J);
} else {
System.err.println(”usage: java Main <image files”);
}
}
1
class ImageCanvas extends Component {
Image image;
Label label;
intLJ pixels;
boolean paintlargetPixels;
int targetPixelValue;
ImageCanvas(Image image, Label label) {
this.image = image;
thi s.1abel = label;
// Add listeners for canvas
addMouseMotionListener(new MouseMotionEventHandler());
1168
addMouseListener(new MouseEventHandl er Q);
void paintPixels(Graphics g, int w, int h) {
int count = 0;
g.setColor(Color.red);
for (int x=0; x<w; x++) {
for (int y-0; ych; y+O {
int p pixelsfy * w * x];
if (p == targetpixelValue) {
g.fi1lRect(x, у, 1, 1);
count-n-;
}
}
}
label .setTextC'count: “ + count);
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if (image != null) {
g.drawlmage(image, 0, 0, this);
int w = image.getWidth(this);
int h -- image.getHeight(this):
if (w < 0 I। h < 0) return;
if (paintlargetPixels) {
paintPixelsCg, w, h);
}
if (pixels null) {
// Create a pixel grabber and retrieve the pixels,
pixels =- new i nt Lw * hj;
try {
PixelGrabber pg =- new PixelGrabber(
image, 0, 0, w, h, pixels, 0, w);
pg.grabPixels();
// Check for errors.
if ((pg, statusO & ImageObserver.ABORT) !- 0) {
System.err .pri ntlnCError whi le fetching image’’);
System.exit(l);
}
} catch (Exception e) {
e .pri ntStackl race О *,
System.exi t(l);
}
}
}
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
int x - evt.getXO, у - evt.getYO;
i f (pi xels -= nul1 | I
x >= image.gettoidth(ImageCanvas.this) II
у image.getHeight(ImageCanvas.this)) {
111
PixclG rabber ja va.awt. i rn age
aborlGrabbingf }
1 abel, setTextC);
return;
}
ColorModel cm - ColorModel.getRCBdefaultО;
inr p - pixels^y * image.gettaidth(ImageCanvas.this) + x] ;
// The pixel value is translated into a color using
// the default color model.
label.setlext(x + “," + у + “: “ + cm.getRed(p) + " “
4 cm.getCreen(p) + " M ± cm.getBlue(p)
4- “ a(“4cm.getAlpha(p) -
}
}
class MouseEventHandler extends MouseAdapter {
public void mousePressedCMouseEvent evt) {
int x - evt.getXO, у = evt.getYO;
i f (oixels -- null I t
x >- image.qetWidth(ImageCanvas.this) I’
у >- image.getHeight(ImageCanvas.this)) {
return;
}
targetPixelValue - pixels[y * image.getWidth(ImageCanvas.this) 4- xj;
paintTargetPixels = true;
repai nt();
}
public void mouseReleased(Mousebvent evt) {
paintTargetPixels - false;
repaintO:
}
}
}
abortG rabbi ng()
pi rposi. Aborts retrieval of the pixels.
syntax public synchronized void abortGrabbi ngO
DiiscRiHioN This method aborts the retrieval of the pixels by this pixel grabber by calling
imageCompleteO with IMAGEABORTED.
sff. also getStatusO, imageCompleteO. startGrabbi ngO.
getColorModelf)
pi rposi. Retrieves the color model being used to accumulate the pixels.
svsi ax public synchronized ColorModel getColorModel()
1170
getHeight()
descrip ГЮЧ If this pixel grabber was constructed with an explicit pixel buffer or if it was created with forceRGB set to true, this method always returns the default RGB color model. If it was created with forceRGB set to false, the color model being used is that of the source image (i.e.. the color model passed to setPixelsQ). If a different color model is passed to setPixelsQ at any time, the default RGB color model is used. The color model returned may be null if the color model has not been determined.
RETURNS The color model currently being used for accumulating the pixels; null if not yet determined.
see: also ColorModel, ColorModel.getRGBDefaultO, PixelGrabber(), setPixelsQ.
EXAMPLE: See MemorylmageSource. setAni mateQ.
getHeight))
PURPOSE. Retrieves the height of the pixel buffer.
SYNTAX public synchronised int getHeightQ
DESCRIPTION If this pixel grabber was constructed with a non negative height, this method returns that height. If it was created with a negative height, the height of the pixel buffer is determined by the height of the source image when the dimen- sions of the image are delivered (see setDimensionsO). If the dimensions are not yet available, this method returns 1.
RETURNS The final height of the pixel buffer; -1 if not yet determined.
SEE ALSO PixelGrabberQ, setDimensionsO, setPixelsQ.
EXAMPLE See MemorylmageSou rce.setAni mate Q.
getPixels()
PURPOSE Retrieves the pixel buffer.
SYNTAX public synchronized Object getPixelsQ
DESCRIPTION If this pixel grabber was constructed with an explicit pixel buffer, this method always returns that pixel buffer. Otherwise, it returns the pixel buffer dynami caily allocated for this pixel grabber. The color model being used affects the type of the buffer used (whether byte array or int array). Moreover, because the color model can be changed at any time due to calls to setPixelsQ (see
111
PixeKJrabber
getStatus( I
java.awl.image
getColorModel (H the object returned by this method nia> change over time
until lhe pixel grabbing has completed.
A RETURNS The pixel buffer containing the pixels grabbed; null if the size and format of lhe pixel buffer has not yet been determined. The value returned is cither a byte arras or an int array, depending on lhe color model being used to accu-
В mulate the pixels.
c SEI. \ES(> Pi xelGrabber О t setPixelsQ.
D EXAMP1.E See MemorylmageSource. setAnimateO.
Г
G
H
I
J
К
I.
M
getStatusf)
purpose Determines the current statu of the pixels.
syntax public, synchronized int getStatusO
description The result value indicates the current state of the pixels. The result value is a
bitwise “of* of flags in the ImageObserver interface. See lhe ImageOb-
server class for details on available status bits.
SEE M so ImageObserver.
i ХЛМР1 e See the class example.
о getWidth() . _
01 PURPOSE Retrieves the width of the pixel buffer.
Q SYNTAX R DESCRIPTION S public synchronized int getWidth() If this pixel grabber was constructed with a non-negative width, this method returns that width. If it was created with a negative width, the width of the
1 I’ pixel buffer is determined by lhe width of the source image when the dimen- sions of the image are delivered (sec setDimensionsO )• If the dimensions are not yet available, this method returns -1.
V Rl It RNS fhe final width of the pixel buffer; -1 if not yet determined.
W SEE AL.SO Pixe IGrabberQ , setDimensionsO, setPixelsf).
X EXAMPLE .See MemorylmageSource. setAnimateO.
1172
grabPixels(
grabPixelsf)
purpose Starts retrieval of the pixels and blocks waiting for the pixels.
syntax public synchronized boolean grabPixelsO throws
InterruptedException
public synchronized boolean grabPixels(long ms) throws
InterruptedException
description This method causes the image or image producer to start delivering pixels to
the pixel grabber. This method returns when all of the images in the desired
rectangle (as specified in the constructor) are retrieved. If ms is specified and is
greater than 0. this method returns either when all of the pixels are retrieved or
when ms milliseconds have elapsed.
If this method returns false, the pixels were not successfully retrieved. The
cause can be determined using the getStatusO method.
This method can be called more than once and will return immediately if either
all of the pixels have been retrieved or if there has been an error. 'Typically, this
method is called more than once if a time-out has been specified.
PARAMETERS
ms The number of milliseconds to wait for the image pixels. This value must be
greater than 0.
returns true if the pixels were successfully retrieved: false otherwise.
EXCEPTIONS
InterruptedExcepti on
If another thread interrupted this thread before ms milliseconds has expired or
before all of the pixels were retrieved.
seealso getStatusO, java.lang.InterruptedException, startGrabbing().
example See the class example.
imageComplete()
purpose Called by the image producer to deliver completion status to the pixel grabber,
syntax public synchronized void imageCompletefint status)
description The PixelGrabber class implements this method as part of the ImageCon-
sumer interface. It should not be used.
PARAMETERS
status A combination of the status bits as defined in the ImageConsumer class.
seealso ImageConsumer.imageCompleteО.
example See ImageConsumer.
ii'
PixelGrabber
java.awt.image
PixelGrabber()
PixelGrabber()
purpose Constructs a new PixelGrabber instance.
SYNTAX public PixelGrabberflmage img, int x, int y, int w, int h, i nt[]
A pix, int off, int scansize)
public PixelGrabber(ImageProducer ip, int x, int y, int w, int h,
В int[] pix, int off, int scansize)
c public PixelGrabberflmage img, int x, int y, int w, int h, boolean
forceRGB)
D DESCRIPTION This constructor constructs a new PixelGrabber instance to retrieve the pix-
E els in the rectangle defined by (x, y. w, h). If the image img is specified, the
F pixels are retrieved from img. If the image producer ip is specified. the pixels
are retrieved from i p.
u The first two forms of the constructor provide for the pixel values to be stored
H in the pix integer array in the default color model. The pixel value for pixel
I (i , j), where (i, j) is inside the rectangle (x, y, w, h), is stored in the
1 array at pix[(j - y) * scansize + (i - x) + off]. The pixels are accumu-
J lated using the default RGB color model.
к The third form of the constructor provides for a buffer to be allocated for the
L pixel grabber to store the pixels. If forceRGB is true, the pixels are accumu-
M lated using the default RGB color model. If forceRGB is fal se, the pixels are
IV! accumulated using the color model of the source image (i.e., the color model
N passed to setPi xel s()). If different color models are passed to different calls
О to setPixels(), the default RGB color model is used.
The action of retrieving the pixels is not started until the grabPixels()
method is called.
Q
PARAMETERS
R forceRGB If true, accumulate the pixels using the default RGB color model; if false,
S use the color model of the source image.
T h The height of the rectangle of pixels to retrieve. If negative, the height will be
1 determined by the height of the source image.
U img The non-null image.
V ip The non-null image producer.
off The offset into the array at which to store the first retrieved pixel.
w scansize The width of one row of pixels in pi x (not necessarily the same as w).
X w The width of the rectangle of pixels to retrieve. If negative, the width will be
Y determined by the height of the source image.
X The x-coordinate of the upper-left corner of the rectangle.
Z У The y-coordinate of the upper-left comer of the rectangle.
pix The non-null array of integers to hold the retrieved pixels.
1174
setColorModeh
SEE also ColorModel,getRGBdefaultО- setDimensionsC), setPixelsO.
example See the class example.
setColorModel()
PURPOSE Called by the image producer to deliver the color model for the source image.
SYNTAX public void setColorModel(ColorVodel model)
DESCRIPTION The PixelGrabber class implements this method as part of the ImageCon- sumer interface. It should not be called directly.
PARAMETERS model A non-null color model.
SEE ALSO ImageConsumer.setColorModel()
EXAMPLE See ImageConsumer.
setDimension$()
PURPOSE Called by the image producer to deliver the dimensions of the source image.
SYNTAX public void setDimensions(int width, int height)
DESCRIPTION The PixelGrabber class implements this method as part of lhe ImageCon- sumer interface. It should not be called directly.
PARAMETERS height width The height of the image in pixels. The width of the image in pixels.
SEE ALSO ImageConsumer.setDimens i ons().
EXAMPLE See ImageConsumer.
setHintsl)
PURPOSE Called by the image producer to specify how ihe pixels will be delivered.
SYMAX public void setHints(int hints)
DESCRIPTION The PixelGrabber class implements this method as part of the ImageCon- sumer interface. It should not be called directly.
PARAMETERS hints A set of bits that specify how pixels w ill be delivered.
PixelGrabber
java.awt.image
setPi xcls()
SEE ALSO ImageConsumer.setHints().
EXAMPLE See ImageConsumer.
setPlxels()
В C D E PURPOSE Called by the image producer to deliver pixels to the image consumer.
SYNTAX public void setPixels(int x, int y, int w, int h, ColorModel model, byte pixels[J, int offset, int scansize) public void setPixels(int x, int y, int w, int h, ColorModel model, int pixels[], int offset, int scansize)
F G DESCRIPTION The PixelGrabber class implements this method as part of the ImageCon sumer interface. It should not be called directly.
H PARAMETERS
I h
model
J offset
К pixels
I scansize
w
M
У
see: ai.so
EXAMPLE
The height of the rectangle in which the pixels are destined.
The non-nul 1 color model used to translate the pixel values.
The index of the first pixel in the pixel array.
The non-null array of pixel values.
The width to use when extracting pixels from pi xel s.
The width of the rectangle in which the pixels are destined.
The .r-coordinate of the rectangle in which the pixels are destined.
The у-coordinate of the rectangle in which the pixels are destined.
ImageConsumer.setPixels()
See ImageConsumer.
R setProperties()
s
purpose Called by the image producer to deliver the properties for the source image.
T
syntax public void setProperties(Hashtable props)
l' description The PixelGrabber class implements this method as part of the ImageCon-
V sumer interface. It should not be called directly.
W PARAMETERS
x props Л non-null hash table of properties.
seealso ImageConsumer.setPropertiesO -
example See ImageConsumer.
1176
startGrabbingO
startGrabbing()
PURPOSE Stans retrieval of the pixels.
SYNTAX public synchronized void startGrabbingO
DESCRIPTION This method causes the image or image producer to start delivering pixels to the pixel grabber. Unlike grabPixel s(). it returns immediately. This method can be called more than once and will return immediately if either all of the pixels have been retrieved or there has been an error. getStatusO can be called subsequently to check on the status of the retrieval.
SEE ALSO getStatusO, grabPi xel s() , abortGrabbingO .
statusO DEPRECATED
PURPOSE Replaced by getStatusO.
SYNTAX public synchronized int statusO
DEPRECATION Replace the usage of this deprecated method, as in int status = grabber.statusO; with int status - grabber.getStatusO ;
java.awt
Point
Point implements Serializable
A
В
c Syntax
n public class
E
Description
A point represents a location on a 2D plane. The coordinates of the point arc integers, so only
integral locations can be represented. A point is typically used in conjunction with AWT paint
H ing operations and with layout managers. In the AWT coordinate system, the у coordinates
increase downward rather than upward, as in classical analytical geometry.
1 In general, when returning a Point instance in a method call, either return a copy if you
j need to retain the instance or discard the instance after returning it. If you pass a point instance
in a method call and wish to continue using the instance, note whether the method will retain
lhe instance or will copy the values.
L
M
N о MEMBER SUMMARY
Constructor Poi nt О Constructs a new Point instance.
Q Point Methods
p getLocat ion() Retrieves a copy of this point.
к setLocati on() Mo\es this point to a new location.
S translateO Adds an offset to this point.
T Fields
и X Contains this point's л-coordinate.
1 1 ! у C’ontains this point's v-coordinate.
V Object Override Methods
w equals() Determines whether an object is equal to this point.
X hashCode() Calculates the hash code for this point.
Y toStringO Generates a string representation of this point.
z Deprecated Method
; move() Moves this point to a new location.
1178
ju ui.qwi
See Also
java. io. Seri a 1 i zabl e.
Example This example creates a "mine field*' of hidden Point Example НГ-Ш
•
random points. If you move the cursor over a
point, it turns red. See Figure 297.
import java.awt. import java.awt.event; • •
class Main extends Frame {
int dotSize = 10; PointП pts new Point[1002; FIGI’RE 297: Point.
Main() {
superC'Point Example”);
for (int i—0; i<pts.1ength; i*+) {
ptsГi1 = new Point();
}
setForeground(Color.red);
// Add mouse motion listener for frame
addMouseMotionListener(new MouseMotionHandlerO);
setSize(200t 200);
show();
}
// Returns a random integer in the range [0..Г-1].
int random(int r) {
r - Math.max(r, 0);
return (i nt) (Math. floor (Math. randomO *r));
}
public void paint(Graphics g) {
Insets insets = getlnsetsO;
int w ~ getSize()-width-insets.left-insets.right;
int h getSizeO.height-insets.top-insets.bottom;
for (int i=0; i<pts.length; i++) {
pts[i].setl.ocation(random(w-dotSize), random(h-dotSize)) ;
}
}
public void update(Graphics g) {
for (int i--0; i<pts.length; i+O {
if (pts[i].x < 0) {
g. fi 1 lOval (-pts [i ]. x, -pts[il.y, dotSize, dotSize);
}
}
}
// Mouse motion handler for movement within frame
class MouseMotionHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
int x - evt.getXO;
Point
java.awt
equals()
int у = evt.getY();
Point p = new Point(x-dotSize/2, у dotSize/2);
for (int i-0; i<pts.1ength; i+*) {
if (p.eqiials(pts[i])) {
pts [i ]. x - -pts Li J. x;
a pts[iJ.y = -ptsLiJ y;
repai ntO;
В break;
}
C }
}
D }
E static public void main(Stri ng О args) {
new MainO;
I- }
}
(1
equals()
I *
pi rpose Determines whether an object is equal to this point.
syntax public boolean equalsfObject object)
К
I in.scrip! ion Two points are equal if both their a- and v-coordinates arc equal.
PAR A Mil ERS
M , . ...
object I he point to which to compare.
N
returns true it object is an instance of Point and is equal lo this point: false othei
<> wise.
overrides java.lang.Object.equals().
example See the class example.
s
I
i:
v
w
x
Y
Z
getLocation()
purpose Retrieves a copy of this point.
syntax public Point getLocationO
ri h rns A new non-null point containing this point's coordinates.
sei. also sett ocati on().
ex ampi e This example moves a point vertically.
void moveVertical(Point pt, int deltaY) {
Point orig = pt. getLocationO ;
pt.setLocation(orig.x, orig.y+deltaY);
}
1180
hashCode()
hashCode()
PURPOSE Calculates the hash code for this point.
SYNTAX public int hashcode()
DESCRIPTION This point's hash code is an integer that is calculated from the point's л- and y- coordinates. If equals(pl, p2) is true, then pl and p2 will have (he same hash code. Otherwise, pl and p2 will very likely have different hash codes.
RETURNS The point's hash code.
OVERRIDES j ava.1ang.Obj ect.hashCode().
SEE A1JSO equals().
EXAMPLE This method uses a hash table to associate a point with an integer count.
Hashtable ht = new HashtableO;
void inc(Point p) {
int i = 0;
Integer integer = (Integer)ht.get(p);
if (integer null) {
i == integer. intValueQ;
}
ht.put(p, new Integer(i+1));
}
DEPRECATED
move()
PURPOSE Replaced by setLocati on О.
SYNTAX public void move(int x, int y)
PARAMETERS
X The new jr-coordinate.
У The newy-coordinaie.
deprivation Replace the usage of this deprecated method, as in point.move(x, y); with point.setLocation(x, y);.
Point()
purpose Constructs a new Point instance.
syntax public PointO
public Point(Point src)
public Point(int x, int y)
Point java.awt
setLocaiiont)
DESCRIPTION This constructor creates a new Point object and initializes it using either the coordinates x and у or the coordinates from the point src. If no coordinates are specified, they default to 0. 0.
PARAMETERS src I'he point whose r- and y-coordi nates io use for constructing the new point.
X I'he a-coordinate.
У I he y-coordinate.
EXAMPLE See the class example.
setLocation()
Pl RPOSI Moves this point to a new location.
SY StAX public void setlocation(int x, int y) public, void sett ocation(Point pt)
DESCRIP HON This method changes the a- and у coordinates of this point to be x and у or the coordinates indicated by the point pt.
PARAMETERS Pt X The non-null point of the new location. I he new a-coordinate.
У The new y-coordinate.
SEE ALSO getLocationQ
EX \MPI F See the class example.
toStringO
— —
PIRP< )SE Generates the string representation of this point.
SYNTAX public String toStringO
DESCRIP 1 ION This method generates this point's string representation, which consists of the point's coordinates. Phis method is typically used for debugging output.
RETVRNS A non-null string containing the coordinates of the point.
OVERRIDES java. lang.Object. toStringO.
EXAMPLE These statements print identical string representations of the point.
Point p - new Point(10, 20);
System.out.println("p - “ * p.toString());
System.out.println(“p = “ + p);
1182
translate!)
translated
PURPOSE Adds an offset to this point.
SYNTAX public void translate!!nt x, int y)
description This method adds x to the point's л-coordinate and adds у to the point’s y-coor- dinate.
parameters X The offset to add to the point’s л-coordinate.
У l he offset to add to the point’s y-coordinate.
EXAMPLE This example paints a red square with a shadow at point p:
public void paintShadowRect(Graphics g, Point p) {
p.translated, 5);
g.setColor(Col or.gray);
g.fillRectCp.x, p.y, 100, 100);
p.translate(-5, -5);
g.setColorfColor.red);
g.fi11Rect(p.x, p.y, 100. 100);
}
X
purpose Contains this point s л-coordinate.
syntax public int x
example: See (he class example.
У
purpose: Contains this point’s y-coordinate.
syntax public int у
exampi,e See the class example.
i is
java.awt
Polygon
A —< poi
В
c Syntax
D public class Polygon implements Serializable
E
Description
A polygon is a data structure that maintains a list of points. Phis class is primarily used in eon
C junction with Graphics. drawpolygon О and Graphics.fill Polygon(). The polygon
H maintains a bounding box. which is the smallest rectangle that includes all of the points in the
polygon. See getBoundsO for more details.
J MEMBER SUMMARY
1/
IS. 1
1 Constructor
L . Polygonо Constructs a new Polygon instance.
M Fields
N I bounds Contains this polygon's bounding rectangle.
() 1 npoints Contains the number of points in this polygon.
। xpoints Array containing the x-coordinates of this polygon's points.
| ypoints Array containing the у-coordinates ol this polygon's points.
Q I Point Methods
R addPoi nt(j Adds a point to this polygon.
I containsQ Determines if a point is inside this polygon.
S । translateO Adds an offset to all points in this polygon.
1 | Bounding Box Method
U getBoundsO Calculates this polygon's bounding box.
V 1 Deprecated Methods
w I getBoundingBoxO Replaced by getBoundsO.
x | insideO Replaced by contai ns(). j
Y
See Also
java.io.Serializable. Point.
1184
Example
This example generates a random
polygon and allows you to flip it or
shift it. See Figure 298. There are
four buttons that modify the polygon.
The New button creates a new ran-
dom polygon based on the current
size of the canvas. The Id ip Ver but-
ton flips the polygon around the \-
axis. The Flip Hor button flips the
polygon around the v-axis. l he Shift
button moves the polygon down and
to the right 5 pixels.
Also, a label at the top indicates
whether the position pointed to by the
cursor is considered to be inside or
outside the polygon.
import java.awt.*;
import java.awt.event;
public class Main
extends Frame
i mplements
ActionListener {
Label 1 = new Label ();
MainCanvas cv =
new MainCanvas(l;;
Polygon Example
3sl*l
i. и nt s i rr- true
1 IGI Rl, 298: Polygon.
Main О {
superCPolygon Example";:
Panel p = new Panelfnew GridLayout(1, 0;);
Button b;
p.add(b = new Button("New";; ;
b.addActi onLi stene^(thi s; ;
p.add(b = new ButtonC’Fl ip Ver";};
b.addActi onLi stenerГthi s);
p.add(b = new Button("Flip Hor";;;
b.addActionLi stenerfthis;;
p.addfb = new ButtonC’Shi ft";; ;
b.addActionLi stenerfthis);
addfp. BorderLayout.SOUTH;;
cv.setSi ze<300, 300};
addfev, BorderLayout.CENTER; ;
addfl, BorderLayout.NORTH;;
pack C) :
showf;.
Polygon
java, awl
// Action handler for buttons
public void actionPerformed(ActionEvent evt) {
String what = evt .getActionCorrmandO ;
if ("New”.equals(what)) {
cv.poiygon = nul1;
} else if (cv.polygon != null) {
if ("Shift”.equals(what)) {
cv.poiygon.translate(5, 5);
} else {
boolean ver - “Flip Ver”.equals(what);
Rectangle r - cv. poiygon .qetBoundsO ;
r.add(0, 0);
for (int i=0; i<cv.polygon.npoints; i++) {
if (ver) {
cv.polygon.ypointsli] - r.height - cv.poiygon.ypoints'
} else {
cv,poiygon.xpoints[i1 - r.width - cv.poiygon.xpoints[
}
}
}
}
cv. repaintO ;
}
static public void main(String[J args) {
new Mai n();
}
}
class MainCanvas extends Canvas {
Label label;
Polygon polygon;
MainCanvas(Label label) {
thi s.label = label;
addMouseMotiоnL i stener(new MouseMot ionHandlerO);
}
// Returns a random number in the range [0..Г-1].
int random(int r) {
ret urn (int) (Math. floor (Math. random () •• r)) ;
}
public void paint(Graphics g) {
int w = getSize().width;
int h - getSize().height;
if (polygon -- null) {
polygon = new PolygonO;
for (int i=0; i<25; i4<) {
// Points need to be one pixel from the
// right and bottom edges otherwise the polygon
// will extend outside the canvas bounds.
poiygon.addPoint(random(w 1), random(h-l));
}
}
g.fi11 Polygon(poiygon);
}
1186
addPoint()
// Mouse motion handler for canvas
class MouseMotionHandler extends MouseMotionAdapter {
public void mouseMoved(Mousel-vent evt) {
i f (polygon != nul1) {
label.setTextCcontains: “ 4
po 1 ygon. contai ns (evt .getXO , evt.getYO)) ;
}
}
}
}
addPoint()
purpose Adds a point to this polygon.
syntax public void addPoint(int xt int y)
descriptkin This method adds the point (x, y) to the polygon. After this method, the point
will be included in the polygon’s bounding box.
If you call getBoundsO and retain a handle to the rectangle instance, lhe val-
ues in the rectangle instance will be automatically updated after calling
addPointО.
PARAMETERS
x The х-coordinate of the new point.
у The y-coordinate of the new point.
see also getBounds О.
example See the class example.
bounds
purpose Contains this polygon's bounding box.
syntax protected Rectangle bounds
description The bounding box is described in the class description. If the bounding box has
not been calculated yet, this field is null. The bounding box is calculated
when contai ns О or getBoundsO is called.
t fSF
java.awt
Polygon
contains()
contains()
PURPOSE Determines if a point is inside this polygon.
SYNTAX public boolean contains(int x, int y) public boolean contains(Point pt)
DESCRIPTION This method determines if point (x. y) or pt is inside the polygon. It uses an even-odd insideness rule (otherwise known as an alternating rule).
PARAMETERS Pt X У The non-null point whose coordinates are to he tested. The л-coordinate of the point to be tested. The y-coordinate of the point to be tested.
RETURNS true if the point is inside the polygon; fal se otherwise.
EXAMPI F See the class example.
getBoundingBox()
DEPKEC4TEI)
PURPOSE Replaced by getBoundsO.
SYNTAX public Rectangle getBoundingBoxQ
RETURNS A non-null rectangle defining the bounds of the polygon. Do not modify the rectangle.
DEPRECATION Replace the usage of this deprecated method, as in Rectangle box = polygon.getBoundingBoxQ ; with Rectangle box = polygon.getBoundsO;
getBounds()
PURPOSE Calculates this polygon's bounding box.
SYNTAX public Rectangle getBoundsO
DESCRIPTION The bounding box is defined to be the smallest rectangle that includes all of the points in the polygon. The values in the returned rectangle are updated auto- matically as points are added to the polygon. If either getBoundsO or contai ns О has been called, do not directly modify any of the fields npoints, xpoints, or ypoints. Modifying these after the bounding box has been calculated will invalidate the hounding box. However, there's no way to recalculate the bounding box, except to create a new polygon instance.
1188
inside(
RETIRSS A non-null rectangle defining the bounds of the polygon. Do not modify the rectangle.
SEE AUSO bounds.
EXAMPI.I: See the class example.
inside() DEPRECATED
PURPOSE Replaced by contai ns().
SYNTAX public boolean inside(inL x( int y)
PARAMETERS X The л-coordinate of the point to be tested.
У The y-coordinate of the point to be tested.
RETURNS true if the point is inside the polygon; fal se otherwise.
DEPRECATION Replace the usage of this deprecated method, as in if (polygon,inside(x, y)) ... with it (polygon.contains(x,y)) ... if (polygon.containsfnew Point(x, y))) ...
npoints
PURPOSI. Contains the number of points in this polygon.
SYNiAX public int npoints
DESCRIP'I ION Do not modify this field if either getBoundsO or contai ns О has been called. See getBoundsO for details.
SEE Al SO getBoundsO.
example See the class example.
PolygonQ .
PURPOSE Constructs a new Polygon instance.
SYNTAX public PolygonO public Polygon(int[] xpoint, int[] ypointst int npoints)
DESCRIPTION The two forms of this constructor create a new Polygon instance with npoi nts points. The point coordinates are specified in lhe arrays xpoi nts and
java.awt
Polygon
translated)
ypoints. The x- and у-coordinates of point i are. respectively* xpoints[i]
and ypoi nts [i]. If no parameters are specified, the polygon is created with
no points.
PARAMETERS
A npoi nts lhe number of supplied points in xpoints and ypoints.
В xpoints The non-null array ofx-coordinates.
C ypoints The non-null array of y-coordi nates.
D E EXAMPLE See the class example.
F translate^)
G PURPOSE Adds an offset to all points in this polygon.
H SYXTAX public void translate(int x, int y)
I DESCRIPTION For each point in this polygon, this method adds x to lhe point's л-coordinate
J and adds y to the point’s y-coordinate.
К PARAMETERS
1 X The offset to add to the л-coordinate of the points in this polygon.
L, У The offset to add to the y-coordinate of the points in this polygon.
M SEE Al SO Point.translateО •
X 0 EXAMPLE See the class example.
Q R xpoints
Pl RPOSE Array containing the л-coordinates of this polygon’s points.
S SYNTAX public int[] xpoints
T и DESCRIPTION Do not modify this field if either getBoundsQ or contai nsQ has been called. See get Bounds О for details.
v SEE ALSO getBoundsQ.
V w EXAMPLE See lhe class example.
X
Y
Z
1190
jav<j.awi e
у point
у points
PURPOSE Array containing the y-coordinates of this polygon’s points.
SYNTAX publi c i nt [] ypoi nts
DESCRIPTION Do not modify this field if either getBoundsO or contains() has been called. See getBoundsO for details.
SEE ALSO getBoundsO.
EXAMPI E See the class example.
java.awt
PopupMenu
i Syntax
c public class PopupMenu extends Menu
11
I
J
К
L
M
N
()
Description
P
Q
R
S
T
и
V
w
X
A popup menu is a menu that “pops up” near a
component as a result of the user's making a
popup menu gesture. Most often, a popup menu is
created with menu items specific to the current
object and is typically’ displayed at the cursor
position where the popup menu gesture was
made. For example, displaying a popup menu on
an HTML h\perl ink in an HTML editor could
show operations such as change color and change
URL. Similarly, display ing a popup menu on a
file folder could show operations on the file
folder, such as open. move, and delete. Figure 299
shows a popup menu on a file.
The Parent and Origin
Before a popup menu can be displayed, it must
have a parent. 'I'he parent can be an\ component.
Although the popup menu must be a child of
J | L omponent
J | Container |a*
J | Dialog iava ,
< |
I Size ! Typtjd
Open
Send To ► c
Cut
Copy
Create Shortcut
Delete
Rename
Pjoperties
FIGURE 299: Popup Menu for a File.
some component, it can actually be displaced on any descendant of the popup menu's parent.
The code that displays the popup menu controls where to locale it. B\ conwntion. the popup
menu's top-left corner is displayed al the cursor position.
Y The Popup Trigger
The popup menu gesture is platform-dependent. To prexent people from ha\ing to write plat-
form-specific code to detect the popup menu gesture, the AWT takes care of watching for the
gesture and notifying the application when it occurs.
1192
More specifically* the AWT assumes that popup menus are triggered by some kind of
mousing gesture. So when it detects the mouse event that should display the popup, it tags it
with a property called the popup menu trigger (see MouseEvent.i sPopupTriggerQ), If this
property is true, it means the user made the popup menu gesture and that the popup menu is
to be displayed.
You must do the following to make a popup menu work for a component:
1. Use Component. add О to add the popup to the component.
2. Write code to detect when the popup trigger occurs and to display the popup menu.
Step 2 can be done either by overriding the component s processMouseEventO or by
adding a listener for the mouse events that are typically used for popup triggers. Although the
popup trigger is platform-dependent, it is usually associated with either the mouse released or
the mouse pressed event.
If either step is omitted, the component's popup menu will not be displayed.
Popups and AWT Components
In Java 1.1.2, support for popup menus is not consistent across AWT components. The class
example creates various components and adds popup menus for each. For example, TextArea
is an AWT component that has a popup menu already defined for editing its contents. If you
attempt to add a popup menu to a text area, the menu will not override the one defined by the
system. It will just be ignored.
Keyboard Shortcuts
If a menu item in a popup menu has a keyboard shortcut, the shortcut is ignored. To have the
desired effect of a shortcut for a popup menu item, make a copy of the menu item with the
shortcut and add it to a menu in the menu bar.
Events
Л popup menu fires the same events that a menu fires and follows the same rules used by a
menu in dealing with menu items that fire events. See the Menu class for details.
^MEMBER SUMMARY
Constructor PopupMenu() Constructs a new PopupMenu instance.
Show Method show() Displays this popup menu.
Peer Method addNoti fyO ('reales this popup menu’s peer.
PopupMenu
ja\ a.aw l
See Also
Component.add(), Component.remove(),
java.awt.event.MouseEvent.i sPopupTrigger().
A
В
C
I)
I.
I
Example
This example creates various AWT compo-
nents and adds to each a popup menu. Use lhe
popup trigger lo attempt to bring up the popup
menu for each component and sec how each
behaves. See Figure 300.
(i
H
I
.1
к
I.
M
\
import java.awt.';
import java . awt. event.;
class Main extends Frame {
Component [] comp -
new Component[11J;
PopupMenuLJ popup -
new PopupMenu [11];
Main (J {
super(“show() Example’");
setLayout(new FlowLayout());
I IGl Rb 300: PopupMenu for various AW I
Components.
()
Q
R
S
I
t
V
w
// Create various types of components
comp[0] = new TextArea (“t hi s is a text area”, •>, 10);
conip[l] = new Text Fi el dCthi s is a text field”);
comp[2] = new Button(“Button”):
comp[3] = new Label(“Label");
comp[4J = new Checkbox(“Cheekbox”) ;
Choice c - new Choicel);
c.additem(“a”) ;
c.addltem(“b") ;
c . add! tem(“c") ;
comp[5] - c;
cornp[6] = new Sc rol 1 ba r (Sc rol 1 ba r . HORIZONTAL ) ;
Canvas canvas = new MyCanvasO;
canvas.setSize(20, 20);
comp[7] - canvas;
list 1 = new Li st() ;
comp[8] - 1;
1.addltem(“one”);
1 . addltem(“two") ;
1 . addltemC'three”) ;
Component Iw -- new MyComponentU;
comp[9] = Iw;
comp[10] - this;
MouseListener ml = new MouseEventHand I er();
// Add listener and popup menus to components
for (int i =0; i <= 10; iti) {
comp[i ] . addMousel i stener'(ml) ;
popup[i] = new PopupMenu(“popup” + i);
popup[i].add(“popup item “ + i);
1194
сотрет 1.add(popupГ il);
if (i != 10)
add(comp[il);
}
setSize(150, 150);
show();
}
// Native component
class MyCanvas extends Canvas {
public void paint(Graphics g) {
g.drawOva1(0, 0, getSize()-width, getSize()•height);
}
}
// Lightweight component
class MyComponent extends Component {
public Dimension getPreferredSizeO {
return new DiTension(20, 20);
}
public void paint(Graphics g) {
g.fi1lOval(0, 0, getSize().width, getSize().height);
}
)
// Override mouseReleasedO and mousePressedO to
// catch popup menu trigger.
class MouseEventHandler extends YouseAdapter {
int findComponent(Component c) {
for (int i - 0; i 10; i++) {
if (c.equals(corpfij)) {
return i;
}
}
return 1;
)
public void mouseReleased(MouseFvent evt) {
if (evt.isPopupTrigger()) t
int i - fi ndComponent((Component)evt .getSourceO);
if (i > 0) [
popupfi ] . show(comp[i 5 . evt.getXO, evt.getYO);
} else {
System, out. pri ntln(“no popup1');
}
J
)
public void mousePressed(MouseEvent evt) {
if (evt.isPopupTrigger()) (
int i - fi ndComponent ((Component) evt. getSourceO);
if (i > 0) {
popup [i J . show(comp Fi ] r evt.getXO, evt.getYO);
} else {
System.out.pri ntln(“no popup");
}
}
}
java.awt
PopupMenu
addNotifyO
public static void main(String args[]) {
new Main();
}
}
C
D
E
F
G
H
I
J
К
L
M
N
О
addNotifyO
purpose Creates this popup menu's peer.
syntax public synchronized void addNotifyO
description This method creates the peer for this popup menu if it does not yet exist. The
peer is created by a call to Tool ki t. createPopupMenuO. The addNotifyO
method should never be called directly. It is normally called by the parent.
overrides Component.addNoti fyO-
seealso Component, Toolkit.
example See Component.addNotifyO.
Q
R
S
T
U
PopupMenuO
purpose Constructs a new PopupMenu instance.
syntax public PopupMenuO
public PopupMenu(String label)
description This constructor creates a new popup menu instance. If label is not specified,
it defaults to
PARAMETERS
label A non-null string specifying the popup menu's label.
example See the class example.
show()
purpose: Displays this popup menu.
syntax public void show(Component origin, int x, int y)
description This method displays this popup menu at the coordinates x. у relative to the
bounds of the component origin. The origin parameter must be in the com-
ponent hierarchy of this popup menu's parent. Furthermore, the parent of this
1196
showf)
popup menu must be visible and showing on the screen. Otherwise, a runtime
exception is thrown.
PAR AM FT ERS
origin
x
У
The non-null component that defines the coordinate space.
The r coordinate position to display the popup menu.
The y-coordinate position to display the popup menu.
exceptions
Il legalArgumentException
If this popup menu's parent is not an ancestor of origin.
RuntimeException
If this popup menu s parent is not showing.
SEE also Component.i sShowi ng(), java,lang.111 egalArgumentException,
java.lang.RuntimeExcepti on.
example This example creates a frame that has a
popup menu that is shown relative to a child
component (a Button). See Figure 30 L
One of the menu items in the popup has a
shortcut but it is always ignored.
import java.awt.*';
import java, awt. event;
class Main extends Frame
implements ActionListener {
PopupMenu pm = new PopupMenu("Colors");
FIG ( RE 301: Showing a Popup
Menu in a Child Component.
Button button - new Button(“West");
Main() {
super(“PopupMenu Example");
// You can add shortcut but it is ignored for popups
pm.add(new MenuItemCRed” , new MenuShortcut(KeyEvent.VK_R)));
pm. add (“Green1’);
pm.add(“Blue");
pm.addC'-’’);
pm.add(“Black”);
pm.add(“Whi te");
add(pm);
add(button, BorderLayout.WEST);
// Enable mouse events and listen for action events.
pm.addActionLi stener(thi s);
enableEvents(AWTEvent.MOUSE^EVENT-MASK'AWTEvent.KEY-EVENT MASK);
setSize(150, 150);
show();
119
java.awt
PopupMenu
show()
Л
В
C
D
E
Г
G
II
public void actionPerformed(ActionEvent evt) {
System.out.print In(evt.getActionCommandO);
}
protected void processMouseEvent(MouseEvent evt) {
if (evt. i sPopupFri ggerO) {
// Illustrates that you can make popup show
// subcomponents, using any coordinates
pm.show(button. button. getSizeO .width, 0);
super.processMousetvent(evt);
}
public static void main(String args[J) {
new Mai n();
}
I
J
К
L
M
N
О
Q
R
S
T
C
V
w
X
Y
z
1198
о*».
iava.awi.puci
PopupMenuPeer
Syntax
public interface PopupMenuPeer extends MenuPeer
Description
The popup menu component (see the PopupMenu class) in the AWT uses (he platform’s native
implementation of a popup menu. So that the AWT popup menu behaves the same on all plat-
forms, the popup menu is assigned a peer whose task is to translate the behavior of the plat-
form’s native popup menu to the behavior of the AWT popup menu.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
j ava. awt counterparts.
Menu component peers serve the same role as component peers. See Component and
Tool ki t for additional information about component peers.
"SUMMARY
Peer Method
showO
Displays the popup menu.
See Also
j ava.awt.Component, j ava.awt.PopupMenu, j ava.awt.Tool kit.
i к
PopupMenuPeer
java.awt.peer
show()
PURPOSE Displays the popup men it
SYNTAX void showCEvent evt)
DESCRIPTION T his method displays the popup menu at the coordinates specified in the event evt relative to the coordinate system of the source component specified in the ex ent.
SEI: XL SO java. awt. PopupMenu . showO.
1200
java.awi
PrintGraphics
Syntax
public interface PrintGraphics
Description
Generating a printed page is very simi-
lar to painting on the screen. In particu-
lar, you need to create a special
graphics context for the printer rather
than for the screen. Sec Figure 302.
Use the Printjob.getGraphicsO
method to create such a print graphics
context. After obtaining a print graph-
ics context, you can use all of the nor-
mal drawing operations in the
Graphics class on the print graphics
context. For example, to draw a line on
the page, you would use Graph-
ics .drawLineО.
drawLi net)—►
Drawing
surface
FIGURE 302: Graphics Context Drawing Surfaces.
The coordinate system for a print graphics context is identical _____x
to the coordinate system of the screen; that is, the i -coordinate at r
the top of the page is 0 and increases from top to bottom. See Fig-
ure 303. у
You can obtain the printable dimensions of the print graphics
object by calling PrintJob.getPageDimensionf).
FIGURE 303:
PrintGraphics
Coordinates.
java.awt
HI
A
В
C
PrintGraphics
getPrintJobO
MEMBER SUMMARYY
Print Job Method
j getPrintJobO
Retrieves the printjob associated with this print graphics con-
text.
See Also
Graphics, PrintJob.
r Example
Cl See the Pri nt Job class example.
H
[
J
К
L
M
N
getPrintJobO
pi’rpose: Retrieves the printjob associated with this print graphics context.
syntax public PrintJob getPrintJobO
nt scripi ion This method returns the print job object from which this printer graphics con
text was created. 1’his method can be useful when a painting method wants ti
behave differently if the graphics context is actually a printer graphics object.
RLTVRNS /X non-nul 1 Pti nt Job object.
SliL ALSO PrintJob
example: See lhe PrintJob class example.
R
S
T
i:
v
w
x
Y
z
1202
java.awt
Pri nt Job
-—J
« print job" cT|| A
В
Syntax c
public abstract class Printjob D
E
Description
This class is used to print to the system's printer. Generating a printed page is very similar to *
painting on the screen. For example, to draw a line on the page, you would use Graph- G
ics.drawLineO- The coordinate system for a printed page is identical to the coordinate sys-
tem of the screen; that is. the y-coordinate at the top of the page is 0 and increases from top to
bottom. See Pri ntG raphi cs. 1
ЛИ of the drawing operations that you can perform on the screen can be performed on a j
printed page.
К
Steps to Print L
I. To start a print job, you must call Tool kit .getPr i nt JobO to get a print job instance. M
Calling this method causes a platform-dependent modal printer options dialog to appear.
The user must select the options and click either Cancel to cancel the print job or OK to
continue w ith the print job. О
2. With the print job instance, you must call getGraphi csO to obtain a graphics context on
which you can paint. Anything painted on this graphics context will appear on a printed
page. When the page is completed, di sposeО must be called on the graphics context.
3, To print more pages, you call getGraphi csO for each page. After each page is com- R
pleted, the graphics context must be disposed of.
4. Finally, once all of the pages have been generated, the print job's end() method must be
called to cause the pages tn be printed. 1
Limitations and Bugs
The print job class will be enhanced in future versions. However, here are some of its present '
limitations: V
• There is no way to abort a print job once it has been created. Once the user has decided to
go ahead with the print job and the program starts to generate pages, the program cannot
decide to abort the job. '
Printjob
java.awt
A
В
C
D
E
F
G
H
1
J
К
L
• There is no way for a program to select printer options. For example, the program cannot
choose to print in portrait mode or landscape mode. Which mode to use must be indicated
by the user in the printer options dialog. If the user chooses incorrectly; the pages will he
printed incorrectly.
• The method to determine the page dimensions, getPageDimensionO, may return incor-
rect results. This is a bug. The workaround is to use the screen resolution (see Tool-
kit. getScreenResolution()) to determine the page dimensions. In other words,
multiply the screen resolution by 8.5 to gel the page's pixel width and by II to gel lhe
page’s pixel height. However, not all of this area is printable; the page typically has a mar-
gin in which it cannot print. At present, there is no way to determine the size of this mar-
gin, so the user must guess. Also, the guessed number may not work for all primers.
• After the user selects the printer options from the printer options dialog, the set of selected
options are not available to the program. In particular, the props parameter to Tool-
kit .getPrintJobQ is ignored.
• Images that contain transparent pixels are not painted correctly. The transparent pixels are
painted with a color from the image's color map. The pixels behind the transparent pixels
cannot show through.
• A true preview of the print job on the screen before printing it is not possible to attain. At
present, the best you can do is render it on the screen using the screen resolution and
screen font metrics and hope that the printer resolution and font metrics are similar.
M
N
()
Q
R
S
T
u
V
w
MEMBER SUMMARY ——- —— — —
Graphics Method getGraphi csO Creates a graphics context for painting on a primed page.
Page Properties getPageDimensionO getPageResoluti on() lastPageFi rst() Retrieves the dimensions of the page in pixels. Retrieves lhe resolution of the printed page in pixels per inch. Determines if pages should be printed backwards.
End Job Method end() Completes lhe print job.
Garbage Collector Method finalizeO Completes lhe prim job.
See Also
Z Component.printO, Component.printAllО, Graphics, PrintGraphics,
Tool kit.getPri ntJobО -
1204
java aw I
Printjob
HIM________________________________________ WG
а** ЯИИИМИИП] |
йнф
IsW HPDMkJH’ZW
LPT 1
(xrwiwrt r
¥ Murtmrf PT** 3
r 1 r JI J jj • I*.
[ oi I J
FIGI RE 304: Printer C ontrol Dialog.
Example
This rather long example implements a f*iiU\ func-
tional program that will print a text file in land-
scape mode with two pages per sheet of paper. See
Figure 305. For a simple example, see getGraph-
ics().
With the program, you can set a font si/e and
preview the results on the screen. However, due to
restrictions of the printer methods, what appears
on the screen may not be identical to w hat appears
on paper. This could happen if the font metrics for
the desired font size supported by the screen and
those supported by the printer do not match.
The previewer main-
tains a vector of lines that
have been broken lo fit in :
the page. The methods that
render the page always >
check the supplied graphics
context for any changes to
the page dimensions or font .... :
metrics. If there are any
changes, it recomputes the
vector of broken lines.
To indicate broken
lines, the program displays -
a continuation character
(depicted as an arc) at lhe
end of the line. The pro-
gram remembers to display ________
the continuation chaiacter FIGURE 305: Sample PrintJob Output,
by appending a + al the end
of lines that have been broken. When the program prints the line, it print the continuation sym-
bol instead of the +.
Note: In Java 1.1.2. the getPageDimension() method returns incorrect results. The
workaround is to determine a page si/e by applying the screen resolution on an 8.5-/-11-inch
sheet of paper. However, most printers cannot print in all of this area. At present, there is no
way to determine lhe exact si/e of the printable area, so we simply guess and reduce the area's
width and height by three-fourths of an inch.
Printjob
java.awt
import java.awt.*;
import java.awt.event. *;
import java.io.*;
import java.uti1. *;
import java.text.*;
class Main extends Frame implements ActionListener {
int curPointSize = 12;
String filename;
Vector lines = new VectorO;
Button printBtn = new Button(“Print...”) ;
TextField pointsize = new TextField(““ + curPointSize);
TextField pageNum = new TextField(*ll”);
Preview preview;
Main(String filename) {
super("PrintJob Example”);
// Remember the filename,
this.fi1 ename = filename;
// Read the file into lines,
try {
String line;
BufferedReader fis = new BufferedReader(
new InputStreamReader(new FilelnputStream(filename)));
while ((line = fi s. readLineO) != null) {
lines.addElement(1i ne);
}
fis.close();
} catch (Exception e) {
e.printStackTraceO ;
}
// Listen for events.
pageNum.addActionLi stener(thi s);
pointsize.addActionListener(thi s);
pri ntBtn.addActionLi stener(this);
// Layout and show components.
Panel p = new Panel (new FlowLayoutQ);
p.add(new Label(“Page:”, Label.RIGHT));
p.add(pageNum);
p.add(new Label(“Point Size:”, Label.RIGHT));
p.add(poi ntSi ze);
p.add(pri ntBtn);
add(p, BorderLayout.NORTH);
// Create and prepare the preview component,
preview = new Preview(filename, lines);
add(previ ew, BorderLayout.CENTER);
preview.setFont(new Font(“Monospaced”, Font.PLAIN, curPointSize));
pack();
showO;
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSourceO == pageNum) {
1206
java.awt
Printjob
// Set the page.
preview.setPage(Integer.parselnt(pageNum.getlext())-l);
} else if (evt.getSourceO ~= pointsize) {
// Set the point size.
curPointSize = Integer.parseInt(pointSize.getTextO);
preview.setFont(new Iont(“Monospaced”, Font.PLAIN, curPointSize));
} else if (evt .getSourceO — printBtn) {
// Print the file.
Properties props = new PropertiesO;
Printjob pj - getToolkit().getPrintJob(this. filename, props);
if (pj != null) {
// Print out any properties.
for (Enumeration e - props,propertyNames() :
e. hasMoreElements() ;) {
System.out .println(e.nextElement()) ;
}
Graphics pjG = pj .getGraphicsO ;
int pages - preview.getPageCount(pjG);
// Always print even number of pages,
if (pages % 2 -= 1) {
pages* *;
}
for (int i^0; i<pages; i 2) {
if (pjG -- nul1) {
pjG pj .getGraphicsO ;
}
if (pj.lastPageFirst()) {
preview.print(pjG, pages-i-2);
} else {
preview.print(pjG, i);
}
pjG.disposeO;
pjG = nul1;
}
pj.end();
}
}
}
public static void main(String[l args) {
if (args.length —- 1) {
new Main(args[0]);
} else {
System.err.println(“Usage: java Main <text file>”);
}
}
}
class Preview extends Component {
int page;
String filename;
Font headerFont = new Font(“Serif”, Font.BOLD, 14);
Font font;
Vector lines;
Preview(String filename, Vector lines) {
this,fi1 ename - filename;
Printjob
java.awt
this.lines = lines;
}
// Sets the font and repaints the display,
public void setFont(Font f) {
font = f;
A repaintO;
}
В
// p is 0-based.
C void setPage(int p) {
page - p;
D repaintO;
}
E
// Returns the page count relative to the metrics in g.
F int getPageCount(Graphics g) {
prepareLayoutValues(g);
G return (brokenLines.sizeO-1) / linesPerPage + 1;
}
H
// Prints the page p and p+1.
I // p is 0-based.
public void print(Graphics gT int p) {
J page = p;
paint(g);
К }
L public void paint(Graphics g) {
prepareLayoutValues(g);
M
g.setFont(headerFont);
N FontMetrics fm g.getFontMetrics();
О // Draw the filename.
g.drawString(fi lename, boxRect.x. fm.getHeight О/2+fm. getAscentO);
// Draw the date and page number.
Q g.drawString(
DateFormat.getDateTimelnstanceO . formatCnew DateO) ,
R boxRect.x + pageRect.width, fm. getHei ght ()/2+fm. getAscentO);
S
for (int p=0; p<2; p++) {
T if (page + p >= (brokenLines.size()-l) / linesPerPage + 1) {
break;
L' }
V // Draw page number.
String s - u<< + (page + p + 1);
W g.setFont(headerFont);
fm = g.getFontMetricsO :
X g.drawString(s,
boxRect.x + p*pageRect.width + boxRect.width -
Y fm.stringWidth(s),
fm.getHei ght О/2+fm.getAscent O);
Z
g.drawRect(boxRect.x + p*pageRect.width,
boxRect.у, boxRect.width-1t boxRect.height-1);
1208
java.awt
Pri nt Job
// Find the starting line on the current page.
int 1 - Math.mi n(brokenl_ines . sizeO , (page+p) ” 1 inesPerPage);
g.setFont(font);
f#n - g. getFontMetricsO;
int x -= 1istingRect.x + p-pageRect .width;
int у = 1istingRect.у * fm.getAscent();
for (int i=0; i<1inesPerPage && 1+i < brokenl ines.size(); i*+) {
s - (String)brokenLines.elementAt(l + i);
if (s.length() > charsPerline) {
int charWidth = fm.charWidth(‘v’);
s = s. substring(0, charsPerlire);
// Draw the continuation symbol,
g.drawArc(
1istingRect.x+charsPerLine*charWidth + p*pageRect.width,
y-fm.getAscentО < fm.getHeight()/2r
charWidth, fm.getHeight()/2,
45, -180);
}
g.drawString(s, x, y);
у += fm.getHei ght();
]
}
}
// External margin in which the printer cannot print.
int pageMargin;
// Internal margin between boxes and text.
int margin = 10;
Insets margins - new Insets(10, 10, 10, 10);;
// Bounds which includes the header, box, and listing.
Rectangle pageRect;
// The bounds of the box.
Rectangle boxRect;
// The bounds of the listing. This rectangle strictly contains
// the text and not the continuation character.
Rectangle 1istingRect;
// Number of characters per line.
int charsPerLine;
// Number of lines per page.
int 1inesPerPage;
// rhe lines after they have been broken so they fit within charsPerline.
Vector broken! ines;
// This method calculates and sets up all the fields above
// based on the metrics in g.
void prepareLayoutValues(Graphics g) {
Dimension pageSize;
int res;
Printjob
java.awt
if (g instanceof PrintGraphics) {
Printlob pj - ((PrintGraphics)g).getPrintJob();
res - pj.getPageResolution();
pageSize «. pj .getPageDimensionO ;
// getPageDimensionO does not return the correct result.
// The following is a workaround.
res = getToolkitO .getScreenResolution();
pageSize - new Dimension((int)(8.5 * res), 11 * res);
} else {
res - getToolкit().getScreenResolution();
pageSize ~ new Dimension((int)(8.5 " res), 11 •• res);
}
pageMargin = (int)(.75 * res);
pageSize - new Dimension(pageSize.height-pageMargin,
pageSi ze.width-pageMargin):
// Reserve space for the header.
FontMetrics fm = g.getFontMetrics(headerFont);
pageRect = new Rectangle(0, 0, pageSize.width/2, pageSize.height);
boxRect = inset(pageRect, margin, 2"fm.getHeight(), margin, 0);
listingRect - inset(boxRect. margin, margin, margin, margin);
/7 Set up listing font.
fm = g.qetFontMetrics(font);
int Ipp = 1istingRect.height/fm.getHeight();
int cpp - listingRect.width/fm.charWidth(*M');
// The metrics have changed so recompute the broken lines.
if (Ipp 1= linesPerPage I! cpp 1- charsPerLine) {
brokenLines = new VectorO;
for (int i-0; i<1ines.size(); i-t-+) {
String s = (String)lines.elementAt(i);
while (s.lengthO > cpp) {
brokenLi nes.addElement(s.substring(0, cpp) /’♦”);
s - s.substring(cpp);
}
brokenli nes.addElement(s);
}
linesPerPage = Ipp;
charsPerLine - cpp;
}
1
Rectangle inset(Rectangle r, int left, int top, int right, int bottom)
Rectangle s = new Rectangle(r);
s.x += left;
s.y += top;
s.width left+right;
s. hei ght = top+bottorr;
return s;
}
}
1210
Printjob
end()
java.awt
end()
— _ — -
PURPOSE-, Completes the print job.
SYNTAX public abstract void endO
DESCRII'I EON On some systems, the printer may not start printing pages until this method is called. After this method is called, this object can no longer be used. At present, there is no way to abort a print job once the print job object has- been created.
EXAM PE.E; See the class example.
finalizeO
purpose: Completes lhe print job.
SYNTAX public void finalizeO
DESCREP Fl ON This method is not typically called directly. Use end() instead. This method is normally called by the garbage collector when there arc no more references to this print job object. When this method is called, any remaining pages that have not yet printed will be printed.
see: Al.SO end().
getGraphicsO
plrixjse: Creates a graphics context for painting on a primed page.
SYNTAX public abstract Graphics getGraphicsO
DESCRIPIION Anything that is drawn on the returned graphics context will appear on the printed page. To determine the printable area on the graphics context, use getPageDimensionO- When a page is completed, Graph! cs. di sposeO should be called in order for the page lo be printed. Whenever a new' page is needed, this method must be called again to obtain a new graphics context. In fact, it is not necessary to dispose of a graphics con- text before creating a new one. This allows pages to be generated concurrently. The pages are ordered by when the graphics contexts are created, not by when dispose() is called. For example, if getGraphicsO is called twice and the second graphics context is disposed of before the first, lhe page associated with the first graphics context will still be printed first (when it is disposed of).
Printjob
getGraphics()
java.awt
Note.'. In Java 1.1.2, creating multiple graphics contexts docs not work on all
platforms. At present, it is safer to dispose of one graphics context before cre-
ating another.
RETURNS
SEE ALSO
EXAM RLE
A non-nul 1 graphics context that is a subclass of Pri ntGraphi cs.
PrintGraphics.
This example demonstrates the steps needed to
print an image and string centered on a sheet
of paper. See Figure 306.
It is necessary to wait until all of the pixels in
the image have been loaded before printing
can occur. This program uses the media tracker
class to force all of the pixels to be loaded.
Since the media tracker requires a component
to do its work, a simple component, called
ImageReader, is defined for the media tracker.
FIGI RE 30b: Printing an
Image and a String.
Note: In Java 1.1.2, the getPageDi mens! on О
method returns incorrect results. The
workaround is to determine a page size by
applying the screen resolution on an 8.5-x-l 1-inch sheet of paper. However,
most printers cannot print in all of this area. At present, there is no means to
determine the exact size of the printable area, so we simply guess and reduce
the area's width and height by three-fourths of an inch.
import java.awt.*;
import java.util.*;
w
X
Y
z
class Main {
public static void main(String[] args) {
if (args.length ’= 1) {
System,err.println("Usage: java Main <image file>”);
System.exit(l);
}
// Get the image.
Image image ~ new ImageReader(args[0]).image;
// Get the print job object.
PrintJob pj =
Toolkit.getDefaultToolkit(),getPrintlob(null, ’‘Title1', null);
if (pj null) {
System,err. pri ntl nC’The print request was cancelled.''):
System.exit(l);
}
// Get the pixel dimensions of the page.
Dimension d = pj.getPageDimension();
T
1212
java.awt
Printjob
getGraphicsO
// The above is currently not working in Java 1.1.2.
// The following is a workaround. Given the screen resolution,
// determine pixel size of 8.5x11 inch sheet of paper.
int res = Tool ki t. getDefaul tToolkitO .getScreenResol utionQ ;
d = new Dimension((int)(res * 8.5), (int)(res * 11));
// Reduce the dimension of the page due to margins around
// the page.
d.width -= (int)(res * ,75/*in*/);
d.height -« (int)(res * .75/*in*/);
// Get graphics context for first page.
Graphics g = pj .getGraphicsO;
// Paint the image.
g.drawlmage(image, (d.width-image.getWidth(nul l))/2,
d.height/2-image.getHeight(null), nul1);
// Set up the string and font.
String msg = "\u5496\u5561?";
g.setFont(new Font(”Serif", Font.PLAIN, 48));
FontMetrics fm = g.getFontMetrics();
// Draw the string in the center.
g.drawstring(msg, (d.width-fm.stringWidth(msg))/2,
d. heigh t/2+fm. getAscentO) ;
g.di spose();
// Start printing.
pj.endO;
System.exi t(0);
}
}
class ImageReader extends Component {
Image image;
ImageReader(String filename) {
image = getToolkitO.getImage(fi1 ename);
MediaTracker tracker = new MediaTracker(this);
try {
tracker,addlmage(image, 0);
tracker.waitForAll (0);
} catch (Exception e) {
e.printStackTraceO ;
У
Printjob
getPageDimensiont)
java.awt
getPageDimensionO
/X PURPOSE. SYNTAX DES(-RIPTION Retrieves lhe dimensions of the page in pixels. public abstract Dimension getPageDimensionO This method retrieves the printable dimension of a page in pixels. Any paint-
в ing done in this area will appear on the page: any painting outside this area
c D might not appear on the page. The dimensions returned are always in portrait mode, regardless of what orien- tation the user chose.
f: Note: In Java 1.1.2, this method returns incorrect results. See the class descrip-
г tion for more details on how to work around this bug.
G REIT RNS lhe non-null pixel dimensions of a page.
H EXAMPLE See lhe class example.
j
к
L
M
N
О
Q
R
S
1
I.
V
W
X
Y
Z
getPageResolution()
pi rpose Retrieves the resolution of the printed page in pixels per inch.
svnia.x public abstract int getPageReso1ution()
description This \alue is used to determine the exact pixel dimensions of the printed page. :
For example, fora З-х-5-inch sheet of paper, lhe pixel width would be 3*res-
olution and the pixel height would be 5*resol ution.
reti rns The non-negative resolution of the printed page in pixels per inch.
ex am pt.e See the class example.
lastPageFirstO
purpose: Determines if pages should be printed backwards.
syntax public abstract boolean lastPageFirstO
description When a printer prints paper such that new pages are stacked face up on top of
old pages, the pages need lo be printed backwards. Otherwise, lhe slack of
pages will be in lhe wrong order. For such printers, this method returns true, j
Note: In Java 1.1.2, this method might not return the correct results.
hei i rns true if the last page will appear on top of a printed stack: false otherwise.
ex vmpi i See the class example.
1214
java.beans
PropertyChangeEvent
<iv<i . AWTr vi*.'.’ qJ|
Syntax
public class PropertyChangeEvent extends Eventobject
Description
A properly change event is fired by a bean when one of its hound or constrained properties is
changed.
Bound Properties
FIGURE 307: Bound Property Event Flow.
A bound property is any bean property that, when modified, fires a property change event to
notify any property change listeners (see PropertyChangeLi stener) of the change. See Fig-
ure 307. Property change listeners cannot listen for changes to a particular bound properly in a
bean; they will receive property change events when any bound property in the bean is modi-
fied. However, the property change event sometimes contains information about which prop-
erty was modified.
PropertyChangeEvent
java.beans
Constrained Properties
FIGURE 308: Constrained Property Event Flow.
И Л constrained property is similar to a bound property, except that just before the property
j value is actually modified, the bean fires a property change event to notify vetoable change lis-
teners of the requested change. Any vetoable change listener can veto the requested change,
J thereby canceling the change. If no listener vetoes the change, the properly value is changed
К (see VetoableChangeLi stener for more details). At this point, if the property is also bound,
! a property change event is fired to the property change listeners. See Figure 30X.
Note that although there are two kinds of listeners property change listeners and veto*
M able change listeners- both use PropertyChangeEvent to notify their listeners.
Listening for Property Change Events
° Any bean with a bound properly must provide both an addPropertyChangeLi stenerO and
a removePropertyChangeLi stenerO method so that objects can listen for these events. See
PropertyChangeLi stener and PropertyChangeSupport for more details. The event is '
delivered to the listeners by a call to each listener’s propertyChangeO method.
R Any bean with a constrained property must provide both an addVetoabl eChange Lis-
$ tenerO and a removeVetoableChangeListener() method so that objects can listen for *
these events. See VetoableChangeListener and VetoableChangeSupport for more
1 details. The event is delivered to listeners by a call to each listener’s vetoableChangef)
U method.
V
Property Name
W A property change event includes the name of the properly that changed. The property name
X can be null, which means that many properties have changed and that the listener should j
retrieve all relevant values from lhe bean. See the following “Multichange Event” section for
Y more details.
1216
java.beans
Property Ch an geE vent
Old and New Values
The event includes the old and new values of the changed property. The values have the type
Object, so if the value is actually a primitive type, it must be contained in a wrapper. For
example, a bool ean needs to be wrapped in a Bool ean object.
Before a property change event is fired, a check should be made to ensure that the new
value is different from the old value. The recommended way to check this is to first compare
references and then use the Object, equal s() method.
Multichange Event
In most cases, one property change event is Fired for each bound or constrained property that
changes. However, when many properties have been changed at one time, a bean may reduce
the number of fired events by firing only one event. In this case, the property name, the old
value, and the new value of the event must all be nul 1.
Care must be taken when using this feature of property change events. Since the listeners
have no way of knowing which properties changed, they must get every bean property value in
which they are interested. This flurry of “gets" may result in more overhead than the savings in
fired events.
Propagation Id
The propagation id property of a property change event is reserved for future use. Its only
requirement is that if a listener receives a property change event and then proceeds to forward
the same event or a derived version, the propagation ids of both events must be the same.
MBffiER SUMMARY
Constructor PropertyChangeEventО Constructs a new PropertyChangeEvent instance.
Value Methods getNewValue() getOldValueO Retrieves the changed property 's new value. Retrieves the changed property 's old value.
Name Method getPropertyNameO Retrieves the name of the changed properly.
Propagation Id Methods getPropagati onld() setPropagati onld() i i Reserved for future use. j Reserved for future use. j
See Also
PropertyChangeListener, PropertyChangeSupport, VetoableChangelistener.
Property C hangeEvent
java, beans
Example
This example demonstrates both an object that fires property change events (because a bound
property changed) and one that listens for these events.
This example implements an invisible bean that has one bound property: "price," When
A the bean is created» it creates a thread that occasionally changes its price. When the price
R changes» the bean fires a property change event to its listeners. The bean uses Property-
ChangeSupport to implement the property change event listeners list.
C Lhe Mai n object creates the bean and then listens for property change events. Whenever
D an event occurs. Mai n prints out the price difference.
E
Г
G
H
1
J
К
I.
M
N
Q
R
S
T
U
V
w
X
Y
Z
import java.awt.';
import java. beans.;
class Main implements PropertyChangeListener {
Main() {
Bean bean = null;
try {
// Create the bean.
bean = (Bean)Beans.instantiate(Main.cl ass.getClassloader(), "Bean"):
} catch (Exception e) {
e.pri ntStackT raceО;
}
bean.addPropertyChangeLi stener(thi s);
}
public void propertyChange(PropertyChangebvent evt) {
float pl - ((Hoat)evt.getOldValue()) .floatValueO ;
float p2 ((Float)evt .getNewValueO).floatValue();
// Only show two digits after decimal point,
float diff = Math. round(Cp2-pl) 100)/100.0f;
System.out.pr i nt(evt.got Prope rtyName());
if (p2 > pl) {
System.out.println(" increase by " * diff);
} else {
System.out.print 1n(" decrease by " + -diff);
}
}
public static void main(String args[]) {
new Main();
}
}
public class Bean implements Runnable {
float price = 1.49f;
// Constructor
public Bean() {
(new Thread(this)).start();
}
// The price is a bound property,
public float getPriceQ {
1218
PropertyChangeEvent
getNew Valued
java.beans
return price;
}
public void setPrice(float newPrice) {
float oldPrice = price;
price - newPrice;
pceLi steners.fi rePropertyChange("price",
new Float(oldPrice), new Float(newPrice));
}
// Create the listener list.
PropertyChangeSupport pceListeners -
new PropertyChangeSupport(this);
// The listener list wrapper methods.
public synchronized void addPropertyChangelistener(
PropertyChangeListener 1) {
pceListeners.addPropertyChangeListener(l);
}
// removePropertyChangel i stenerO method omitted...
public void run() {
try {
while (true) {
// Change price up or down by .50.
setPrice(Math.max(1.0f, price * .5f - (float)Math. randomO));
// Sleep for a random amount of time.
Thread. sleep(Math. round(Math. randomO * 5000));
}
} catch (Exception e) {
e.printStackTraceO;
}
}
}
Output
price decrease by 0.35
price increase by 0.01
price increase by 0.38
price increase by 0.37
price decrease by 0.18
price decrease by 0.38
price increase by 0.48
getNew Val ue()
Pl’RPOSB Retrieves the changed property’s new value.
syntax public Object getNewValue()
description If the new value and the event’s property name are null, this event is a multi-
change event. See the class description fur more details.
PropertyChangeEvent
gctOldValue()
java.beans
RETURNS Phe changed property's possibly null new \alue.
EXAMPLE See the class example.
A getOldValue()
В C PURPOSE Retrieves the changed property's old value.
D SYNTAX public Object getOldValue()
E DESCRIPTION If the old value and the event's property name are nul 1. this event is a niulii- change event. See the class description for more details.
F RETURNS l he changed property's possibly null old \alue.
G H EXAMPLE See the class example.
I J getPropagationldt)
К PURPOSE Fhe propagation property is reserved for f uture use.
L SYNTAX public Object getPropagationId()
M DESCRIPTION This property's only requirement is that if a listener receives a property change
N event and then proceeds to forward the same event or a derived version, the
propagation ids of both events must be rhe same.
о RETURNS The event's propagation id.
Q R getProperty Name()
S PURPOSE Retrieves lhe name of the changed property.
T SYNTAX public String getPropertyNameO
и DESCRIPTION If the property name is null, this event is a multichange event. See the class
V description for more details.
w RETURNS The possibly null name of the changed properly. May be null if multiple
X EXAMPLE properties have changed. See the class example.
Z
1220
Property C h angeE vent
Property ChangeE ven t()
java.beans
PropertyChangeEventO
purpose Constructs a new Propertychange Eve nt instance.
syntax public PropertyChangeEvent(Object source, String propertyName,
Object oldValue, Object newValue)
description This constructor creates a property change event with source as the object
that fires lhe event. The propertyName parameter may be null, which indi-
cates that this is a mullichange event. In that case, then oldValue and
newValue must also he null. See the class description for more details.
PARAML IFRS
newValue The possibly null new value of the changed property.
oldValue The possibly null old value of lhe changed property.
propertyName
The possibly null name of the changed property
source The non-nul 1 object that is firing this property change event.
example This example fragment demonstrates what typical(y happens before and after a
property change event is created. I he values should be checked for equality by
first comparing references and then using the Object.equals() method. If
the values are equal, the event is not fired.
After the event is created, it should be distributed to all listeners.
A bean does not typically have lo create property change events. The function-
ality of maintaining a listener list, creating a property change event, and dis-
tributing that event to the listeners is provided by PropertyChangeSupport.
See PropertyChangeSupport for more details.
public void firePropertyChange(Object source,
String propertyName,
Object oldValue, Object newValue) {
// Check if the values are different before firing an event,
if (oldValue null && oldValue.equals(newValue)) {
return;
}
PropertyChangeEvent evt = new PropertyChangeEvent(
source, propertyName, oldValue, newValue);
// Now distribute the event to all its listeners...
1
java.beans
PropertyChangeEvent
set Propagation I d( )
A
В
C
D
k
F
setPropagationld ()
purpose The propagation property is reserved for future use.
syntax public void setPropagation!d(Object propagationld)
description This property's only requirement is that if a listener receives a property change
event and then proceeds to forward the same e\ent or a derived version, the
propagation ids of both events must be the same.
PARAMETERS
propagationld
rhe event's propagation id.
1222
java.beans
Property ChangeLi stener
Syntax
public interface PropertyChangeListener extends EventListener
Description
When a bound property in a
bean is changed, the bean will
fire a property change event
to notify listeners of the
change. See Figure 309. See
Prope rtyChangeEvent for
more details. To listen for
these events, you must define
an object that implements the
method in this interface and
FIGI RE 309: Bound Property Event Flow.
then register the object as a
listener by calling the bean’s
addPropertyChangel i stener Q method.
java.beans
Property C han ge L isten e r
propertyChangeO
Extra Events
When a listener is removed from a bean's listener list, ii should be prepared to receive a few
more property change events. Whether a listener will receive the extra events depends on how
the bean distributes events. In particular, a bean has the option of using a copy of the listener
A list while delivering events. И the listener is removed while an event is being delivered, it is
removed from the main list but nor from the copy. Since the listener is still in the copied list, it
may receive the event.
C
° Гм ember summary
i: I------------------------------------------------------------
। Event Callback Method
f propertyChangeO C?alled when a bean's bound property has changed.
G ' '
H
See Also
J Bean, java.util.FventListener, PropertyChangeEvent.
К
Example
See the PropertyChangeEvent class example.
M
property Changet)
pi rposh Called when a bean's bound property has changed.
SYNtAX void propertyChange(PropertyChangeb.vent evt)
description This method is called when the source bean fires a property change event after
a bound property is changed. See PropertyChangeEvent for details.
Phis method may be called a few more times even after the listener is removed
from the bean's listener list. See the class description for details.
PARAMETERS
evt A non-null properly change event.
example See the PropertyChangeEvent class example.
1224
java.beans
PropertyChangeSupport
j
Syntax
public class PropertyChangeSupport implements Serializable
Description
Any bean that has bound properties must be able to deliver property change events (see Prop-
ertyChangeEvent). This involves maintaining a list of property change event listeners and
delivering events to these listeners. This class can be used by a bean to maintain the listener
list and to deliver the events.
There are two ways a bean can use this class. First, it can have the bean extend this class.
This is not typical, since it prevents the bean from inheriting other useful classes, such as Com-
ponent. The second, and typical way, is for the bean to create an instance of this class and pro-
vide wrapper methods for addPropertyChangeListenerO and removeProperty-
ChangeListenerO. These bean methods should simply call the methods in this class that
have the same name.
MEMBER SUMMARY
i Constructor PropertyChangeSupportO Constructs a new PropertyChangeSupport instance.
Listener Methods addPropertyChangeLi stenerO removePropertyChangeLi stenerO Adds a listener for receiving property change events. Stops a listener from receiving property change events.
Event Method f i rePropertyChangeO Delivers a property change event to the listeners.
See Also
java,awt-Component, java.io.Serializable, PropertyChangeEvent,
Prope rtyChangeLi stener.
PropertyChangeSupport
java.beans
A
В
C
D
II
F
G
H
I
.1
К
L
M
XI
()
Q
R
S
T
r
V
w
X
Y
z
Example
This example implements a simple bean that
maintains a price that is a floating-point value.
When the price changes, the propertx change
event listeners (if any) arc notified of the change.
Figure 310 shows lhe propertx sheet of lhe
Beanbox when this example bean is selected.
Notice lhe price field.
import java.awt.-;
import java.beans.-;
public class Bean extends Canvas {
float price = 1.49f;
// Constructor
public Bean() {
// A couple of calls to make the
setВас kg round(Color.pi nk);
setSize(50, 50);
}
ПСИ RE 310: PropertyChangeSupport.
bean visible.
// The price is a bound property.
public float getPriceO {
return price;
}
public void setPrice(f1 oat newPrice) {
float oldPrice = price;
price = newPrice;
pceLi steners.fi rePropertyChange("price",
new Fl oat(oldPrice), new Fl oat(newPrice));
}
// Create the listener list.
PropertyChangeSupport pceListeners -
new PropertyChangeSupport(thi s);
// The listener list wrapper methods.
public synchronized void addPropertyChangeListener(
PropertyChangeListener 1) {
pceLi steners.addPropertyChangeListenerfl);
}
public synchronized void removePropertyChangeListener(
PropertyChangeListener T) {
pceLi steners.removePropertyChangeL i st ener (1);
}
}
/••
manifest.txt file:
Name: Bean.cl ass
]ava-Bean: True
jar command:
jar cfm bean.jar manifest.txt Bean.class
"7
1226
java.beans PropertyChangeSupport add Propert у Change IJ stene r()
addPropertyChangeListener()
purpose: Adds a listener for receiving property change events.
SYNTAX public synchronized void addPropertyChangeListener(PropertyChangelistener listener)
descrip i ion This method adds listener io the listener list. The method does not check if listener has already been added, so a listener can be added to the list more than once.
PARAMETERS 1istener A non-null property change event listener
se-:f also removePropertyChangel istenerQ.
EXAMPI F See the class example.
firePropertyChange()
PURPOSI-, Delivers a property change event to the listeners.
SYNTAX public void firePropertyChange(String propertyName, Object oldValue, Object newValue)
DESCRIP1ION This method creates a new property change event and delivers it to all listen ers. Listeners should not throw any exceptions. An exception that is thrown is consider a programming error. This method first checks if oldValue and newValue are equal. If they are. the method call is ignored. I he two values arc equal if oldValue != null && oldValue.equal sfnewValue). If oldValue is not equal to newValue. a new property change event is created with the values propertyName. oldVal ue. and newValue. The event's source is the one that was used when creating this class. This new event is delivered to each of the listeners. Ihe parameter propertyName can be null, which indicates that this is a mul- tichange event (see PropertyChangeEvent for details). In this case. old- Value and newValue will also be null.
PARAMEJI RS newValue oldValue Ihe possibly null new value of the property. The possibly null old value of the property.
propertyNameA possibly null property name.
EXAMPLE-. See the class example.
java.beans
Prope rty Ch angeSupport
PropertyChangeSupportO
PropertyChangeSupport!)
purpose Constructs a new PropertyChangeSupport instance.
syntax public PropertyChangeSupport(Object source)
Л description This method creates a new property change support object and records source
В as the object that will be firing property change events. The source object will
c always be included in every new property change event that is Tired by fi re-
PropertyChangeO- The source object cannot be changed.
D
PARAMETERS
E source The non-nul 1 bean that will be generating property change events.
see also fi rePropertyChangeC).
example See the class example.
removePropertyChangeListener()
purpose Stops a listener from receiving property change events.
symax public synchronized void
removePropertyChangeLi stener(PropertyChangeLi stener 1 i stener)
description This method removes 1 i stener from the listener list.
PARAMETERS
1i stener
SEE ALSO
EXAMPLE
The removed listener should be prepared to receive a few more property
change events. See PropertyChangeLi stener for more details.
Л non-nul 1 property change event listener.
addPropertyChangeLi stenerO.
See the class example.
T
U
v
w
X
Y
Z
1228
java.beans
Property Descriptor
Syntax
public class PropertyDescriptor extends FeatureDescriptor
Description
A property descriptor contains information about a
bean property» such as its localized name and
whether it is bound. There is one property descriptor
for each property. A bean's property descriptors can
be retrieved through the introspector by calling
Introspector.getBeanlnfoO.getProperty-
DescriptorsC).
For Bean Editors Only
The information contained in a property descriptor
is meant for programs such as bean editors (pro-
grams that help connect together beans into an
application). It is not used by the bean itself. These
and other descriptors essentially help a bean editor
to construct a meaningful user interface for editing
the bean. When the bean is actually running in an
application, the property descriptors are never used.
Bean Editor И
Introspector
Explicit
Descriptors
Implicit
Descriptors
Bean
.. (P
Bean Descriptor
Event Set Descriptors
Method Descriptors
Parameter Descriptors
Property Descriptors
Bean-Info
FIGI! RE 311: Property Descriptor.
Implicit and Explicit Property Descriptors
When retrieving the property descriptors, the introspector first looks in the bean's bean-info
(see Beaninfo) for any property descriptors that the bean has explicitly supplied. These are
called explicit property descriptors. If none are found, the introspector must use introspection
Property Descriptor
java.beans
on the bean to discover all the bean’s properties and then create implicit property descriptors
for the properties. See Figure 311. Implicit property descriptors are given default values for
some of the property descriptor attributes. Table 22 shows the attributes of a property descrip-
tor and the default values for implicit property descriptors.
A
В Attribute Contents Default Value
c Bound true if the property is bound. false.n
D Constrained true if the property is constrained. false.b
F- Property type I he Cl ass object of the property The Cl ass object of the
p type. property type.
Read method The Method object of the property's The Method object of the
G read accessor method. property's read accessor
H method.
Write method The Method object of the property's The Method object of the
1 write accessor method. property's write accessor
J method.
IZ Property editor The Class object of the property's null.
lx class property editor.
1. Name The property's nonlocalized name. The property's nonlocalized
M name.
N Display name The property's localized name. I'he property’s non localized
name.
() Short description A localized description of the prop- The property's non localized
erty. name.
Expert true if the property is considered for fal se.
Q use by experts only
R Hidden true if the property is meant to be fal se.
used by a tool: fal seif meant to
S T he used by a person.
C’
a.
TABLE 22: Property Descriptor Attributes.
I f ihc in inspector discovers that the bean fires the prupenv change event isee PropertyChangeEvent).
then ihe bound attribute for implicit property descriptors is .set to true.
If the introspector discovers that the property's indexed or non indexed write accessor methods throws
PropertyVetoExcepti on (see PropertyVetoException). (hen the constrained attribute tor the
property will be true.
V
b.
w
X
z
1230
java, bean s Property Desc ri p t or
Accessor Method, Signature Conventions
The bean specification defines conventions for the signatures of property read and write acces-
sor methods. These conventions serve two purposes.
1. They makes the bean's API easier for a programmer to read. That is. it's easy io see which
methods are accessor methods and which are not.
2. They enable the introspector to discover a bean's properties and create implicit property
descriptors. In other words, the introspector looks at the entire list of a bean s public
methods. When a method is found that matches the accessor method signature conven-
tion, the introspector assumes that it must be an accessor method. Prom the signature of
the accessor method, it can deduce the name and type of the property.
For example, if the name of a property is PropertyName and its type is PropertyType, the
convention of a read accessor method signature is
public PropertyType getCapPropertyNameO
where CapPropertyName is the property name, with the first character capitalized. The con-
vention of a write accessor method signature is
public void setCapPropertyName(PropertyType')
If PropertyType is boolean, then the read method can be replaced or complemented by a
read accessor with the signature
public PropertyType isCapPropertyNameO
For example, if the property name is 'Toasted" and the property type is boolean, then the set
of accessor methods is
public boolean isRoastedO
public boolean getRoastedO
public void setRoastedfboolean r)
When the read method is not explicitly specified and both "is" and "get" methods are avail-
able, lhe 4s" read method is used. If only a read accessor method is found, the property is
assumed to be read-only. If only a write accessor method is found, the property is assumed to
be write-only.
MEMBER SUMMARY
_____—_______
Constructor PropertyDescriptorО Constructs a PropertyDescriptor instance. 1
Bound Property Methods i sBoundQ setBound() 1 Determines if this properly is bound. Specifies whether the property is bound. Continued 1
PropertyDescriptor
ja\a.beans
A
В
C
D
E
F
Ci
H
I
J
К
L
M
N
()
Q
R
S
I
H
V
w
X
Y
Z
MEMBER SUMMARY
Constrained Property Methods
1sConstrai ned()
setConstrai ned()
Property Type Method
getPropertyTypeО
Property Accessor Methods
getReadMethodO
getWri teMethodQ
Property Editor Class Methods
getPropertyEdi torClass()
setPropertyEdi torClass О
Determines it* this properly is constrained.
Specifies whether lhe property is constrained.
Retrieves lhe property \ ty pe.
Retrieves the properly \ read accessor method.
Retrieves lhe property 's write accessor method.
Retrieves the property's property editorclass.
Sets a propeily editor for lhe properly.
See Also
BeanInfo.getPropertyDescri ptors(), java.1ang.Class, PropertyEdi tor.
Example
This example implements a bean that
has a single property : “price.” The bean
displays the current value of price in a
label. See Figure 312.. The price prop-
erty is both bound and constrained, so
the bean w ill fire both \ doable and reg-
ular property change events when the
price is changed.
This example also includes a lis-
F4fr E-Л Vfe?w Hdp
FIGI RE 312: “price” Property Sheet.
tener. BeanPri ceLi stener. for that bean. The listener listens for both v doable properly
change events and regular property change events, l he listener is setup to veto change prices
increases that exceed 50 cents.
To run this example, you need to hook up lhe listener io lhe bean. First, in lhe Beanhox.
select the bean and then select Edi t->Events->vetoabl eChange->vetoableChange. Next,
click lhe bean listener and select Edit->Events->propertyChange->propertyChange.
Finally, click the bean listener again. T he bean listener is now registered for both events.
For other examples, sec any of the examples in the PropertyEditorSupport and
IndexedPropertyDescri ptor classes.
1232
java.beans
PropertyDescriptor
Nitre: The Bcanbox in the BDK 1.0apr97 requires that the bean and bean listener be in a
named package. When they are in an unnamed package, the Beanbox will not hook up the
bean listener to lhe bean.
classexample/Bean.java
package classexample;
import java.awt.*;
import java.beans.*;
public class Bean extends Panel {
float price = 1.49f;
Label 1 = new Label ('”'+price);
public BeanO {
add(l);
}
// The price is a bound and constrained property.
public float getPriceQ {
return price;
}
public void setPrice(float newPrice) {
float oldPrice - price;
try {
vceLi steners.f i reVetoableChange(”pri ce”,
new Float(oldPrice), new Float(newPrice));
// No vetos so update the price
price = newPrice;
pceListeners.fi rePropertyChange(“price",
new Float(oldPrice), new Float(newPrice));
} catch (PropertyVetoException e) {
// Don’t change the price
}
1 .setText(’"’+price);
}
// Create the vetoable property change listener list.
VetoableChangeSupport vceListeners =
new VetoableChangeSupport(this);
// The listener list wrapper methods.
public synchronized void addVetoableChangeListener(
VetoableChangeListener 1) {
vceLi steners.addVetoableChangel i stener(l);
}
public synchronized void removeVetoableChangeListener(
VetoableChangeListener 1) {
vceListeners.removeVetoableChangeLi stener(1);
}
// Create the property change listener list.
PropertyChangeSupport pceListeners =
new PropertyChangeSupport(this);
Property Descriptor
java.beans
// Ihe listener list wrapper methods,
public synchronized void addPropertyChangeListener(
PropertyChangeListener 1) {
pceL i steners.addPropertyChangeLi stener(1);
}
public synchronized void removePropertyChangeListener(
A PropertyChangeListener 1) {
pceLi steners.removePropertyChangeLi stener(1);
В }
}
С Л
mani fest. txt:
Г) Name: cl assexample/Bean.class
Java-Bean: True
E
Name: cl assexarr.pl e/BeanPri cel i stener.class
Java-Bean: True
jar command (Solaris):
G jar cfm bean.jar rrani fest. t xt cl assexample/* . с 1 ass
jar command (Windows):
H jar cfm bean.jar manifest.txt с 1 assexampl eV.class
V
1 classexample/BeanBeanlnfo.java
т package classexample;
К import java.beans."’;
। public class BeanBeanlnfo extends SimpleBeaninfo {
public PropertyDescriptor[] getPropertyDescriptorsO f
PropertyDescriptor pdf] = new PropertyDescriptor[1];
X tr> {
pd[0] = new PropertyDescriptor("price", Bean.class):
Q pd[0].setBound(true);
pd[0].setConstrained(true);
P
} catch (Exception e) {
e.printStackTraceO ;
return null ;
s >
classexample/BeanPriceListener.java
package classexample;
import java.awt.'’;
import java.beans V;
import java.uti1.*;
public class BeanPricel.istener implements PropertyChangeListener, Veto-
ableChangeListener {
Vector priceChangeLog = new VectorO;
// If the price difference is too high, veto it.
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
float oldPrice =- ((Float)evt .getOldValueO) . floatValueO ;
1234
java.beans
Prope rty I )esc r i pt or
gctPropcrly EdtlorClassf)
float newPrice = ((Fl oat)evt.getNewValue()).f1oatValue();
if (newPrice - oldPrice > .5f) {
throw(new PropertyVetoException(“Too Much1", evt)):
}
// Save the new price.
public void propertyChangeCPropertyChangeEvent evt) {
pri ceChangeLog.addElement(evt.getNewValue()):
}
}
getPropertyEditorClassf)
PCRPOSi. Retrieves the propertv \ propertv editor class.
SWT.W public Class getPropertyEditorClass()
DF.SCRIP I K)\
This method is typically called by a bean
editor when it needs to determine property
editors for the bean's properties. The
returned Class object, when instantiated,
will yield an object of type PropertyEdi -
tor. See PropertyEdi tor for more
details.
If the returned value is null, the bean edi-
tor will determine the type of the propertv
and then ask the properly editor manager if
it has a property editor for that type. See
PropertyEdi torManager tor more
details.
I Kit RE 313: Displaying Custom
Propertv Editors.
The propertv editor class for a propertv
descriptor can be set only bv a call to set-
PropertyEdi torClass().
Ri.it R\s A possibly null Class object for a propertv editor.
st t \i so setPropertyEdi torCl ass().
fa wifi I This example implements a program that uses the filename ot a class file con-
taining a bean to discover it' bean has any custom properly editors. It it does,
the program creates instances of them and displays them. Figure 31 ' shows the
example when run on the bean in the PropertyEditorSupport.getCus-
tomEditorQ example.
Property Descriptor
getPropertyEditorC)ass()
java.beans
This example uses the FileClassLoader class to load the bean from a file.
The source code for this class is in the Introspector class example.
A gridbag layout is used to lay out the custom property editors and their labels.
Main.java
л import java.awt.*;
import java.beans.*;
B import java.io.*;
import java.lang.reflect.*;
( import java.uti1. *;
import java.net.-v;
class Main {
public static void mai n(Stri ng[] args) {
if (args.length 1= 1) {
r System.err.println(”Usage: java Main <name of bean class file>");
z, System.exit(l);
G }
11 try {
// load the bean class and get the property descriptors.
// (See the Introspector class example for FileClassloader
// source code.)
J Class beanClass - FileClassLoader.load(args[0]);
Beaninfo beaninfo = Introspector.getBean!nfo(beanClass);
K PropertyDescriptor pds[] - beaninfo.getPropertyDescriptorsO;
( Frame frame = null;
for (int i=0; i<pds.length; i++) {
M PropertyEditor peditor - null;
Class peClass = pds[i].getPropertyEditorClass();
~ if (peClass 1= null) {
° try {
// Instatiate the custom editor
peditor = (PropertyEditor)peClass.newInstanceO;
} catch (Exception e) {
Q }
R }
if (peditor 1= null && peditor.supportsCustomEditorO) {
try {
° // Instantiate the bean.
Object bean - beanClass.newInstanceO;
1 Method getter = pds[i2.getReadMethodQ;
Object argumentsLJ { };
L peditor.setValue(getter,invoke(bean, arguments));
V // Create a frame for the custom editor,
if (frame null) {
w frame = new FrameC’getPropertyEditorClass Example”);
frame.setLayout(new GridBagLayout());
X }
addComp(frame, pds[i] .getNameO ,
Y peditor.getCustomEditor());
} catch (InvocationTargetException e) {
Z e.printStackTraceO;
} catch (InstantiationException e) {
e. printStackTraceO;
} catch (IllegalAccessException e) {
1236
java.beans
Property Desc riptor
getPropertyType()
e.pri ntStackTrace();
}
}
}
i f (frame ’= nul1) {
f name.pack();
frame. showO;
}
} catch (IntrospectionException e) {
e.printStackTraceO ;
}
}
static void addCompfContainer cont, String label. Component comp) {
GridBagLayout gbl =- (GridBagl ayout)cont.getLayoutO ;
GridBagConstraints c = new GridBagConstraintsO;
// Add label.
Label 1= new Label(label);
cont.add(l);
gbl.setConstraints(comp, c);
// Add component.
cont.add(comp);
c =₽ new GridBagConstraintsO;
c.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(comp, c);
}
}
getPropertyTy pe()
Pl’RPOSE Retrieves the property's type.
SYNTAX public Class getPropertyTypeO
DESCRIPTION The property's type is represented by a Class object of that type. For example, if the type is a String or an int, then this method returns java, lang. St ring, cl ass or int. class, respectively. If the property is an indexed property (see IndexedPropertyDescriptor) with no nonindexed accessor methods, this method returns null. The property’s type is determined in the constructor. See the property descrip- tor constructor for more details on how this is done.
RE-TERNS The possibly null Class object of the property’s type.
EXAMPLE See the Introspector class example.
PropertyDescriptor
gctRcadMethodO
java.beans
getReadMethodf)
PURPOSE Retrieves the property's read accessor method. public Method getReadMethodQ The property's read accessor method is used to read the propern value. h is
A SYNTAX DESCRIPTION
В typically called by the bean editor as the user edits the property value through a
c property editor (see PropertyEditor). The read accessor method does not
take any arguments. It returns an object of the same type as that returned by
D getPropertyType().
E The property's read accessor method is determined by the constructor. The
F method may have been specified in a bean-info or discovered through intro-
spection. Sec the constructor for more details.
If the property does not have a public read accessor method, this method
H returns null.
I RETURNS The possibly null read accessor method.
J SEE ALSO java.lang.reflect.Method, getPropertyTypeО, getWriteMethod(),
К IndexedPropertyDescri ptor.
I EXAMPLE This example demonstrates how to invoke the property's read accessor
I - method. The program loads a bean and its bean-info, if present. It then instan-
M tiates the bean. Finally, it iterates over the bean's list of properties and prints
N out the initial value of each one.
o Component beans are treated specially. This is because the property values for
a component are not accurate until the component’s peer is created. For the
peer to be created, the component is inserted into a frame and addNotifyO is
Q called on the frame.
R The creation of the frame causes various internal AWT threads to be created
that prevent the program from exiting at the end of the main О method. To
s exit, the program explicitly calls System.exit().
T This example uses the FileClassLoader class to load the bean from a file.
и The source code for FileClassLoader is in the Introspector class exam-
V ple.
Main.java
w import java.awt.*;
import java.beans.*;
X import j ava.io.*;
import java.lang.reflect.*;
Y import java.uti1.*;
z import java.net.*;
class Main {
public static void main(String[] args) {
if (args,length !-* 1) {
1238
java.beans
PropertyDescriptor
getReadMethodO
System.err.println("Usage: java Main <name of bean class filer*");
System.exi t(l);
}
try {
// Load the bean and get the bean info.
// (See the Introspector class example for
// FileClassLoader source code.)
Class beanClass - Гi1eClassLoader.load(args[0]);
Beaninfo beaninfo - Introspector.getBeanInfo(beanClass);
// Instantiate the bean.
Object bean - beanClass.newInstanceO;
// Components are treated specially.
if (Beans.islnstanceOf(bean, Component.class)) {
Frame frame - new FrameO;
frame.add((Component)bean);
frame. addNotifyO ;
}
// Now print each property and its value.
PropertyDescriptor pdsO - beaninfo.getPropertyDescri ptorsO ;
for Ont i=0; i<pds.length; i*-<-) {
Method reader - pdsLi] .getReadMethodO ;
Object[] arguments = {};
// Invoke the read accessor method.
Object value = reader.invoke(bean, arguments);
// Print the results.
pri nt(pds[i 1 . getNameO , 15);
System.out.pri ntln(value);
}
} catch (IntrospectionException e) {
e.pri ntStackT race();
} catch (IllegalAccessException e) {
e.printStackTraceO ;
} catch (InvocationTargetFxception e) {
e.printStackTraceO ;
} catch (InstantiationException e) {
e.printStackTraceO;
}
System.exit(0);
}
// Prints s and pads the string with Math.max(l, width-s.lengthQ) spaces,
static void print(String s, int width) {
System.out.pri nt(s);
for (int i-0; i<Math.max(l, (width~s.1ength())); i++) {
System.out.print(” ");
PropertyDescriptor
getWriteMethodO
java.beans
Output Here is the output of the program when run on the Our But ton demo bean that comes with ВIЖ l.0apr97:
enabled true
preferredSi ze java.awt.Dimension[width=44,height=231
A foreground java.awt .Color[r=0,g=r0Tb=0]
label press
R visible true
и background j ava. awt. Col or[ r=192 , g=192 , b=-192 J
C fontSi ze 12
font java.awt.Font[family-Di alog,name=Dialog,style^plai n,si ze=12j
[} name canvasO
largeFont Fa 1 se
E debug fal se
F mi n imumSize java.awt.Dimension[width=44,height=231
н
getWriteMethodO
I J PURPOSE SYNIAX Retrieves the property's write accessor method, public Method getWriteMethodO
К DESCRIPTION The property's write accessor method is used to modify the property value. It
L is typically called by the bean editor as the user edits the property value
M through a property editor (see PropertyEditor). The write accessor method
takes one argument and does not return any. The argument must be the same
N type as that of the argument returned by getPropertylypeQ.
() The property's write accessor method is determined by the constructor. The method may have been specified in a bean-info or discovered through intro- spection. See the constructor for more details.
Q If the property does not have a public write accessor method, this method
R returns null.
s RETI'RNS The possibly null write accessor method.
T SEI Al SO java. 1 ang. ref 1 ect.Method, getPropertyTypeQ , getReadMethodQ >
П IndexedPropertyDescri ptor.
EXAMPLE This example implements a program that loads a bean, instantiates it. finds all
V properties of the type Color, randomizes those colors, and finally serializes
w the bean:
X Main.java
import java.awt,*;
V import java.beans.*;
import j ava.io.*;
Z import java.lang, reflect.’';
import java.util.*;
import java.net.*;
1240
Property Descriptor
getVVritcMethodO
java.beans
class Main {
public static void main(String [] args) {
i f (args.length !- 2) {
System.err.pri ntln(
’’Usage: java Main <bean class file> coutput f i le> . ser") ;
System.exit(1) ;
}
if (!args[l].endsWith(".set")) {
System, err, pri ntl nC'Output file must end with .ser");
System.exit(l);
}
try {
// load the bean and get the bean-info.
// (See the Introspector class example for
// FileClassloader source code.)
Class beanClass = rileClassLoader.ioad(args[0]);
Beaninfo beaninfo = Introspector.getBeanlnfo(beanClass);
// Instantiate the bean.
Object bean = beanClass.newInstanceO;
// Find all color properties.
PropertyDescriptor pds[] beaninfo.getPropertyDescriptorsO ;
for (int i-0; i<pds.length; i+*) {
if (pds[i].getPropertyTypeQ == Color.class) {
// Create a random color.
Color color - new ColorfColor.HSBtoRGB(
(fl oat) Ma th. randomO , (f 1 oat) Ma th. random () ,
(float)Math. randomO));
// Get the write method.
Method writer = pdsfi] .getw’riteMethodO ;
// Invoke the write accessor method.
ObjectП arguments - {color};
writer.invoke(bean, arguments);
// Print the results.
System.out.printl n(pds[i] .getNameO + " + color);
}
}
// Serialize the bean.
java.io.FileOutputStream fos -
new java.io.FileOutputStream(args[1]);
java.io.ObjectOutput os -
new java.io.ObjectOutputStream(fos);
os.wri teObject(bean);
os.closeO;
} catch (TOFxception e) {
e.printStackTraceO ;
} catch (IntrospectionException e) {
e.printStackTraceO ;
} catch (Il legalAccessException e) {
e. printStackTraceO ;
} catch (InvocationTargetFxception e) {
e.pri ntStackT race();
} catch (Instantiationtxception e) {
e. pri ntStackTraceO ;
PropertyDescriptor
isBoundO
java.beans
}
System. exi t(0) ;
}
}
/-
command to run example:
java 'lain Bean.class random-color bean.ser
man i fext. txt:
Name: random-color-bean.ser
lava Bean: True
jar command:
jar cfm bean.jar manifest.txt A.ser
Bean.java
import java.awt.^;
public class Bean extends Canvas {
public BeanO {
sotSize(100, S0);
}
public void paint(Graphics g) {
g.fi1lOval(0, 0, getSize().width, getSize().height);
}
}
isBoundO
- - — — - — -
Pl'RP( )SL Determines if this property is bound.
SYMAX public boolean isBoundO
DE'SCRIPTIOX A bean property is bound if it fires a property change event at the time that the propertv value changes (as opposed to a constrained property, which fires a property change event when lhe property value is about to change). See Prop- ertyChangeEvent for more details. This method is typically called by a bean container to determine which of the bean s properties are bound. /\ bean container cannot determine by introspec- tion which properties are bound. If a bean wants to inform lhe bean container which properties are bound, it must create a property descriptor for each bound property, call setBound(true) on them, and publish lhe properly descriptors in the bean's bean-info descriptor (see Beaninfo).
RETl-R\S true if this is a bound property .
SEI: VLSI) EXAMPLE setBoundQ. See lhe Introspector class example.
1242
property uescnpior
KConstrainedO
java.beans
isConstrainedt)
purpose: Determines if this property is constrained.
SYNTAX public boolean isConstrained()
DESCRIPTION A bean property is constrained if it fires a vetoable property change event when the property value is about to change (as opposed to a bound property, which fires a property change event at the time that the property value is changed!. See PropertyChangeEvent and VetoableChangeSupport for more details. This method is typically called by a bean container to determine which of the bean’s properties are constrained. A bean container can determine by intro- spection which properties are constrained. In addition, a bean can inform the bean container of additional properties that are constrained. It does this by cre- ating a property descriptor for each and then calling setConstrai ned(true) on them. The bean can then publish these explicitly created property descrip- tors in the bean s bean-info descriptor (see Beaninfo).
RETURNS true if this is a constrained property.
SET: ALSO setCons trai nedQ.
LXAMPLI: See the Introspector class example.
Property Descriptor)
PURPOSE: Constructs a PropertyDescriptor instance.
SYNTAX public PropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException public PropertyDescriptorfString propertyName, Class beanClass, String readerName, String writerName) throws IntrospectionExcepti on public PropertyDescriptor(String propertyName, Method reader, Method writer) throws IntrospectionException
DESCRIPTION Property descriptors are either implicitly created by the introspector or explic- itly created by a bean. Sec the class description for more information. When a property descriptor is created, five attributes are initialized: • Property name • Class object ot the bean • Read accessor method • Write accessor method • Property type
Property Descriptor
PropertyDescriptor()
java.beans
В
c
n
F
Г
G
II
I
J
К
L
M
S
T
i;
V
w
X
Y
Z
All other attributes are given default values that can be changed by methods in
this class and in the FeatureDescriptor class. The default values for a prop-
erty descriptor are shown in Table 22.
The property type is not specified. Rather, it is determined by using reflection
to examine the read and write methods. Basically, the type returned by the read
method becomes the property type.
If reader and writer are specified, a check is made to ensure that the meth-
ods have the appropriate signatures. The signatures arc discussed in the class
description.
If readerName and wri terName are specified, retlection is used to look for
methods with these names. (Although they don't have to use the "is/get/set”
naming conventions, it is highly recommended that they do.) lhe method can
be in either the bean or one of its ancestors. Once these methods are found,
they are subject to the signature compatibility check as discussed in the class
description.
If the accessor methods are not specified, they are discovered using reflection
and the follow ing rules:
• l he first letter of the properly name is capitalized. For example, "roasted”
becomes "Roasted." For purposes here, the capitalized propen у name is
CapPropertyName.
• Reflection is used to look for a method named setCapPropertyName that
has the appropriate signature. The method can be in either the bean class or
one of its ancestors. If one is found, it becomes the write method and the
parameter type becomes the property type: otherwise. IntrospectionEx-
ception is thrown.
• If the property type is bool ean, retlection is used to look for a method
named i sCapPropertyName that has the appropriate signature. The
method can be in either the bean class or one of its ancestors. For example, if
"roasted" is the property name, (hen i sRoasted() is the read method. If a
method is found, it becomes the read method.
♦ Otherwise, reflection is used to look for a method named getCapProper- ;
tyName that has the appropriate signature. The method can be in either the j
bean class or one of its ancestors. If one is found, it becomes the read
method: otherwise, IntrospectionException is thrown.
PARAMETERS
beanCl ass The bean's Cl ass object.
propertyNameThe non-null nonlocalized name of the property.
reader The possibly null Method object of the property's read accessor method.
readerName The possibly nul 1 name of the property's read accessor method.
wri ter The possibly nul 1 Method object of the property 's write accessor method,
wri terName The possibly nul 1 name of lhe property's write accessor method.
1244
java.beans
PropertyDescriptor
Property Descriptor)
EXCEPTIONS
IntrospectionException
If the signatures of the read and write methods are incompatible. For example,
the type returned by reader does not match what is accepted by writer.
example This example demonstrates how to use the three different forms of the con-
structor. The bean has three integer parameters: property!. property2. and
property}. The bean-info class. BeanBeanlnfo. creates three property
descriptors, one for each of the three properties, using the three different con-
structors.
Bean.java
public class Bean {
int propertyl;
int property2;
int property};
public int getPropertyl() {
return propertyl;
}
public void setPropertyl(int v) {
propertyl = v;
}
public int getProperty2() {
return property2;
}
public void setProperty2(int v) {
property? - v;
}
public int getProperty3() {
return property};
}
public void setProperty3(int v) {
property} = v;
}
}
/*
manifest.txt:
Name: Bean.cl ass
Java Bean: True
jar command:
jar cfm bean.jar manifest.txt *.class
V
BeanBeanlnfo.java
import java.beans.*;
import java.lang.reflect;
public class BeanBeanlnfo extends SimpleBeaninfo {
public PropertyDescriptor[] getPropertyDescriptorsO {
PropertyDescriptor pd[] new PropertyDescriptor[31;
try {
// The getter and setter methods are derived from the property name.
java.beans
Prope rty Desc r i p t or
set Bou ndO
pd [0] T- new PropertyDescri ptor("propertyl", Bean.class);
// The names of the getter and setter methods are supplied,
pdfll ~ new PropertyDescriptor(,’property2“, Bean.class,
"getPropertyZ’', ”setProperty2M);
A // The Method objects of the getter and setter methods are supplied.
Classf] getArgs = {};
В
// The getter method must not take any parameters.
C Method getter - Bean.cl ass.getVethodC'getPropertyS”, getArgs);
D // The setter must take one parameter and it must have the
// same type as returned by the getter method.
E Classf] setArgs - {getter .getReturnTypeO];
Method setter - Bean.cl ass.getMethod(MsetProperty3", setArgs);
F pd["2^ - new PropertyDescriptor Cproperty3'’, getter, setter);
G return pd;
} catch (NoSuchMethodException e) {
H e.printStackTraceO;
} catch (IntrospectionException e) {
I e.printStackTraceO;
}
J return nul1 ;
}
К }
M
setBoundO
PCRPOSI-
SXN I -XX
PL'SCRIPTIOX
XV
X
Y
Z
PARAMI I FRS
bound
SEE .Al SO
EXAMPLE.
T
I
Specifies whether lhe property is bound.
public void setBound(boolean bound)
A bean property is bound if it fires a property change event at the time that the
property value changes (as opposed to a constrained property, which fires a
property change ex ent when the property value is about to change). See Prop-
ertychange Fvent for more details.
A bean container cannot determine by introspection which properties are
bound. If a bean wants to inform the bean container which properties are
bound, it must create a property descriptor for each bound property, call set-
Bound (true) on them, and publish the property descriptors in the bean’s
bean-info descriptor (see Beaninfo).
true if this is a bound property: false otherwise.
getBound().
See the class example.
1246
java.beans PropertyDescriptor
setConstrainedO
setConst rainedO
purpose Specifics whether the property is constrained.
syntax public void setConstrained(boolean constrained)
description A bean property is constrained if it fires a vetoable property change event
when the property value is about to change (as opposed to a bound property,
which fires a property change event at the time that the properly value is
changed). See PropertyChangeEvent and VetoableChangeSupport for
more details.
Л bean container can determine by introspection which properties are con-
strained. In addition, a bean can inform the bean container of additional prop-
erties that are constrained. It does this by creating a property descriptor for
each and then calling setConstrained(true) on them. The bean can then
publish these explicitly created property descriptors in the bean’s bean-info
descriptor (see Beaninfo).
PARAMETERS
constrained true if this is a constrained property; fal se otherwise.
see al so getConstrai ned().
example Sec the class example.
setProperty Editor Class()
purpose Sets a property editor for the property.
syntax public vold setPropertyEditorClass(Class propertyEditorClass)
description A property editor is essentially a user interface for editing a bean property. A
bean editor provides property editors for many common property types. How-
ever, if the property type is not one of these types, you must supply your own
properly editor. See PropertyEdi tor for complete details on building prop-
erty editors.
This method is typically called in a bean-info while a property descriptor is
being set up. This method associates a property editor with the property.
PARAMETERS
propertyFdi torClass
lhe non-null property editor class.
exampi e See the class example or any of lhe examples in lhe PropertyEditorSupport
and IndexedPropertyDescriptor classes.
java.beans
PropertyEditor
(^PropertyEditor
В
c
D
E
F
G
H
1
J
К
L
M
N
()
Q
R
T
U
V
w
X
Y
Z
Syntax
public interface PropertyEditor
Description
A property editor is essential!} a user interface
for editing a bean pro pert} . The property must
have both a read and write accessor method.
Different property types require different prop-
erty editors. For example, in the case of a string
property, the string property editor might pro-
vide a text field for editing the siring. In the
case of a color, the color property editor might
provide knobs for controlling each of the
color's components. Figure 314 show s a few of
the property editors provided by the Beanbox.
Shown arc the property editors for the types
double, int. String, and boolean.
< Property Sheet
FIGURE 314: Property Editors Provided by
the Beanbox.
Properly editors are objects that arc created and used by a bean editor. They must imple-
ment the PropertyEditor interface and must have a public null constructor.
The Value
A property editor maintains a copy of the bean's property value. However, if the property type
is primitive, this value must be contained in the corresponding wrapper object. For example, if
the primitive type is boolean, the returned object will be a Boolean object.
'This value must be updated (via a call to setValueQ) whenever the user modifies the
value. For more details about how this is done, see the event flow discussion that follows.
One important note about this value is that when the user makes a modification, a new
object must be created to hold the new value. In other words, the current value object should
not be changed. This is because, for efficiency, the bean editor uses a quick reference compar-
ison to determine if a property value has changed. So. if the original value is modified rather
than copied and modified, the bean editor incorrectly assumes that the value has not changed,
since the references have not changed. (Efficiency is important because whenever one prop-
erty value changes, the bean editor must check every other property value in case they also
changed.)
1248
java.beans
PropertyEditor
Note: In the case of indexed properties (see IndexedPropertyDescriptor), it may be
very inefficient to clone a large array when only one element has changed. The bean specifica-
tion does not yet address this issue.
Locating Property Editors
When a bean editor edits a bean, it not only needs to determine the properties in the bean. It
also needs to find a property editor for each property to allow the user to edit it. There are two
places a bean editor can find a property editor for a property:
1. In the bean-info. The bean may have explicitly defined a property editor for the property.
If so, it would appear in die bean-info. See Beaninfo for more details.
2. In the property editor manager registry. If no property editor is defined for that property in
the bean-info, the bean editor then determines the property’s type and asks the property
editor manager if it has a property editor for that type. See PropertyEdi torManager for
more details.
If neither place yields a property editor, then the property cannot be edited.
Default Property Editors
The property editor manager provides property editors for a few types. The following types
have default property editors:
boolean
byte
short
int
long
float
double
java.lang.Stri ng
java.awt.Font
If the property type is not one of these types, you must supply your own property editor.
Three Kinds of Property Editors
In most cases, it is convenient to think of a property editor as an AWT component designed for
editing a bean property. However, lhe truth is that the PropertyEdi tor class is not a compo-
nent. Rather, it contains information from which a bean editor can construct a component to
edit the property. For example, suppose you have an "align” property that can have one of
three possible integer values with the names LEFT. CENTER, and RIGHT. When the bean editor
encounters the align property, it can see that the property is of type int. However, it has no
way of knowing that only three values are allowed and what the names of the these values are.
This information is provided by a property editor. With this information, a bean editor can con-
struct a component that lets the user choose one of those values, typically using a choice com-
ponent.
Property Editor java, beans
In short» the true purpose of a property editor is to help a bean editor construct a compo-
nent for editing a property. There are several ways by which it can do this, but in general, a
property editor falls into one of three kinds:
1. Property editors that convert property types to and from strings
л 2. Property editors that have tags
В 3. Property editors that support a custom editor
C Each kind of property editor is described later in this item.
There is no flag that identifies w ith what kind of property editor a bean editor is dealing.
Instead» the bean editor first checks to see if the property editor supports a custom editor (by
F calling supportsCustomEdi tor() described shortly). If it doesn't, the bean editor checks to
p see if the property editor has tags (by calling get Tags О ). If not. the bean editor assumes that
the property editor is the type that converts property types to and from strings.
H Property Editors That Convert Property Types To and From Strings
This kind of property editor takes the property value and converts it to a human-readable
string. It also must be able to reconvert a string into a valid property value, l or example, sup- ;
J pose the property is an integer IP address and you want the user to edit in dottedMriii# nota-
K tion. which has the form “byte. byte.byte, byte.” The property editor would have to provide
methods for converting a 32-bit IP address ю and from dotted string notation. More specific
L cally. it needs to implement the getAsTextO and setAsTextO methods.
M
Property Editors That Have Tags
SJ
Some properties have values that can be from only a small set ot values. I’he set ot four com-
() pass points is such a property. For such properties, a property editor can supply a set of tags by
overriding getTagsO and returning the lags. A tag is the name of one of the values. For
example, in the case of the compass points, there would be four tags: “north,'' “south.” “east,"
and “west.”
p When a bean editor detects this kind of property editor, it retrieves the set of tags and pre-
sents them to the user. Most bean editors typically use a Choi ce component to display the lags.
Unless the property is a string, the property editor must also implement getAsTextO and I
T setAsTextO to convert the lags to the native property type. For example, if the compass |
property were actually an integer, then getAsTextO and setAsTextO would have to con-
vert the tags to and from integer values.
V
w Property Editors Thai Support Custom Editors
When a property cannot be represented as a single string or as a set of tags, it is necessary to Я
X provide a custom editor. \ custom editor is a true AWT component. For example, a font is Я
Y made up of at least three parts: the font family, the font style. and the font si/e. Such a property»
z would be better edited with a special component rather than as a string. Figure 315 shows the I
Beanbox's two custom editors: color and font custom.
1250
java.beans
Property Editor
The bean editor is responsible for disposing of the custom editor. It does not inform the
custom editor when it is about to be disposed of. This means that if the custom editor wants to
'*bateh” lhe changes so that (he bean property is not updated immediately, the custom editor
must provide a button to allow lhe user to save the changes.
Unfortunately, at present, the
custom editor is not informed
before it is disposed of.
Note: lhe Beanbox in BDK
1.0apr97 requires that properly
editors that support custom editors
have a paintable area (see the fol-
lowing discussion). This may not
be required in other bean editors.
The Paintable Area
The paintable area of a properly
editor is some visible area on the
bean editor. It is used in conjunc-
tion with a custom editor and
allows a bean to give some visual
representation of the property
value. For example, for a color
property, the actual color could be
painted in the paintable area. Fig-
sun. beans. edilors.FonlEditor
| SansSerif
(a) Font Property Editor
sun. beans. editors.ColorE ditor
| | Ц92Д92Д92
Done |
3
(b) Color Property Editor
FIGURE 31S: Custom Editors Provided by the Beanbox.
ure 315 show's the paintable areas for the Beanbox’s color and font property editors.
The size and location of the paintable area is determined by the bean editor and cannot be
controlled by the property editor.
Note: The Beanbox in BDK 1.0apr97 requires that property editors that have a paintable
area also support a custom editor (see previously). This may not be required in other bean edi-
tors.
Data and Event Flow
While a bean editor is editing a bean, all of the property values in the bean are kept in sync
with the property values in the property editors. Here's how it's done:
1. Just after the bean editor creates the property editor, it retrieves the property value from
(he bean (by invoking the read accessor method) and passes it to the property editor via a
call to setValue(). If the property type is a primitive type, the bean editor wraps the
value in the appropriate wrapper object before calling setValueO.
2. The bean editor registers itself with the new property editor so as to receive property
change events.
3. If the property editor does not support a custom editor, the bean editor calls its getAs-
PropertyEditor
java.beans
Text О method to retrieve a string representation of the current value. Otherwise, if the
property editor does support a custom editor, the bean editor calls its getCustomEdi-
torO method and displays the custom editor. The custom editor is responsible for initial-
izing itself from the property editor.
4. If the user changes the property value in the property editor, the bean editor calls the
property editor's setAsTextO method, using the new value. The property editor then
converts the new string to an object of the property type and calls setValueO. If the
property value is changed through a custom editor, the custom editor must also call set-
ValueO with the new value.
5. The setVal ue() method saves the new value in a private field and then fires a multi-
change property change event to the bean editor.
6. The bean editor receives the property change event, determines which property editor
fired it, and then retrieves the new property value by calling the property editor's
getValueO method.
7. The bean editor uses the new value to update the bean's property by calling the bean
property's write accessor method. If the property editor supports a custom editor, the bean
editor will call the property editor's pai ntValueO method to update the paintable area.
8. Since a change to one property can affect another property, the bean editor must retrieve
all property values from the bean (by calling all of the read accessor methods) and check
for changes. The bean editor maintains a list of all previous property values from the
bean, so it can compare the values from this list with the retrieved property values (it sim-
ply does a reference comparison to determine if two values are the same). For each value
that has changed, it calls the setValueO method for the appropriate property editor with
the new value.
Note: If a property in the bean changed, the property editor showing its value is not imme-
diately updated. However, that property editor will be updated as soon as the user uses any
property editor to make a change.
MEMBER SUMMARY 1
Value Methods
: getValueO Retrieves the current property value.
setValueO Sets a new value for the property.
String Conversion Methods
getAsTextO Generates a string representation of the property value.
setAsTextO Converts a string representation of a properly value to an object of the property type.
Tag Method
getTagsQ Retrieves the property editor's tag list, if any.
1252
java.beans
Proper! у Editor
MEMBER SUMMARY
Paint Methods i sPai ntable() pai ntValue() Determine^ if lhe properlv editor can paint a repre- sentation of the propertv. Called to paint a representation of the proper!} value.
Custom Editor Methods getCustomEdi tor 0 supportsCustomEdi tor() Retrieves the properl} editor’s custom editor, if an\. Determine^ whether the properlv editor supports a custom editor.
Listener Methods addPropertyChangeLi stenerO removePropertyChangeLi stenerO Adds a listener for receiving proper!} change events. Stops a listener from receiving properl} change events.
Java Initialization String Method getJavalni ti ali zati onStri ng О Generates a fragment of Java source code lor creating an instance of lhe properlv value.
See Also
PropertyEdi torSupport.
Example
This example demonstrates
a simple property editor
that uses tags. The example
has a property called “fla-
vor/' Although the prop-
erty is a string, it can hold
only a string that is from a
fixed set of strings. A prop-
erty editor. Fl avorEdi tor.
is defined for lhe flavor
property Since the property FIGI RE 316: FlavorEditor.
is a siring. onl> the get-
TagsO method needs to he overridden in order to return the list of flavors. See Figure 316.
(For an example of where the propertv is an int. see the PropertyEdi torSupport. setAs-
Text О example.)
PropertyEditor
java.beans
A bean-info is necessary to associate FlavorEditor with the bean's "flavor’4 property.
The bean-info must be defined in a class, with the bean's name appended with ’’Beanlnfo." in
this case, is BeanBeanlnfo.
A
В
C
D
Bean.java
import java.awt.*;
import java.beans.*;
public class Bean extends Panel {
public static String[l flavors =
{"French", ’'Columbian", "Mocha’', "Foldgers"};
String curFlavor - flavors[0];
// Use a label to display the current flavor.
Label 1 = new Labe 1(curFlavor);
public BeanO {
add(l) ;
}
public String getFlavor() {
return curFlavor;
}
public void setFlavor(String f) {
1.setText(curFlavor = f);
}
}
/*
manifest.txt:
Name: Bean.cl ass
Java-Bean: True
jar command:
jar cfm bean.jar manifest.txt Bean.class FlavorFditor.class BeanBean-
Info.cl ass
V
FlavorEditor. java
import java.beans.*;
R
S
T
public class FlavorEditor extends PropertyEditorSupport {
public StringE] getTagsO {
return Bean.flavors;
}
}
BeanBeanlnfo.java
import java.beans.*;
public class BeanBeanlnfo extends SimpleBeaninfo {
public PropertyDescriptor[] getPropertyDescriptorsO {
PropertyDescriptor pd[] = new PropertyDescriptor[1];
try {
pd[01 = new PropertyDescriptor("flavor"t Bean.class);
pd[0]setPropertyEdi torClass(FlavorFdi tor.cl ass):
pd[0].setBound(true);
return pd;
} catch (Exception e) {
1254
java.beans
PropertyEditor
add Prope rt у Chan ge L i sten er()
e.printStackTraceO; return null; }
}
}
addPropertyChangeListenerO
PURPOSE Adds a listener for receiving property change events.
SYNTAX void addPropertyChangeListener(PropertyChangelistener listener)
DESCRIPTION This method should add listener to the listener list. After calling this method, the property editor should notify listener of any changes to the property by way of property change events. T he property name, old value, and new value fields of the events will all be set to nul 1. This method is typically called by a bean editor so that it can be notified when the user changes the value in the property editor.
PARAMETERS listener A non-null property change event listener.
SEE ALSO removePropertyChangeListenerO-
EXAMPLE See the PropertyChangeEvent class example as an example of how' to use PropertyChangeSupport to implement this method.
getAsTextO
PURPOSE Generates a string representation of the property value.
SYNTAX String getAsTextO
DESCRIPTION If the property editor does not have a custom editor and the bean property is not a string, it is necessary to provide methods to convert the property type to and from a string. This method converts the property type to a string in a form that setAsTextO can reconvert to the property type. This method typically retrieves the property value to convert by calling getValueO. If a custom editor is available or if the property is a string, the property editor does not need to do string conversions, so this method should simply return null.
RETURNS The possibly null string representing the property value.
SEE ALSO getValueO f setAsTextO.
Property Editor
getCustomEditorO
java.beans
example See the PropertyEditorSupport class example, PropertyEditorSup-
port. getCustomEdi tor(X and PropertyEdi torSupport.getAsText().
a getCustomEditorO
pi rposi- Retrieves the property editor's custom editor, if any.
syntax Component getCustomEditorO
D di scripik >n When a property cannot be represented as a single string or as a set of tags, it is
H necessary to provide a custom editor. A custom editor is a component specially
p designed for editing the property. It must not be a window, since the bean edi-
tor needs to insert it into an existing container. In lhe case of the Beanbox. lhe
G custom editor is inserted into a frame by clicking a Done button.
H A property editor should implement this method to return the custom editor. If
। no custom editor is available, nul 1 should be returned.
j The custom editor is typically created when this method is called. It should
provide a means for reporting changes to lhe property editor as the user inler-
K acts with the custom editor. The simplest way is for the custom editor to save a
L reference to the property editor and call the property editor's setValuef) or
setAsTextO methods when appropriate. Another way is for lhe custom edi-
tor to fire property change events whenever the value changes. The custom
N editor will then have to provide the property change listener methods so that
o the property editor can register for events. See PropertyChangeSupport for
more details on how to do this.
reti rns A possibly null component for editing the property.
Q
slf also supportsCustomFdi tor().
R
exampi e See PropertyEdi torSupport. getCustomEdi tor().
s
T
. getJavalnitializationStringO
V PC RPOSE Generates a fragment of Java source code for creating an instance of the prop- 1
w erty value. ]
X SYNTAX String getJavalnitializationStringO ,
Y DESCRIPTION This method should take the current value (as returned by getValueQ) and generate a fragment of Java source code that, when compiled (within a compi-
z lation unit), will yield the current value in the property's type. The fragment may create an object; in this case, it must include the new keyword and fully *
qualified object type.
1256
java.beans PropertyEditor geiTagsO This method is used by some bean editors to generate initialization Java source code. When compiled and run, this code will initialize the properties of a bean.
RETURNS A non-null fragment of Java source code.
example If the property type is float: public String getJavalni t iali zationSt ri ngO { return + getValue() + "f”: } If the property type is Font: public String getJavalnitializationString() { Font f -r (Font)getValue(); return "new java.awt. Font(\"" * f.getTami ly() + ” + f.getStyleO * ”, " * f.getSizeO + О"; }
getTagsQ - ..
purpose Retrieves the property editor's tag list, if any.
SYNTAX Stringf] getTagsQ
DESCRIPTION If lhe property editor uses tags, the implementation ol this method should return a non-null array of tags. See the class description for more information about tags, If the type of the properly is not a siring, then getAsTextQ and setAsTextQ must be implemented to return and accept any of lhe tags. See the method descriptions for details.
RETURNS A possibly null array of tags.
SEE ALSO getAsTextQ, setAsTextQ.
EXAMPLE See PropertyEditorSupport.getTagsQ.
getValueQ
PURPOSE Retrieves the current property value.
SYNTAX Object getValueQ
DES( Rl PTION This method should simply return the most recent value passed in by set- Val ueQ. It is typically called by the bean editor immediately after it receives a property change event from some property editor in order to determine if the property has changed. This method can be called by getAsTextQ when it needs to create a string representation of the property value.
PropertyEditor java.beans
isPaintablct)
If the properly type is a primitive type, this method will return the property value contained in the corresponding wrapper object. For example, if the prim- itive type is boolean, the returned object will be a Boolean object. This method does not have to create the wrapper object, since the wrapper object will already have been created before setValueO is called. The returned value should be treated as immutable and should not be modified.
RETURNS I'he possibly null current properly value.
SET Al SO getAsTextO, setValueO.
I X \MPl 1 See PropertyFdi torSupport.getAsTextO.
isPaintableO
PLRPOSE Determines if the properly editor can paint a representation of the property.
SYNTAX boolean isPaintableO
DESCRIP 1 ION If the property editor can paint a representation of the property, the implemen- tation of this method should return true. For example, if the property is a color, this method could paint the color. Or if the property is an image, this method could paint a scaled version of the image. This method is typically called by the bean editor. If this method returns true, the bean editor will also call the property editor's paintValueQ method w henever the property value must be painted. Note'. The Beanbox in ihe BDK I.Oapr97 ignores this method unless sup- portsCustomEditor() also returns true. This may not be required in other bean editors.
RE 11 RNS true if the property editor can paint a representation of the property; false otherwise.
EXAMPI E See PropertyEditorSupport.getCustomEditor().
paint Value!)
Pl RPOSE Called to paint a representation of the property value.
SYNTAX void paintValuefGraphics g, Rectangle box)
DESCRIPTION if isPaintableO is true, this method will be called by the bean editor to allow the property editor to paint a representation of the property value within the box. For example, if the property is a color, this method could paint the color in the box. Or if the property is an image, this method could paint a
1258
java.beans
Property Editor
re m о ve Prope rt у Ch an ge Li ste n c r()
scaled version of the image in the box. This method is called each time the
property editor fires a property change event.
I’he size and location of box is determined by the bean editor and cannot by
specified by the property editor.
If this method might paint outside the box rectangle, it must set the clipping
rectangle on g. The box instance is a new instance, so it can be modified with-
out affecting the bean editor\ state.
Note: When the Beanbox in BDK L0apr97 is used, the width and height of
box are 2 pixels too wide and 2 pixels too high. Subtract 2 from both the w idth
and height to get the true dimensions.
parameters
box A new' non-nul 1 Rectangle specifying lhe area in g in which to paint.
g /X new non-nul 1 graphics context on which to paint.
see: also java.awt.Graph!cs, java.awt.Rectangle.
example See PropertyEditorSupport.getCustomEditorO-
removePropertyChangeListenerO
PURPOSE Stops a listener from receiving properly change events.
SYNTAX void removePropertyChangelistener(PropertyChangeListener 1i stener)
DESCRIH ION This method should remove listener from the listener list. If listener is not in the listener list, the method call should be ignored. The implementation of this method does not have to stop delivery of events immediately. That is. after this method is called, (he listener may receive a few more property change events. See PropertyChangeListener for more details.
PARAMEIERS listener A non-null property change event listener.
SEE ALSO addPropertyChangeListener().
EXAMPI J See the PropertyChangeEvent class example for an example of how to use PropertyChangeSupport to implement this method.
PropertyEditor
java.beans
setAsTextO
setAsTextQ
PURPOSE Converts a string representation of a property value to an object of the property type.
A SYNTAX void setAsIext(String text) throws II legalArgumentException
В DESCRIPTION If the property editor docs not have a custom editor and the bean property is
C not a string, methods must be provided to convert the property type to and from a siring. The getAsTextQ method converts the property type to a string.
D E This method must be able to reconvert the string to the property type. If the property type is a primitive type, the new value must be wrapped in the
F appropriate wrapper object. For example, if the property type is boolean, then
ZT the new value must be wrapped in a Bool ean object.
M If text is successfully converted to a valid property value, this method must
H call setValueО with the new value. (Note that the value passed to set-
I Val ueQ must be a new instance of the property type: this method must not
f modify the current property value.) setValueQ will notify lhe bean editor
J that the value has changed.
к PARAMETERS
L text The non-null string representation of the property value.
M EXCEPTIONS
IllegalArgumentException
If text cannot be converted to a valid property value.
О '
see also getAsTextQ, java. lang. Il legal ArgumentException, setVal ue().
И example See PropertyEdi torSupport. setAsTextQ.
Q
setValueQ
purpose Sets a new value for the property.
syntax void setValue(Object value)
V
W
X
description This method is called by the bean editor to initialize the property editor just
after it is created. It is also called whenever the user changes the value of the
property. For example, if the property is the label of a button, this method will
be called each time the user changes the button's label.
If the value has indeed changed, the caller should create a completely new
instance of the value before calling setValueQ. That is.
getValueQ != value.
1260
PropertyEditor
supportsCustomEd i tor()
java.beans
See the class description for more details. The new value should be stored in a private field in the property editor. The bean editor will later retrieve the new value (via a call to getVal ue()) and then directly update the property value in the bean. This method may also be called by setAsTextO when a string representation of the property value is converted to an object of the property type. If the property type is a primitive type, the new value must be wrapped in the appropriate wrapper object. For example, if the property type is boolean, then the new value must be wrapped in a Boolean object. This method must also fire a property change event to any property change event listeners. The property change event should be a multichange event (see PropertyChangeEvent). so the property name, old value, and new value should all be nul 1.
PARAMETERS value The possibly null new property value.
SEE ALSO getValueO, setAslextf).
exampi e See the PropertyEditorSupport class example. PropertyEditorSup port. getCustomEdi tor(). and PropertyEdi torSupport. setAsTextO-
supportsCustomEditorf)
PURPOSE, Determines whether the property editor supports a custom editor.
SYNTAX boolean supportsCustomFditorO
DESCRIPTION A property editor should implement this method to return true if a custom editor is available: false otherwise. Note: The Beanbox in the BDK 1,0apr97 ignores this method unless i sPai nt- abl eO also returns true. T his may not be required in other bean editors.
RETURNS true if the property editor supports a custom editor.
SEEALSO getCustomEdi tor().
EXAMPLE See PropertyEdi torSupport.getCustomEditor().
java.beans
Property EditorManager
A
В
c Syntax
□ public class PropertyEditorManager
Description
The PropertyEdi torManager is used to locate a property editor (see PropertyEdi tor) for a
G particular type. For example, if the type is i nt. class, the property editor manager will try to
H locate a property editor suitable for editing integer values.
Fhe property editor manager supplies property editors for the following types:
1 boolean
byte
J short
int
К long
float
double,
java. lang. St ring
M java.awt.Color
java.awt.Font
О
Q
R
S
T
L
You may override your own property editor for any of these types, or you may provide new
property editors for new types.
The Search Path
When the property editor manager does not have a registered property editor for a type, it tries
to find one. Where it looks is determined by the search path. The search path is an array of
package names; the way in which these package names are used is described in the next sec-
tion.
The property editor manager’s default search path is sun .beans.editors.
v Locating a Property Editor
When no association between a requested type and a property editor exists, the property editoi
manager tries to find one. It first takes the package-qualified class name and appends the string
X “Editor”. It then tries to instantiate a class with that name. For example, if the type is
java. awt. Image, it tries to instantiate a class named java.awt. ImageEdi tor.
If no class with that name is found, it removes the package name from the class name. For
7 example, java. awt. ImageEdi tor becomes ImageEdi tor. It then prefixes each of lhe pack-,
age names in the search path with the class name (separated by Л”) and then tries to instantiate J
that class. For example, if the search path contained sun.first and sun.second, the prop-1
1262
java.beans
PropertyEditorManager
erty editor manager tries to instantiate sun.fi rst. ImageEdi tor. If that fails, it tries
sun. second. ImageEdi tor.
SUMMARY
Find Method fi ndEditorO Locates a property editor for a type.
Registration Method regi sterEditorO Associates a property editor with a type.
Search Path Methods getEditorSearchPath() setEdi torSearchPathO Retrieves the property manager's search path. Sets the property manager's search path.
See Also
PropertyEditor.
Example
This example implements a bean that, when loaded (it doesn't even need to be instantiated),
replaces the property editor manager's default color editor. This means that after (his bean is
loaded, all beans that have the type Color will use the replacement color editor.
The color editor is in (he package ’editors/' so the “editors'1 package name needs to be
inserted in the property editor manager's search path. Next, the current color editor entry in the
property editor manager is cleared. Then the next time the bean editor looks for a color prop-
erty editor, it will find the replacement version, since the package name is placed in the search
path before its own.
The bean also implements a dummy property of the type Image. Since there is no default
image property editor, the property editor manager tries to find one and will locate the one in
the editors package.
Bean.java
import java.awt.*;
import java.beans,*;
public class Bean extends Component {
public BeanO {
}
// Some dummy methods.
public Image getlmageO {
// Need to return a non-null image, otherwise
// property editor is not created.
return createlmage(l, 1);
Property EditorManage г
java.beans
}
public void setimage(Image image) {
}
static {
StringLJ searchPath = PropertyEditorManager.getEditorSearchPath();
A Stringfj newPath = new String[searchPath .length ± 11;
В newPath[01 ''editors";
for (int i-0; i<searchPath.length; i+O {
C newPath[i+1J - searchPath[iJ;
}
D PropertyEdi torManager.setEdi torSearchPath(newPath);
E // Clear out current entry.
PropertyEdi torManager.regi sterEdi tor(Col or.cl ass, null):
F
// Rather than set search path, the bean could instead explicitly
G // register the property editor, like so:
//PropertyEditorManager.regi sterFdi tor(Color,cl ass,
H // editors.ColorEditor.class);
I // lust checking to see if the search path worked.
PropertyEditor pe - null;
J try {
pe = PropertyEditorManager.findFditor(Color.class);
К if (pe -- null) {
System.err.print 1n("Could not find the color editor");
I, }
M String s = pe.getC’lassO .getNameO ;
if (ls.eguals("editors.ColorEditor")) {
\ System.err.printlnC'Wrong color editor found");
}
О } catch (Exception e) {
e.printStackTraceO;
n
Q >
/”
R mani fest.txt:
Name: Bean.cl ass
S Java Bean: true
jar command:
T jar cfm bean.jar manifest.txt *.class editors/”.cl ass
J7
U
ColorEditor.java
W package editors;
X import java.awt.
import java.awt.event;
Y import java.beans.-;
import java.util.”;
Z
public class ColorEditor extends PropertyEditorSupport {
public boolean isPaintableO {
return true;
1264
java.beans
Prope rtyEditorManager
findEditorO
}
public, void paintValue(Graphics g, Rectangle box) {
g. setCol or ((Co lor) get Value O) :
g.fi11Rect(box.x, box.y, box.width, box.height):
g.setColor(Col or.black);
// There’s a bug in the bean box where box width and height are too
// big by 4 pixels.
g.drawRect(box.x, box.y, box.width-5, box.height 5);
}
public boolean supportsCustomEditor() {
return true;
}
public java.awt.Component getCustomEditorO {
return new ColorCustomFditor(this, (Color)getValue());
}
}
findEditorO
PURPOSE Locates a property editor for a type.
SYNTAX public static PropertyEditor findLditor(Class targetType)
DESCRIPTION The property editor manager first checks to see if a property editor has been registered for targetType. If one has not. it tries to locate the property editor. See the class description for details on how this is done. If no property editor is found, null is returned.
PARAMETERS targetType A non null Class object.
REIT RNS A possibly null property editor for targetType.
EXAMPLE See the class example.
getEditorSearchPath()
Pt'RPOSE Retrieves the property manager‘s search path.
SYNTAX public static String[] getEditorSearchPathO
[M:S( RfRIlON This method returns the property editor manager s search path, which is used to find a property editor when a property editor has not been explicitly regis- tered for a type. See the class description for details on how the search path is used. The search path initially contains a single element: sun. beans. edi tors.
PropertyEditorManager
jav a. beans
register[*diior()
Rl H RXS A non-null array of package names.
SEE ALSO set Edi torSearchPathQ.
FX AMPLE See the class example.
/\
в registerEditorO
c 14 RPOSE Associates a property editor with a type.
D SWT VX public static void registerEditor(Class targetType, Class
I: edi torClass)
F DESCRIPTION Ihis method explicitly associates a type targetType with a property editor editorclass. If a property editor was already associated with targetType. it
G will be overridden with editorClass. If editorClass is null, this method
H 1 will remove any association of a properly editor with targetType. In this case, when a property editor is needed lor targetType, the propertv editor manager needs to search for one (see the class description for more details).
J Changing associations using this method affects all beans in the bean environ-
К me nt. For example, setting a new property editor for int (i.e.. Integer .TYPE)
L means any bean property with type i nt will use the new property editor.
PARAMI: lERS
M editorClass The possibly null Class object of the property editor.
N targetType rhe non-null Class object of the type.
() EXAMPLE; See the class example.
Q setEditorSearchPath()
R PERPOSE Sets the property manager's search path.
S SV ХГЛХ public static void setEditorSearchPath(String path[])
T и V DESCRIPTION This method sets the property editor manager s search path, which is used to find a property editor when a property editor has not been explicitly registered for a type. See the class description for details on how the search path is used.
When selling a new search path, you should include the elements of the current
w search path in the new search path. The old search path can be retrieved by
X calling getEditorSearchPathO-
Y PARAMETERS
Z path A possibly null array of package names.
SEE ALSO getEdi torSearchPath().
EXAMPLE See the class example.
1266
java.beans
Property EditorS upport
PropertyEditorSupperr
Syntax
public class PropertyEditorSupport implements PropertyEditor
Description
A property editor is essentially a user interface for editing a bean property. When a bean editor
edits a bean, it needs to create a property editor for each of the bean's properties. A bean editor
provides a default property editor for a number of types, but if a property type is not one of
these, then you must provide a property editor for that property type. This class provides a com
venicnl superclass for building a property editor. See PropertyEdi tor for complete informa-
tion on property editors and how to build them.
MEMBER SUMMARY
Constructor PropertyEditorSupportО Constructs a new PropertyEdi torSupport instance.
Value Methods getValueO setValueO Retrieves the cunent property value. Sets a new value for the property.
Text Methods getAsTextO setAsTextO Generates a string representation of the property value. J Converts a string representation of a property value to an object of the property type.
Tag Method getTagsQ Retrieves the property editor's tag list, if any. j
Custom Editor Methods getCustomEdi tor() supportsCustomEdi tor О Retrieves the pro реп у editor’s custom editor, if any. Determines whether the property editor supports a custom editor.
Continued
Property EditorSupport
java.beans
A
В
C
D
E
F
G
H
MEMBER SUMMARY
Paint Methods
i sPai ntable()
pai ntValue()
Listener Methods
addPropertyChangeLi stenerO
fi rePropertyChangeO
removePropertyChangeLi stenerO
Initialization String Method
getJavalni ti ali zati onString О
Determines if the properlv editor can paint a repvsen-
talion of lhe properlv.
Called lo paint a representation ol lhe piopcrtv value
Adds a listener lor rccciv ing propertv change cvcnK
Delivers a properlv change event to lhe listeners.
Removes a listener from receiving propeliv change
ev ents.
Generates a fragment of Java source code lor creating
an instance of the properlv value.
I
J
К
I.
M
N
()
See Also
PropertyChangeEvent,
Example
PropertychangeLi stener, PropertyEdi tor.
Q
R
S
T
и
V
w
X
Y
FIGURE 317: Locale-sensitive Date Bean and Editor.
P
This example implements a dale bean that can display a date in anv locale. (For simplet exam-
ples of property editors, sec the method examples in this class.)
1268
java.beans
PropertyEditorSupport
The date bean has three properties: date, locale, and date format style. The date property is
represented by a Date object and basically contains the day, month, and year. The locale prop-
erty contains one of the available locales. The style property is an attribute of the date format-
ter and specifies how long the string representation of the date should be (see
java.text .DateFormat for more details). See Figure 317.
The DateEditor demonstrates a property editor that converts a property type. Date, to
and from a string. Both Local eEditor and StyleEditor demonstrate property editors that
use tags.
Л bean-info is necessary to associate the three property editors with the bean's property.
The bean-info must be defined in a class with the bean’s name appended with "Beaninfo." in
this case. BeanBeanlnfo.
Bean.java
import java.awt.*;
import java.beans.*;
import java.text.*;
import java.util.*;
public class Bean extends Panel {
public Date date = new DateO;
public Locale locale = Locale.getDefaultО;
public int style = DateFormat.MEDIUM;
// Use a label to display the current flavor.
Label 1 ~ new Label(toString());
public BeanO {
add(l);
}
// Date accessor methods.
public Date getDateQ {
return date;
}
public void setDate(Date date) {
this.date = date;
1. setText (toStri ng()) ;
1
// Format Style accessor methods.
public int getStyleO {
return style;
}
public void setStyle(int style) {
this.style = style:
1.s etText(toStri ng Q):
}
// Locale accessor methods.
public Locale getLocaleO {
return locale;
)
public void setLocale(Locale locale) {
this.locale - locale;
1.s etText(toStringO) ;
Property EditorSupport
java.beans
A
В
C
D
E
J
/*
// Converts the date into a string using the current locale and style,
public String toStringO {
return DateFormat.getDateInstance(style, locale).format(date);
}
mani fest.txt:
Name: Bean.cl ass
Java-Bean: True
jar command:
jar cfm bean.jar manifest.txt *.class
F
G
H
I
J
К
L
M
N
О
Q
R
S
BeanBeanlnfo.java
import java.beans.*;
public class BeanBeanlnfo extends SimpleBeanlnfo {
public PropertyDescriptor[] getPropertyDescriptorsO {
PropertyDescriptor pd[] = new PropertyDescriptor[3];
try {
pd[0] = new PropertyDescriptor("date”, Bean.cl ass);
pd[0].setPropertyEditorClass(DateEdi tor.class);
pd[l] = new PropertyOescriptorC’style", Bean.class);
pd[l].setPropertyEditorClass(StyleEditor.class);
pd[2] = new PropertyDescriptorC’locale", Bean.class);
pd[2].setPropertyEditorClass(Local eEditor.class);
return pd;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
DateEditor.java
import java.beans.*;
import java.text.*;
import java.util.*;
// This property editor allows the user to edit the date
// in the default locale, using the SHORT format.
public class DateEditor extends PropertyEditorSupport {
public String getAsTextO {
return DateFormat.getDate!n$tance(
DateFormat.SHORT, Locale.getDefault()).format(((Date)getValue()));
public void setAsText(String text) throws II legalArgumentException {
try {
setValue(DateFormat.getDateInstance(
DateFormat.SHORT, Locale.getDefaul tO) .parse(text));
return;
} catch (Exception e) {
// It doesn't matter what the exception is.
1270
java.beans
Property EditorSupport
}
throw new II 1egalArgumentException(text);
}
}
LocaleEditor.java
import java.beans.*;
import java.text.*;
import java.util
public class LocaleEditor extends PropertyEditorSupport {
Locale[] locales = DateFormat.getAvai1ableLocales();
Stringf] localeNames = new String[locales.length];
public LocaleEditorQ {
superO ;
for (int 1=0; 1<locales.length; i>+) {
local eNames [i ] = locales[1 ].getDisplayNameO ;
}
}
public String!"] getTagsO {
return localeNaires;
}
public String getAsTextO {
return ((Locale) getValueO) .getDi splayNameO ;
}
public void setAsText(Stnng text) throws IllegalArgumentException {
for (int 1=0; i<locales.length; i*-) {
if (text.equals(local eNames[i1)) {
setValue(locales[i ]);
return;
}
}
throw new Ill egalArgumentException(text);
}
}
StyleEditor.java
import java.beans.*;
import java.text.*;
public class StyleEditor extends PropertyEditorSupport {
int[] styleValues =
{DateFormat.SHORT, DateFormat.MEDIUM,
DateFormat.LONG, DateFormat.FULL};
StringL] styleNames =
{’SHORT”, ’’MEDIUM”, '’LONG", "FULl”};
public String[] getTagsO {
return styleNames;
}
public String getAsTextO {
int s - ((Integer)getValueO).intValueO ;
java.beans
Property Ed it orSu p po rt
add Properly Changel Jstcnerf)
for (int i=0; i<styleNames.length; i++) {
if (s -= styleValues[i1) {
return styleNamesfi j;
}
}
// I his should not occur
A return nul1;
}
В
public void setAsIext(String text) throws Il legalArgumentExcept ion {
C for (int i=0; i<styleNames. 1 ength; i +O {
if (text.equals(styleNames[i])) {
D setValue(new Integer(styleValues[iJ));
return;
E }
}
F throw new Г1legalArgumentE-'xception(text);
}
G }
H
I
addProperty ChangeListenerO
pi-rpose:
SY VI AX
DESCRIPTION
PARAMETERS
listener
SEI- ALSO
EXAMPLE-:
Adds a listener tor receiving property change events.
public synchronized void
addPropertyChangeLi stener(PropertyChangeLi stener 1i stener)
This method adds listener to the listener list. The method does not check if
listener has already been added, so a listener can be added to the list more
than once.
Unless you need to distribute events in a way different from this implementa-
tion, it is not necessary io override this method. However, if this method is
overridden, then two other methods must also be overridden: removeProper-
tyChangeLi stenerO and fi rePropertyChangeO.
This method is typically called by a bean editor so that it can be notified when
the user changes the value in lhe property editor.
A non-nul 1 property change event listener.
removePropertyChangeListenerO . fi rePropertyChangeO.
See the PropertyChangeEvent class example.
Y
fireProperty ChangeO
purpose Delivers a property change event to the listeners.
1272
Property EditorSuppci
get A>Te\
ja\ a.beans
SV X I w
01 SC RIГ I l< >X
SEI. Al SO
EXAMPI I
getAsText()
Pl RPOsI
SYXI AX
DES( RIP I |O\
RETI RXs
SEI- Al S( >
EXAMPI I
public void firePropertyChange()
l ibs method creates a new propertv change event and delivers it to all listen-
ers The source of the event is this object. All of the other properties of the
event—propertv name, old value, new value—are null.
Listeners should not throw exceptions. Exceptions thrown arc considered pro-
gramming errors.
PropertyChangeEvent.
See setVal ue().
Generates a string representation of the property value.
public String getAsTextO
If the property type is a string, this method returns the propertv value; other-
wise. it returns null. If the properly editor does not have a custom editor and
the bean property is not a stimg. tills method should be overridden to generate
a string representation of lhe current property value. The string representation
must be in a form that can be reconverted to lhe property value by setAs-
TextO.
This method should retrieve lhe propertv value lo convert by calling
getValue().
I'hc possibly-nul 1 string representing the propertv value.
gptValupf), setAsTextO.
This example bean has a
properlv called ‘align."
which is an integer in a
fixed range of integers. l he
range is small, so the prop-
erty is made a tagged prop-
erty. A properly editor.
AlignEditor. L defined
and returns the alignment
names as tags Since the
alignment is an integer and
not a string. AlignEditor needs to convert integer values to strings and vice
versa 11 docs this by overriding getAsTextO and setAsTextO. Sue I igurc
java.beans
PropertyFditorSupport
gctAsTexU)
A bean-info is necessary to associate Al ignEditor with the bean's align prop-
erty. It must be defined in a class with the bean's name appended with "Bean-
Info/ m this case, BeanBeanlnfo.
Bean, java
Л import java.awt.’;
import java.beans.'-;
В
public class Bear extends Panel {
C public static final int LEFT - 0;
public static final int CENTER = 1;
D public static final int RIGHT = 2;
E public static String[J alignNames ~
{“Left”, "Center", ’'Right’1};
F
int curAlign - CFMER;
G
// Use a label to display the current flavor.
H Label 1 = new Label (al ignNames [curAl i gnj , CENTER);
I public BeanO {
add(l);
J }
public int getAlign() {
К return curAlign;
}
L public void setAlign(int a) {
1.setText(alignNames[curAlign aj);
M 1.setAlignment(a);
}
N }
/*
О manifest.txt:
Name: Bean.class
lava Bean: True
jar command:
Q jar cfm bean.jar manifest.txt Bean.class AlignFditor.cl ass BeanBean-
lnfo. class
R */
S AlignEditor.java
T import java.beans.*;
tj public class AlignFditor extends PropertyEditorSupport {
public StringM getTagsO {
V return Bean.alignNames;
}
w
public String getAsTextO {
X return Bean.al ignNamesL(CTnteger)getValueO) intValueOO
}
Y
public void setAsTextCString text) throws T1 legalArgumenttxception {
Z for (int i-0; i<Bean.a 1ignNames.length; iw) {
if (Bean.alignNamesfi].equals(text)) {
setValue(new Tnteger(i));
return;
1274
java.beans
PropertyEditorSupport
getCusiomliditorO
}
}
throw new Ill egal Argument Exception(text);
}
}
Bea nBean I nf o. ja va
import java.beans.*;
public class BeanBeanlnfo extends SiTpleBeanlnfo {
public PropertyDescriptor[J getPropertyDescriptors() {
PropertyDescriptor pd[l = new PropertyDescriptorfll;
try {
pd[0] new PropertyDescriptor("align", Bean.class);
pd[0].setPropertyEditorClass(Ali gnEditor.class);
return pd;
} catch (Exception e) {
e.printStackTraceO;
return nul1;
}
}
}
getCustomEditor()
pi Rposi Retrieves the property editor's custom editor, if any.
symax public Component getCustomEdi tor О
desoripiiox When a properly cannot be represented as a single string or as a set of tags, a
custom editor must be provided. A custom editor is a component specially
designed for editing the property. Il must not be a window, since the bean edi-
tor needs to insert it into an existing container. In lhe case of lhe Beanbox, the
custom editor is inserted into a frame by clicking a Done button.
This method by default returns nul 1. If a custom editor is available, a property
editor should override this method and return the custom editor.
The custom editor is typically created when this method is called. It should
provide a means for reporting changes io lhe property editor as the user inter-
acts with the custom editor. The simplest way to do this is for the custom editor
to save a reference to the property editor and call the property editor's set-
Val ue() or setAsTextQ methods when appropriate. Another way is for the
custom editor to fire property change events whenever the value changes. The
custom editor would then have to provide the property change listener methods
so that the property editor can register for events. See PropertyChangeSup-
port for more details on how to do this.
rfi i rms nu 11. (herride to return the custom editor.
Property EditorSupporl
ja\ a.beans
gctCustomEditorf)
si.i. \i so
supportsCustomFdi tor().
EX \MPI I
A
В
C
D
E
E
G
H
I
.1
К
L
M
N
()
I bis example implements a Color proper!) editor different from the one pro-
vided by the Beanbox. This color editor has three scrollbars for adjusting the
hue. saturation, and brightness of the color. See Figure 319.
A bean-info is necessarv to associate the ColorEdi tor class with the bean’s
two color properties: foreground and background. I'he bean-info must he
defined in a class with the bean’s name appended with “Beaninfo." in this
case. BeanBeanlnfo.
P
Bean.java
i mport java. awt. *;
import java.beans.-;
public class Bean
extends Component {
public Bean() {
setSize(100, 50);
}
// Paint the background color
// on the left and the fore-
// ground color on the right,
public void paint(Craphics g)
{
g.clearRect(0, 0,
getSi ze().wi dth/2,
getSi ze().hei ght);
g.fi11Rect(
getSize().width/2, 0,
}
}
/'•'•'
manifest.txt:
Name: Bean.cl ass
HGl RE 319: Custom Color Proper!) Editor.
getSize().width/2, getSizeO.height);
Q
R
S
Java-Bean: True
jar command:
jar cfm bean.jar manifest.txt
‘ • . с 1 a s s
T
Г
V
W
X
Y
ColorEditor.java
import java.awt. ;
import java.awt.event.-;
import java.beans.-;
import java.util.-;
public class ColorEditor extends PropertyEditorSupport {
public boolean isPaintableO {
return true;
}
public void paintValue(Graphics g, Rectangle box) {
g. setCol or ((Col or) getValueO);
g.fi11Rect(box.x, box.y, box.width, box.height);
g.setColor(Col or.bl ack);
1276
java.beans
PropertyEdi torSupport
getCustomEditorO
// There's a bug in the bean box where box width and height are too
// big by 4 pixels.
g.drawRect(box.x, box.y, box.width-5, box.height-5);
}
public boolean supportsCustomEditorO {
return true;
}
public java.awt.Component getCustomEditorO {
return new ColorCustomtditor(this, (Color)getValue());
}
}
ColorCustom Editor, java
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
public class ColorCustomEditor extends Panel implements AdjustmentListener {
Color curColor;
PropertyEditor pe;
Scrollbar hSbar - new Scrollbar(Scrol1 bar.VERTICAL, 500, lt 0, 1000);
Scrollbar sSbar = new Scrollbar(Scroll bar.HORIZONTAL, 500, 1, 0, 1000);
Scrollbar bSbar = new Scrollbar(Scrol1 bar.VERTICAL, 500, 1, 0, 1000);
public ColorCustomEditor(PropertyFditor pe, Color c) {
if (c null) {
c «• Color.gray;
}
float[] hsbvals =
Color. RGBtoHSB(c .getRedQ , c. getGreenO , c.getBlueO, null);
this.pe = pe;
curColor - c;
setLayout(new BorderLayoutO);
hSbar.addAdjustmentListenerCthi s);
sSbar.addAdjustmentLi stenerCthis);
bSbar.addAdjustmentLi stener(this);
hSbar.setValue((i nt)Math.round(hsbvals[0J*1000));
sSbar.setValue((i nt)Math.round(hsbvals[1]*1000));
bSbar.setValue((i nt)Math.round(hsbvals[2]*1000));
add(hSbar, Borderl ayout.WEST);
add(sSbar, BorderLayout.SOUTH);
add(bSbar, BorderLayout.EAST);
}
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
public void paint(Graphics g) {
g.setColor(curColor);
g.fi11Rect(0, 0, getSize().width, getSizeO . height);
}
public void adjustmentValueChanged(AdjustmentEvent evt) {
Property Ed it or Support
getl aval nit i a 1 i /.alionStri ng()
java.beans
curColor =- Color.getHSBColorf
hSbar. get Val ue 0/1000.0f,
sSbar. getVal ueQ/1000.0f,
bSbar.getVa1ue(5/1000.0f )
pe.setValue(curColor);
repai nt();
getJavalnitializationStringQ
PURPOSE Generates a fragment of Java source code for creating an instance of the prop- erly \alue.
SYNTAX public String getJavalnitializationString()
DESCRIPTION This method should take the current value as returned by getValueQ and generate a fragment of Java source code that, when compiled (within a compi- lation unit), will yield the current value in the property's type. T he fragment may create an object. In this case, it must include the new keyword and lhe fully qualified object type.
RETURNS A non-null fragment of Java source code.
EX А МИД; If lhe property type is a float: public String getJavalnitializationStri ngO { return + getValueQ + ''f"; } If the property type is a font: public. String getJavalnitializationStringQ { Font f - (Font)getValue(); return "new java.awt. Font(\1M’ + f.getFamilyO + "\'\ '* + f.getStyleO + n, " f,getSizeO + 1
getTagsQ __________________________________________________________________
purpose. Retrieves the property editor's tag list, if any.
sxm-xx public String[J getTagsQ
description If the properly editor is one that uses tags, this method should be overridden to
return a non-null array of tags. See the class description for more information
about tags.
If the type of the property is not String, then getAsTextQ and setAs-1
Text О must be overridden to return and accept any of the tags. See the'
method descriptions for details.
1278
PropertyEditorSupport
getValueO
java.beans
RETURNS A possibly null array of tags.
SEE ALSO getAsTextO , setAsTextO.
EXAMPLE See the PropertyEdi tor example.
getValueO _
PURPOSE Retrieves the current property value.
SYNTAX public Object getValueO
DESCRIPTION By default, this method returns the most recent value passed in by set- ValueO. There is typically no need to override this method. The returned value should be treated as immutable and should not be modified. This method is typically called by the bean editor immediately after it receives a property change event from some property editor in order to determine if the property has changed. This method can be called by getAsTextO when it needs to create a string representation of the property value. If the property type is a primitive type, this method will return the property value contained in the corresponding wrapper object. For example, if the prim- itive type is boolean, the returned object will be a Boolean object. This method does not have to create the wrapper object, since the wrapper object will already have been created before setVal ue() is called.
RETURNS The possibly nul 1 current property value.
SEE ALSO getAsTextO, setValueO.
EXAMPLE See getCustomEditorO.
isPaintableO
purpose Determines if the property editor can paint a representation of the property.
syntax public boolean isPaintableO
description This method returns fal se by default. If this property editor can paint a repre-
sentation of the property, this method should be overridden to return true. For
example, if the property is a color, this method could paint the colon Or if the
property is an image, it could paint a scaled version of the image.
This method is typically called by the bean editor. If it returns true, the bean
editor will also call this property editor's pai ntVal ue() method whenever the
property value must be painted.
PropertyEditorSupport
java.beans
paint Val ue()
Note: The Beanbox in В1Ж 1.0apr97 ignores this method unless supports-
CustomEdi tor О also returns true.
returns true if the property editor can paint a representation of lhe property; false
otherwise.
A
example See getCustomEditorO.
В
paint Val ue()
E PURPOSE Called to paint a representation of the property value.
F SYNTAX public void paintValue(Graphics g, Rectangle box)
G DESCRIPTION If isPaintableO is true» this method will be called by the bean editor to
H 1 J К L M N (J Q R PARAMETERS box allow the property editor to paint a representation of the properly value within lhe box. For example, if the properly is a color, this method could paint the color in the box. Or if the property is an image, this method could paint a scaled version of the image in the box. By default, this method does nothing, h is called each time the property editor fires a property change event. The size and location of box is determined by the bean editor and cannot by specified by the property editor. If this method might paint outside the rectangle specified by box. it must set the clipping rectangle on g, Note: When the Beanbox in BDK 1.0apr97 is used, the width and height of box are 2 pixels too wide and 2 pixels too high. Subtract 2 from both the width and height to get the true dimensions. A non-null Rectangle within the graphics object on which to paint.
S g A non-null graphics context on which to paint.
T SEI: ALSO j ava.awt.Graph!cs, java.awt.Rectangle.
u EXAMPLE See getCustomEditorO.
v
w PropertyEditorSupportO
x purpose Constructs a new PropertyEdi torSupport instance.
Y syntax protected PropertyEditorSupportO
У protected PropertyEditorSupport(Object source)
1280
java.beans Property EditorSupport re mo v e Property Change Li stener()
DESCRIPTION This constructor is typically called by a bean editor while it is creating prop- erty editors for each of the bean's properties. If this constructor is overridden by a subclass, the subclass must call the superO* The source object will be included in any property change events that this property editor support object tires. If source is not specified, it defaults to the new property editor support object itself.
PAR AMI J ERS source The non-null object that will be generating property change events.
removeProperty Changel JstenerQ
PURPOSE Stops a listener from receiving property change events.
SYNTAX public synchronized void removePropertyChangeListener(PropertyChangel istener listener)
DESCRIPTION This method removes listener from the listener list. If listener is not in the listener list, the method call is ignored. The removed listener should be prepared to receive a few more property change events. See PropertyChangeLi stener for more details. Unless you need to distribute events in a way different from this implementa- tion. it is not necessary to override this method. However, if this method is overridden, then two other methods must also be overridden: addProperty- ChangeLi stenerO and fi rePropertyChangeO.
PARAMETERS listener A non-null property change event listener.
SEE AL.SO addPropertyChangeListenerO » fi rePropertyChangeO.
EXAMPIT. See the PropertyChangeEvent class example.
setAsTextQ
PURPOSE Converts a string representation of a property value into an object of the prop- erty type.
SYNTAX public void setAsText(String text) throws 111ega1ArgumentException
DESCRIPTION This method, by default, calls setValue() with text. If the property editor does not have a custom editor and the bean property is not a string, this method should be overridden to convert text to a value in the property type.
PropertyEditorSupport
java.beans
setAsTextt)
If the property type is a primitive type. the new value must be wtapped in (he
appropriate wrapper object. For example, if the property type is boolean, then
the new value must be wrapped in a Boolean object.
If text is successfully converted into a valid properly value, this method must
call setValueO with the new value. (Note that the value passed to set-
ValueO must be a new instance of the property type: this method must not
modify the current property value.) setValueO will notify the bean editor
that the value has changed.
P.XRAMl I IRS
text The non-null string representation of the properly value.
exci rito\s
Ill egal ArgumentExcept! on
II text cannot be converted to a valid property value.
sit. vise getAsTextO, java. 1 ang. Il 1 egal Argumen tFxcepti on , setValueO.
EXAMPLE
File Edit View Help
I КЛ RE 320: IPEditor.
1'his example bean has a property called “ip." which has the type Ip (T(T/IP
address). The bean makes the ip property editable by providing a property edi-
tor called IpEditor. The IpEditor converts the Ip ty pe to and from the dot-
ted notation. which has the form “by te.by te.by le.by le." Il overrides the
setAsTextO method, which parses such strings and. if the string is valid,
calls the setValueO method. See Figure 320.
There is no need to override the getAsTextO method, since, by default, the
getAsTextO method calls the properly value’s toString() method. Talling
the Ip object’s toStringO method yields the desired string.
A bean-info is necessary to associate IpEditor with the bean's ip property.
The bean-info must be defined in a class with the bean’s name appended with
“Beaninfo.’’ in this case. BeanBeanlnfo.
1282
java.beans
PropertyEditorSupport
setAsTextO
Bean.java
import java.awt.'-;
import java.beans.^*;
public class Bean extends Panel {
Ip curlp = new Ip(0x7f000001); // 127.0.0.1
// Use a label to display the current flavor.
Label 1 = new Label(curlp.toString());
public BeanO {
add(l);
}
public Ip getlpO {
return curlp;
}
public void setlp(lp ip) {
curlp = ip;
1 .setText(ip. toStringO) ;
}
}
Г
mani fest.txt:
Name: Bean.cl ass
Java-Bean: True
jar command:
jar cfm bean.jar manifest.txt Bean*.class Ip--.class
V
Bean Bean Info, java
import java.beans.*;
public class BeanBeanlnfo extends SimpleBeanlnfo {
public PropertyDescriptor[] getPropertyDescriptorsO {
PropertyDescriptor pd[] = new PropertyDescriptor[1];
try {
pd[0] - new PropertyDescriptor("ip", Bean.cl ass);
pd[01.setPropertyEdi torClass(IpEditor.class);
return pd;
} catch (Exception e) {
e.printStackTraceO ;
return nul1;
}
}
1
Ip.java
public class Ip {
int ipaddr;
Ip(int ipaddr) {
this.i paddr = i paddr;
}
public String toStringO {
int v — ipaddr;
String result = ;
PropertyEditorSupport
set Value ()
java.beans
for (int i-0; i <4; th) {
if (i > 0) {
result *= ;
}
result += (v»((3-i)*8))&0xff;
}
A return result;
}
В }
IpEditor.java
j} import java.beans.*:
import java .util . ';
к
public class IpEditor extends PropertyEditorSupport {
j; // Make sure the string is in the form of an ip address.
public void setAsText(String text) throws II 1egalArgumentfxception {
G // Break text up into strings separated by dots.
Stri ngTokenizer st = new StringTokenizer(text, ’’.”):
int result -= 0;
I try {
for (int i^0; i<4; i++) {
j int t = Integer.parselnt(st .nextlokenO) ;
K if (t < 0 .| t > 255) {
throw new II 1egalArgumentException(text);
1. }
result (t<<(3-i)*8);
M >
setValue(new Ip(result));
\ } catch (Exception e) {
// It doesn’t matter what the exception is.
O }
____ throw new IllegalArgumentException(text);
n
Q
R
s setValueO
T O I t
purpose Sets a new value tor the property.
U
syntax public void setValue(Object value)
V
description By default, this method saves value in a private field and tires a property
W change event to any listeners. There is typically no need to override this
X method.
This method is called by the Beanbox to initialize rhe property editor just after
the editor is created. It is also called whenever the user changes the value of
z the property. For example, if the property is the label of a bunon. this method
will be called each time the user changes the button's label.
1284
java.beans
PropertyEditorSupport
supportsCustomEditor()
If the value has indeed changed, the caller should create a completely new
instance of the value before calling setValueQ: that is,
getValueQ != value.
See the PropertyEditor class description for more details. lhe new value
should be stored in a private field in the properly editor. The bean editor will
later retrieve the new value (via a call to getVal ueQ) and then directly update
the property value in the bean.
This method may also be called by setAsTextQ when a string representation
of the property value is converted into an object of the property type.
If the property type is a primitive type, the new value must be wrapped in the
appropriate wrapper object. For example, if the property type is boolean, then
the new value must be wrapped in a Boolean object.
This method must also fire a property change event to any property change
event listeners. The event should be a multichange event (see Property-
ChangeEvent). so the property name, old value, and new value should all be
null.
PARAMETERS
value I'he possibly null new property value.
SEF.At.so getValueQ t setAsTextQ.
example See the class example. getCustomEditorQ. and setAsTextQ.
supportsCustomEditor()
purpose Determines whether the properly editor supports a custom editor.
syntax public boolean supportsCustomEditorQ
description This method returns fal se by default. If the property editor supports a custom
editor, it should override this method and have it return true.
Note: The Beanbox in BDK 1.0apr97 ignores this method unless isPaint-
ableQ also returns true.
returns fal se. Override if a custom editor is supported.
see also getCustomEdi torQ.
example See getCustomEditorQ.
java.beans
Property VetoE x cep ti о n
Syntax
public class PropertyVetoException extends Exception
Description
When a constrained property is about to be changed, a bean must fire a vetoable property
change event to all vetoable change listeners (see VetoableChangeListener). When a veto-
able change listener receives the change property event, it can decide to wo the change
request, (hereby canceling the change. Il does this by throwing PropertyVetoException.
See Figure 321. For more details on this process, see VetoableChangeLi stener and Veto- S
ableChangeSupport.
X FIGURE 321: Constrained Property Event Flow,
1286
java.beans
Property VetoException
getPropertyChangelivenK)
linbfBER SUMMARY
Constructor
PropertyVetoExceptionQ Constructs a PropertyVetoException instance.
Get Event Method
getPropertyChangeEventQ Retrieves the exception's property change event.
>e Also
. ropertyChangeEvent, VetoableChangeListenert VetoableChangeSupport.
Example
See the VetoableChangeLi stener class example.
getProperty ChangeEventf)
purpose Retrieves the exception's property change event.
symax public PropertyChangeEvent getPropertyChangeEventO
returns The exception's possibly nul 1 property change event.
example See the Vetoabl eChangeLi stener example.
PropertyVetoException!)
purpose Constructs a PropertyVetoExcepti on instance.
syntax public PropertyVetoException(String msg, PropertyChangeEvent
evt)
description The evt parameter should be the property change event that is being vetoed.
PARAMETERS
evt The possibly nul 1 property change event that was vetoed.
msg A possibly null string describing the reason for the veto.
example See the VetoableChangeLi stener class example.
java.awt
Rectangle
Syntax
public class Rectangle implements Shape, Serializable
Description
/X rectangle represents a rectangular area on a 2D plane. A rectangle is defined by four values:
л\ v, width, and height. r and у define the юр-lett corner of the rectangle: width and height
define the si/e of the rectangle. Rectangles are typically used in the layout of components and
in graphics operations.
When using the methods in this class, note whether a new rectangle is returned. Some
methods modify the current instance, while others return a new instance. In general, when hav-
ing a rectangle instance returned in a method call. either have a copy returned, if you need to
retain the instance, or have the instance discarded after it is returned. If you have passed a rect-
angle instance in a method call and wish to continue using the instance, note whether lhe
method will either retain the instance or copy the values.
MEMBER SUMMARY
Constructor
RectangleQ
Rectangle Tests
equals Q
containsO
IntersectsQ
isEmptyQ
Rectangle Operations
addQ
getBoundsQ
getlocationQ
getSizeO
g row О
intersect! onQ
setBoundsQ
setLocation()
Creates a new Rectangle instance.
Determines if an object is equal to this rectangle.
Determines if a point lies inside this rectangle.
Determines if a rectangle intersects with this rectangle.
Determines if this rectangle has any area.
Enlarges this rectangle.
Retrieves a new instance of this rectangle's bounds.
Retrieves the coordinates of this rectangle's top-left comer.
Retrieves the width and height of this rectangle.
Shifts all four edges of this rectangle.
Calculates the intersection of a rectangle w ith this rectangle.
Modifies this rectangle's bounds.
Moves this rectangle to a new’ location.
1288
java.awt
Rectangle
MEMBER SUMMARY
setSizeO translateO unionO Modifies this rectangle's size. Moves this rectangle by a relative distance. ; Calculates the union of a rectangle w ith this rectangle.
Fields height width X У Holds the rectangle's height. Holds the rectangle's width. Holds the rectangle's л-coordinate. Holds the rectangle's v coordinate.
Hash Code Method hashCodeО Calculates the hash code for this rectangle.
Debugging Method toStringO Generates a string representation of this rectangle.
Deprecated Methods i nside() move О reshapeQ resizeO Replaced by contai nsQ. Replaced by setLocation(). Replaced by setBounds(). Replaced by setSizeQ.
See Also
java. i о. Se ri al izable, Shape.
Example
This example demonstrates how to implement drag-
and-drop within a frame. The program creates three
coins and three slots in the three primary colors. The
coins can be dragged over a slot and dropped on it. A
coin changes color only if it's over the same-colored
slot. If the coin is dropped on the proper slot, the coin
disappears. See Figure 322.
The double-buffering technique is used to elimb
nate flicker during the dragging of the coins.
import java.awt.*;
import java.awt.event ;
class Main extends Frame {
Main() {
super(“Rectangle Example");
^Rectangle Example РП F
HGLRE322: Rectangle.
Rectangle
java.awt
add(new ImageCanvas(), Border! ayout.CENTER);
setSize(200, 200);
show();
}
public static void main(Stri ng[] args) {
Л new MainO ;
}
В }
C class ImageCanvas extends Component {
int numCoins - 3;
D Rectangle[] coins - new Rectangle[numCoins];
Rectanglef] slots = new RectanglefnumCoins];
E Color[] colors = {Color.red, Color.green, Color.blue};
Image bbuf;
F Graphics bbufG;
G ImageCanvasQ {
for (int i=0; i<numCoins; i-ь*) {
H coins[i] = new Rectangle(rand(50), rand(50), 50, 50);
slotsfi] = new Rectangle();
I }
addMouseLi stener(new MouseEventHandler());
J addMouseMotionListener(new MouseMotionEventHandlerO);
}
К
int rand(int r) {
L return C nt)Math. floor (Math. randomO-r) ;
I
M
public void paint(Graphics g) {
N update(g);
}
О
public void update(Graphics g) {
p int w - getSize().width;
int h - getSize().height;
Q
if (bbuf -- null
ll w > bbuf.getWidth(nul1)
j; h > bbuf.getHeight(nul 1)) {
S bbuf = createlmage(w. h);
bbufG <- bbuf .getGraphicsO ;
T }
U bbufG.setColor(Color.white);
bbufG.fi1lRect(0, 0. getSize().width, getSize().height);
V
// paint slots
W for (int i =0; i<numCoins; i ♦•*) {
slots[i1.setBounds(i*w/3, h-30, w/3, 30);
X slots[i].grow( 5, 2);
bbufG.setColor(colors[i ]);
Y bbufG.fillRect(slots[i].x, slots[ij.y,
slots[i].width, slotsfi].height);
Z }
// paint coins
for (int i-0; icnumCoins; i++) {
1290
java.awt
Rectangle
if ( !coinsfi J : isEmptyO) {
if (dragging == i && coins[i1.intersects(slots[i])) {
bbufG.setColor(Color.black);
} else {
bbufG.setColor(colors[iJ);
}
bbufG. fi 1 lOval (coins[ i 1 .x, coins[i] .у,
coins[i J.width, coi nsfi].height);
}
}
g.drawTmage(bbuf, 0, 0, this);
}
int dragging -1;
Point offset;
// Handles mouse presses and releases
class MouseEventHandler extends MouseAdapter {
public synchronized void mousePressed(MouseFvent evt) {
int x - evt.getXO, у evt.getYO;
for (int i=coins.1ength-1; i>^0; i—) {
if (! coi ns [i j. i sEmptyO && coi ns[i ]. contai ns(x , y)) {
dragging = i ;
offset - new Point(coins И J.x-x , coins[i'.y~y);
return;
}
}
}
public synchronized void mouseReleased(MouseEvent evt) {
if (dragging >= 0) {
if (coins[draggingj.intersects(slots[draggingl)) {
coins[dragging].width - 0; // make it empty
dragging - -1;
}
repaintO;
}
}
}
// Handles mouse drags
class MouseMotionEventHandler extends MouseMotionAdapter {
public synchronized void mouseDragged(MouseEvent evt) {
int x = evt.getXO, у = evt.getYO;
if (dragging >= 0) {
coins[dragging].setLocation(x, y);
coins[dragging].translate(offset.x, offset.y);
repai nt();
}
}
}
}
java.awt
Rectangle
add()
add()
— — — — — — — _
PURPOSE Enlarges this rectangle.
SYNTAX public void add(int x, int y) public void add(Point point) public void add(Rectangle rectangle)
DESCRIPTION This method enlarges this rectangle, if necessary to include another point or rectangle. If x and у are specified, they define a point: the rectangle's bounds are modified to be just large enough to include the point. If point is specified, the rectangle's bounds are modified to be just large enough to include the point. If rectangle is specified, the rectangle's bounds are modified to be just large enough to include all of the points in the rectangle. The following invariants for add() hold: • After r.add(x, y), r.contains(xT y) is true. • After r.add(point), r.contains(point.x, point,y) is true • After r.add(rectangle). r.contains(r.union(rectangle)) is true.
PARAMETERS point rectangle X У The non-null point to include. The non-nul 1 rectangle to include. The v-coordinate of the point to include. The y-coordinate of the point to include.
SEE ALSO contai ns().
EXAMPLE. This example takes points defined by clicking the mouse and adds them to a rectangle:
Rectangle rect = new RectangleQ;
public void mousePressed(MouseEvent evt) {
int x ' evt.getXO, у = evt.getYO;
rect.add(x, y);
downX = x;
downY -= y;
}
contains()
PURPOSE Determines if a point lies inside this rectangle.
SYNTAX public boolean contains(int x, int y) public boolean contains(Point pt)
DESCRIPTION A point is inside a rectangle if lhe following condition is true: pt.x >= x && pt.y >*• у && (pt.x-x) < width && (pt.y y) height
1292
Rectangle
equal s()
java.awt
The point can be specified either by its л- and v- coordinates or by a Point instance pt.
PAR.AMHIhRS Pt X The point to check. The point’s л-coordinate.
У The point’s v-coordinate.
RETURNS true if the point is inside the rectangle: fal se otherw ise.
EXAMPLE This example defines a mousePressedO method that responds only if the user clicks inside the rectangle rect.
Rectangle rect = new RectangleO;
public void mousePressed(MouseEvent evt) {
int x = evt.getXO, у - evt.getYO;
if (rect.contains(x, y)) {
} } // (x, y) are inside the rectangle; perform some task
equalsf)
PURPOSE' Determines if an object is equal to this rectangle.
SYNTAX public boolean equalsfObject object)
DESCRIP7ION Two rectangles are equal if their л- and у-coordinates, width, and height are identical.
PARAMETERS object The object to check for equality. This cun be nul 1.
RETURNS true if object is a rectangle and is equal to this rectangle; fal se otherwise.
OVERRIDES java.lang.Object.equals().
EXAMPLE*, This example defines a method that searches through an array of rectangles looking for one that exactly matches a particular rectangle. If a match exists, the method returns the index of the rectangle; otherw ise, it returns '1.
Rectangle[] rects = new Rectangle"100];
int findEqual(Rectangle r) {
for (int i-0; i<rects.1ength; i+*) {
if (r.equals(rectsfi1);
return i;
}
return -1;
1
Rectangle
java.awt
getBounds()
getBounds()
purpose Retrieves a new instance of this rectangle.
symax public Rectangle getBoundsO
returns A new instance of this rectangle.
see Al so setBoundsQ.
EXAMPLE
Rectangle rect = new Rectangle(0, 10, 50, 100);
Rectangle bounds = rect .getBoundsO; // new rectangle (0, 10, 50, 100);
getLocation()
pvrpo.se Retrieves the coordinates of this rectangle's top-left corner.
syntax public Point getLocationO
returns A new non-nul 1 point of this rectangle's top-left corner.
see Ai so setLocation().
exampi e
Rectangle rect = new Rectangle(0, 10, 50, 100);
Point corner = rect.getLocationO; // (0, 10)
getSize()________________________________________________________________________
purpose Retrieves the width and height of this rectangle.
svntax public Dimension getSizeO
reti rns A non-null Dimension object created using this rectangle's width and height.
see al so setSizeO.
EXAMPLE
Rectangle rect - new Rectangle(0, 10, 50, 100);
Dimension dim = rect.getSizeO ; // 50 x 100
growO________ _____
purpose Shifts all four edges of this rectangle.
syntax public void grow(int hor, int ver)
1294
java.awt Rectangle
hashCode()
DESCRIPTION. This method modifies this rectangle such that its left edge is shifted left by hor and its width is increased by 2 * hor. Also, its top edge is shifted up by ver and its height is increased by 2 * ver. hor or ver can be negative. If either value is negative, the rectangle will shrink instead.
PARAMETERS hor ver The amount to shift the rectangle's left and right edges. The amount to shift the rectangle's top and bottom edges.
EXAMPLE This example defines a keyPressedO method, whereby if *g’ is pressed, the rectangle increases in width and height by 2 pixels each and if ’s' is pressed, the rectangle decreases in width and height by 2 pixels each.
public void keyPressedCMouseEvent evt) {
char key = evt.getKeyCharO;
if (key == ’g’) {
rect.grow(l, 1); // enlarge
} else if (key == ’s’) {
rect.grow(-l, -1); // shrink
}
}
hashCode()
PURPOSE Calculates the hash code for this rectangle.
SYNTAX public int hashCode()
DESCRIPTION A rectangle’s hash code is an integer calculated from the rectangle’s bounds. If equals(rl, r2) is true, then rl and r2 will have the same hash codes; oth- erwise, rl and r2 will likely have different hash codes.
OVERRIDES java. lang. Object .hashCodeO.
RETURNS This rectangle’s hash code.
EXAMPLE See equals() and java.1ang.Object.hashCode().
height
PURPOSE This field holds this rectangle’s height.
SYNTAX public int height
DESCRIPTION To change the height of this rectangle, use setSi zeO.
SEEALSO getSizeO, setSizeO, width.
l
java.awt
Rectangle
inside()
example This example paints a rectangle on the screen;
Rectangle rect new RectangleO;
public void paint(Graphics g) {
. g.fi11Rect(rect.x, rect.y, rect.width, rect.height);
A }
В
c inside() DEPRECATED
D 14 RPOS1: Replaced by contains().
e SYM AX public boolean inside(int x, int y)
F PARAML 1 ERS
G X The point's л-coordinate.
II У The point's y-coordinate.
1 RETURNS true if the point is inside the rectangle; fal se otherwise.
J DEPRECATION Replace the usage of this deprecated method, as in
if (rect.inside(x, y)) ...
К with
I. if (rect.contains(x, y)) ...
M
N intersection()
() PI RPOSE Calculates the intersection of a rectangle with this rectangle.
P SYNTAX public Rectangle intersection(Rectangle rectangle)
В DESCRIPTION The intersection of two rectangles is defined to be the set of all points that lie in both rectangles.
s PARAMETERS
T rectangle The non-null rectangle with which to intersect.
t; RETI ’RNS A new non-null Rectangle instance that is the intersection of this rectangle
v and rectangle.
w EXAMPLE This example paints two rectangles and then paints their intersection red:
x Rectangle rl = new RectangleO;
Rectangle r2 - new RectangleO;
public void paint(Graphics g) {
g.fi11Rect(ri.x, rl.y, rl.width, rl.height);
g,fi11Rect(r2 .x , r2.y, r2.width, r2.height);
g.setColor(Color.red);
Rectangle r = rl.intersection(r2);
1296
java.awt Rectangle intersects()
g.fillRect(r.x, г.у, г.width, г,height);
}
intersects()
PI RPOSE Determines if a rectangle intersects with this rectangle.
SYNTAX public boolean intersects(Rectangle rectangle)
DESCRIPTION The intersection of two rectangles is defined to be the set of all points that lie in both rectangles. Two rectangles intersect if the intersection is not empty.
PARA МЬЛ LRS rectangle The non-null rectangle to intersect with this rectangle.
RETURNS true if this rectangle intersects rectangle; false otherwise.
EXAMPLE See the class example.
isEmptyj)
PURPOSE Determines if this rectangle has any area.
SYNTAX public boolean isEmptyf)
DESCRIPT ION Л rectangle is empty or has no area if either of its width or height is less than or equal to 0.
RETURNS true if the rectangle is empty; false otherwise.
EXAMPLE See the class example.
move() DEPRECATED
PURPOSE Replaced by setLocation().
SYNTAX public void move(int x, int y)
PARAMETERS X У The rectangle's new л-coordinate. The rectangle's new y-coordinate.
DEPRECATION Replace the usage of this deprecated method, as in rect.move(x, y); with rect.setLocationCx, y);
Rectangle
java.awt
Recranglef)
Rectanglef) pi’rposf. Constructs a new Rectangle instance. simax public RectangleO
A public Rectangle(int width, int height)
В public Rectangle(int x, int y, int width, int height) public Rectangle(Point point)
c public Rectangle(Dimension dimension) public Rectangle(Point point. Dimension dimension)
D E F G public RectanglefRectangle rect) dlscripiiox This constructor creates a new Rectangle instance that has the specified bounds. Various ways are available to initialize the rectangle's bounds. If no parameters are specified, x. y. width, and height all default to 0. If only width and height are specified, x and у default to 0. If only a point is speci-
H J tied, the rectangle’s top-left corner is at point, but width and height default to 0. If only a dimension is specified, x and у default to 0 and width and height are taken from dimension. If both a point and a dimension are speci-
J fied. the rectangle’s top-left corner is at point and width and height are
К taken from dimension. If a rectangle rect is specified, the bounds from rect
I are used
L- M PARAMETERS dimension The non-null dimension specifying the new rectangle's size.
N height The height of rhe rectangle.
О point The non-null point specifying the new rectangle’s top left corner, rect The rectangle specifying the bounds to use.
P wi dth I'he w idth of the rectangle.
Q и s T x The new rectangle's л-coordinate. у The new rectangle's v-coordinate. example This example creates a hundred rectangles and lays them out in a 10-x-K) grid: Rectanglef] rects - new Rectangle[100];
L for (int x=0; x<10; x++) { for (int y=0; y<10; y++) {
V W rects[i] new Rectangle(xv10. y*10f 10, 10); } }
X V z reshape() deprecated purpose Replaced by setBounds(). syntax public void reshape(int xT int y, int width, int height)
1298
Rectangle
resizef}
java.awt
PAR A MH Г HRS height width The rectangle's new height. The rectangle’s new width.
X The rectangle’s new a-coordinate.
У The rectangle's new y-coordinate.
deprecation Replace lhe usage of this deprecated method, as in rect.reshape(x, y. width, height); with rect.setBounds(x, y, width, height);
resizef) DEPRECATED
PURPOSE Replaced by setSi ze().
SYNTAX public void resize(int width, int height)
PARAMETERS height width The rectangle’s new height. The rectangle s new width.
DEPRECATION Replace the usage of this deprecated method, as in rect.resize(width, height); with rect.setSizetwidth. height);
setBounds(
*
PURPOSE Modifies this rectangle's bounds.
SYNTAX public void setBounds(int x, int y, int width, int height) public void setBounds(Rectangle rect)
description This method modifies the rectangle's top-left comer to be at x and у and its size to be width and height. If rect is specified instead, rect’s bounds are used for this rectangle.
PARAMEIERS height rect width The reciangle's new height. The non-null rectangle specifying the new bounds. The rectangle s new width.
X The rectangle's new v coordinate.
У l he rectangle's new y-coordinate.
SEE AL,SO getBoundsO.
Rectangle
setLocationf)
java.au t
example This example defines two methods for handling mouse events that together
allow the user to stretch a rectangle. The mousePressedQ method sets the
top-left corner of the rectangle, and the mouseDraggedO method adjusts the
dimensions of the rectangle.
Л
Rectangle rect - new RectangleO;
В int downX, downY;
C public void mousePressed(Mousetvent evt) {
downX - evt.getXO;
□ downY - evt.getYO;
}
E
public void mouseDragged(MouseEvent evt) {
E rect.setBounds(downX, downY, evt.getXO-downX, evt.getYO downY);
}
G
H
setLocationf)
purpose Moves this rectangle to a new location.
к SYNTAX public void setLocation(int x, int y)
L DESCRIPTION public void setLocation(Point pt) The method seis the top-left corner of this rectangle to be at the new specific
M location. The new location can be specified by using either a Poi nt instance o.
N a - and y- coordinates.
() PARAMETERS
Pt The non-nul 1 point specifying the new coordinates.
г X Fhe rectangle s new л-coordinatc.
Q У Lhe rectangle’s new y-coordinate.
SEE ALSO getLocationO, translated).
s 'Г EXAMPLE This example defines a mouseDraggedO method that drags around a rectan- gle:
U
Rectangle rect - new RectangleO;
V public void mouseDragged(MouseEvent evt) {
rect.setLocation(evt.getXO , evt.getYO);
Yv repaintO;
}
X
Y
Z
1300
Rectangle
setSizef)
java.awt
setSize()
PURPOSI: Modifies this rectangle's size.
SYNTAX public void setSize(int width, int height) public void setSize(Dimension dim)
DESCRIPTION This method modifies the rectangle's size to he width and height or the dimensions specified by dim.
PARAMETERS dim height width The non-null dimension specifying the new size. The rectangle's new height. The rectangle's new width.
SEE ALSO getSizeO.
EXAMPLE This example defines a mouseDraggedO method that allows you to resize a rectangle:
Rectangle rect = new RectangleO;
public void mouseDragged(MouseEvent evt) {
int x = evt.getXO, у = evt.getYO;
rect.setSize(x-rect.x, y-rect.y);
}
toString()
PURPOSE Generates a string representation of this rectangle.
SYNTAX public String toStringO
DESCRIPTION This method generates this rectangle's string representation, which consists of the rectangle’s bounds. This method is typically used for debugging.
RETURNS A non-null string representing the rectangle's state.
OVfcRRIPIsS j ava.1ang.Obj ect.toStri ng().
EXAMPLE See j ava.1ang.Object.toSt ri ng().
translate!)
purpose Moves this rectangle by a relative distance.
syntax public void translate(int dx, int dy)
Rectangle
union()
java.awt
DESCRIPTION This method modifies this rectangle so that its л-coordinate is shifted by dx and its y-coordinate is shifted by dy. In particular, the rectangle's new л-coor- dinate is x + dx and the rectangle’s new y-coordinate is у + dy.
A PARAMETERS dx The amount by which to shift the rectangle's л-coordinate.
В dy The amount by which to shift the rectangle’s y-coordinate.
C SEE ALSO setLocationO.
D EXAMPLE This example creates a thread that moves a rectangle toward the southeast, one
E pixel at a time, every 30 ms:
F Rectangle rect = new Rectangle(;
public void run() {
for (int i=0; i<100; i++) {
rect .translated, 1);
repaint();
try {
Thread,sleep(30) ;
J } catch (Exception e) { e.printStackTraceO
К }
L }
M union()
N PURPOSE Calculates the union of a rectangle with this rectangle.
о SYNTAX public Rectangle union(Rectangle rectangle)
p DESCRIPTION The union of two rectangles is defined to be the smallest rectangle that
Q PARAMETERS includes all points in both rectangles.
s rectangle The non-null rectangle with which to perform the union.
T RETURNS Л new non-null rectangle instance that is the union of this rectangle and
и rectangle.
V EXAMPLE This example paints two rectangles and then paints a box around them:
w Rectangle Rectangle rl = new RectangleO; r2 = new RectangleO;
public void paint(Graphics g) {
g,fillRect(rl.x, rl.y, rl.width, rl.height);
g.fillRect(r2.x, r2.y, r2.width, r2.height);
g.setColor(Color.red);
Rectangle r » rl.union(r2);
g.drawRect(r,x, r.y, r.width, r.height);
1302
java.awt
Rectangle
width
width
purpose This Held holds this rectangle’s width.
syntax public int width
description To change the width of this rectangle, use setSi zeO.
seealso getSizeO, height, setSizeО.
example This example paints a rectangle on the screen:
Rectangle rect = new RectangleO;
public void paint(Graphics g) {
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
X
purpose This field holds this rectangle’s л coordinate.
SYNTAX public int X
description To change the л-coordinate of this rectangle, use setLocati on ().
seealso getLocation(), setLocation(), y.
exampi e This example paints a rectangle on the screen:
Rectangle rect ~ new RectangleO;
public void paint(Graphics g) {
g.fil1Rect(rect.x, rect.y, rect.width, rect.height);
}
У________________________________________ ________ ____________________
purpose This Held holds this rectangle’s y-coordinate.
SYNTAX public int у
description To change the y-coordinate of this rectangle, use setLocationQ-
seealso getLocationO , setLocationO , x.
example This example paints a rectangle on the screen:
Rectangle rect new RectangleO;
public void paint(Graphics g) {
g.fi11Rect(rect.x, rect.y, rect.width, rect.height);
}
java.awt.image
ReplicateScaleFilter
F
g Syntax
public class ReplicateScaleFilter extends ImageFilter
H
1 Description
j The replicate scale filter is an image filter that scales images using a simple pixel replication
algorithm. When a dimension of an image is scaled down, pixels are omitted. For a higher-
quality scaling image filter, sec AreaAveragingScaleFilter.
L This image filter is meant to be used in conjunction with a Fi 1 teredlmageSource object,
yj which assumes the responsibility for delivering an image to this image filter to scale. See
ImageFilter for more information about the image filtering architecture.
MEMBER SUMMARY
; Constructor Repli cateScalef i 1 ter() Constructs a Repl icateScaleFiIter instance.
Image Consumer Methods Called by the Image Producer setDimensionsO Called to deliver the dimensions of the source image. setPixels() Called to deliver pixels to this image filter. setPropert iesO Called to deliver the properties for the source image.
Protected Fields destHeight destwi dth outpixbuf sreeols[] srcHei ght srcrows[] srcWidth Holds the height of the scaled image in pixels. : Holds the width of the scaled image in pixels. Holds a row of pixel values. Holds an array of special values used by the replication algo- rithm. Holds the height of the original image in pixels. Holds an array of special values used by the replication algo rithm. Holds the width of the original image in pixels.
_______ .J
1304
java.awt.image
.. teScaleFilter
Rephca*>-------------
--------dost Height
See Also
Fi1teredlmageSource.
Example
See the AreaAveragingScaleFi 1 ter class example.
A
В
C
destHeight D
PURPOSE Holds the height of the scaled image in pixels.
SYNTAX protected int destHeight
DESCRIPTION This value of this field is the same as the height value supplied to the cPllsCruc G tor. H
SEE ALSO ReplicateScaleFiIter(). ।
destVVidth J К
PURPOSE Holds the width of the scaled image in pixels.
SYNTAX tv protected int destWidth
DESCRIPTION This value of this field is the same as the width value supplied to the ^,|lslruc tor. <
SEE ALSO Repl1cateScaleFiIterО. F c
outpixbuf , I 5
PURPOSE Holds a row of pixel values.
SYNTAX protected Object outpixbuf
DESCRIPTION This field contains either an array of bytes or an array of pixels. depe^mk on which setPixelsO method is used, It is used by the image filter Ч10Ге a row of scaled pixels. \
ReplicateSealeFilter()
PURPOSE Constructs a Repl i cateScal eFi 1 ter instance.
SYNTAX public ReplicateScaleFiIterfint width, int height)
ReplicateScalcFilter java.au (.image
setDimensionsO
DESCRI PTIOS This method creates a replicate scale filter that scales an image to width and height. This image filter is meant to be used in conjunction with a Fil- teredlmageSource object, which assumes the responsibility for delivering an image to this image filter to scale. If width is negative, it defaults to the width of lhe incoming image. Likewise for hei ght.
PARAMETERS height The new height of the image in pixels. If < 0. defaults to the height of the incoming image.
width The new width of the image in pixels. If < 0. defaults to lhe width of lhe incoming image.
se-л: Al so filteredlmageSource.
EXAMPLE See the AreaAveragingScaleFiIter class example.
setDimensionsO
PURPOSE Called by the image producer to deliver the dimensions of the source image.
SYNTAX public void setDimensions(int w, int h)
DESCRIPTION Although this method is public, il is not meant to be called. This method is part of the image filtering process and is called by an image producer. For more information on image niters, see ImageFiIter.
PARAMETERS height wi dth Fhc height of the image in pixels. The width of the image in pixels.
OVERRIDES ImageFi Iter. setDimensionsO.
SEE ALSO ImageConsumer.setDi mens!ons().
EXAMPLE See ImageConsumer.
setPixelsO
PURPOSE ("ailed by the image producer to deliver pixels to this image filter.
SV VI AX public, void setPixels(int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize)
DESCRIPTION Although this method is public, it is not meant to be called. This method is part of lhe image filtering process and is called by an image producer. For more information on image filters, see ImageFiIter.
1306
Г j a v a. a w t. i m age ReplicateScaleFilter set Propertied)
PARAMETERS h model off pi xels scansize w X У The height of the rectangle in which the pixels are destined. The non-null color model used to translate the pixel values. The index of the first pixel in the pi xel array. I’he non-null array of pixel values. The width to use when extracting pixels from the pixel array. I'he width of the rectangle in which the pixels are destined. The л-coordinate of the rectangle in which the pixels are destined. The v-coordinate of the rectangle in which the pixels are destined.
OVERRIDES Image!iIter.setPixels().
SEE ALSO ImageConsumer.setPi xel s ().
EXAMPLE See ImageConsumer.
setProperties()
pur post-: Called by the image producer to deliver the properties for the source image.
SYNTAX public void setPropertiesfHashtable props)
DESCRIPTION Although this method is public, it is not meant to be called. This method is part of the image filtering process and is called by an image producer. For more information on image filters, see ImageFi Iter.
PARAML I ERS props A non-null hash table of image properties.
OVERRIDES ImageFi1 ter.setProperti es().
SEE Al.SO ImageConsumer. setProperties().
EXAMPLE See ImageConsumer.setProperti es().
srccolsl ]
PURPOSE Holds an array of special values used by the replication algorithm.
SYNTAX protected int srccols[]
DESCRIPTION This field is not typically used by subclasses, since the values arc specific to the replicate scale filter replication algorithm.
ReplicateScaler liter
java.awt. image
srcHeight
srcHeight
PURPOSE! Holds the height of the original image in pixels.
SYNTAX protected int srcHeight
A DESCRIPTION This field is initialized when the image producer calls setDimensionsO.
В SEP A I.SO setDimensionsO.
C
D r; srcrows[]
E F PlRPOSE Holds an array of special values used by the replication algorithm.
G SYNTAX protected int srcrows[]
H DESCRIPTION This field is not typically used by subclasses, since the values are specific to
I the replicate scale filter replication algorithm.
J
К src Width
L PURPOSE Holds the width of the original image in pixels.
M SYNTAX protected int srcWidth
N DESCRIPTION This field is initialized when the image producer calls setDimensionsO.
О SEE ALSO setDimensionsO.
P
Q
S
T
1308
java.awt. image
RGB ImageFi I ter
...........J
• | ROBWgfeFilter Q
___________|
[mJ
Syntax
public abstract class RGBImageFiIter extends ImageFilter
Description
The RGBImageFi 1 ter class is used to modify the pixel values in an image. This can be done
by either modifying the colors in the color table of the image (if the image uses an index color
model) or modifying each pixel in the image. The former is much more efficient if color
changes don’t depend on the location of pixels. An example of this is a filter that simply
brightens all colors. The latter method is necessary if the color changes depend on the location
of the pixels. An example of this is a filter that gradually darkens pixels toward one edge of the
image.
This class is an abstract class and is meant to be subclassed. Only the f i 1 terRGBO method
needs to be overridden. This method is responsible for converting pixel values, fil terRGBO
receives the coordinates of the pixel so that it can convert the color based on the location of lhe
pixel. By default, all pixels in the image are filtered through filterRGBO. It is also possible
just to filter the colors in the color table by setting the field canFi1terlndexColorModel to
true. When this happens, all of the colors in the color table are passed through f i 1 terRGBO
and a new color model is created. This new color model is then used for the pixels that flow
through the filter.
pjEMBKtt SUMMARY
Image Consumer Methods Called by the Image Producer
setCol orModel О Called to deliver the color model of the source image.
setPixels О Called to deliver pixels to the image filter.
Continued
RGBImageFilter
java,awt.image
A
В
C
L>
F
Г
G
H
I
J
К
L
M
N
О
P
Q
R
S
T
I
V
w
X
Y
Z
MEMBER SUMMARY
Fields
canFiIterIndexColorModel
newmodel
ori gmodel
Color Model Substitution
substituteColorModel()
Filter Methods
f ilterlndexColorModelО
fi 1 terRCBQ
filterRCBPixelsQ
Indicates whether color filtering is applied to the color
table.
Holds the converted color model.
Holds the color model passed to lhe
setColorModel() method.
Replaces the color model of the source image.
Filters lhe colors in the color lahlc.
Oxerride to filter each pixel value.
Override to filler a hatch of pixel values.
Example
This example implements a gradient filler using the RGBIm-
ageFilter class. See Figure 323. The example displays an
image in a canvas, which in turn is embedded in a frame, rhe
image is brightened at the top-left corner and is gradually
darkened toward the bottom-right corner. Since the transfor-
mation of a pixel value depends on its location, canFiIter-
IndexColorModel must be false.
import java.awt.";
import java.awt.image.w;
import java.utiI.'•;
FIGURE 323; Gradient Filter
using RGBImageFilter.
class Main extends Frame {
Main(String filename) {
super(“RCBFi 1 ter Example'’);
add(new TmageCanvas(getToolkitO.getlmage(filename)),
BorderLayout.CENTER);
setSize(50, 100);
showO ;
}
static public void mai n(Stri ng [] args) {
if (args.length == 1) {
new Main(args[01);
} else {
System.err.println(“usage: java Main <image file>");
}
1
1310
_______RGBImageFilter
can Fi 1 terl n de x Color M ode I
java.awt. image
class ImageCanvas extends Component {
Image gradientimage;
ImageCanvas(Image image) {
GradientFiIter imgf = new GradientFi1ter();
ImageProducer ip = image.getSourceO; A
ip = new Fi1teredImageSource(ip, imgf);
gradientImage = getToolkit().createlmage(ip); В
repai ntO;
} c
public void paint(Craphics g) { D
g.drawlmage(gradientimage, 0, 0, this);
class GradientFilter extends RGBImageFilter {
float[] hsb = new float[3]; C
int width, height;
H
public void setDimensions(int w, int h) {
super.setDimensionsCw, h); I
width = w;
height = h; J
}
К
public int filterRGB(int x, int y, int rgb) {
Color c = new Color(rgb); L
Color. RGBtoHSBCc .getRedO , c .getCreen() , c.getBlueQ, hsb);
hsb[2] -= .5f - (float)x / width; M
hsb[2] += .5f - (float)y / height;
hsb[2] = Math.max(0.0f, Math.min(1.0f, hsb[2])); N
return Color.HSBtoRGB(hsb[0], hsbLl], hsb[2]);
} o
}
P
Q
и
canFilterlndexColorModel s
purpose Indicates whether color filtering is applied to the color table. T
syntax protected boolean canFilterlndexColorModel U
description The subclass of this filter should set this boolean value to indicate whether to V
color filter just the color table or every pixel. If canFilterlndexColorModel w
is set to true and if the image’s color model is indeed an index color model,
then all of the colors in the color model are transformed using the filter- x
RCBO method and the pixel values flowing through the filter are not modified. Y
If the color filtering does not depend on the position of the pixel values in the 2
image, then for the most efficient implementation, this field should be set to
true.
RGBImageFilter
canFi 1 ter I nde x Co 1 or M ode 1
java, aw (.image
seealso fil terRGBO , IndexColorModel , substi tuteCol orModel ().
EXAMPLE This example implements a brightness tiller. An image is painted in a canvas, which is in turn embedded in a frame. See Figure 324. HE^canFilterlndex... ВИ11EJ
A The image is passed through a brightness ж
В filler, which brightens or darkens all of the entries in the image’s color map. Typing a + brightens the image by 10%. and typing a - R
C FIGIRF. 324: Brightness Filter
D darkens the image by 10%. using RGBImageFi 1 ter.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.";
import java.uti1.*;
class Main extends Frame {
Main(String filename) {
super(“canFi1terlndexColorModel Example”);
add(new ImageCanvas(getToolkit().getImage(fi1 ename)),
BorderLayout.CENTER);
setSi ze(50, 100);
show();
static public void main(String[] args) {
if (args.length == 1) {
new Main(args[0]);
} else {
System.err.println(“usage: java Main <image file>”);
}
class ImageCanvas extends Component {
Image brightlmage;
Image image;
BrightnessFi1 ter imgf = new BrightnessFi1 ter();
ImageCanvas(Image image) {
this.image = image;
processlmage();
addKeyListener(new KeyEventHandler());
public void paint(Graphics g) {
g.drawlmage(brightlmage, 0, 0, this);
void processImageO {
ImageProducer ip = image.getSourceO;
ip = new FilteredImageSource(ip, imgf);
brightlmage = getToolkit().createlmage(ip);
repai nt();
}
1312
java. awt. image
RGBImageFilter
filterIndexColorModel()
class KeyEventHandler extends KeyAdapter {
public void keyTyped(KeyFvent evt) {
char key = evt .getKeyCharQ;
if (key -= * + ’) {
imgf.addBrightness(.if);
} else if (key -- ‘-') {
imgf.addBrightness( .If);
}
processImageO ;
}
}
}
class BrightnessFiIter extends RGBImageFilter {
float bDelta;
float[] hsb = new float[3];
int width, height;
BrightnessFi1ter() {
canFi1terlndexColor^odel * true;
}
public void setDiTensions(int w, int h) {
super. setDimensionsO, h);
width - w;
height = h;
}
public void addBrightness(float f) {
bDelta += f;
}
public int fi 1 terRGB(i nt x, int yt int rgb) {
// x and у are both -1
Color c - new Color(rgb);
Color. RGBtoHSB(c .getRedO , c.getGreenO, c.getBlueO, hsb);
hsb[2] - Math.max(0.0f, Math.min(l.Of, hsb[2] + bDelta));
return Color.HSBtoRGB(hsbL0J, hsb[l], hsb[2]);
}
}
filterlndexColorModelf)
purpose: Filters the colors in the color table.
SYNTAX public IndexColorModel fi1terlndexColorModel(IndexColorModel icm)
DESCRIPTION This method filters an index color model instance by running each entry in its color tables through the filterRGBO function that RGBImageFilter sub- classes must implement. TTiis method uses coordinates of -1 to indicate that a
RGBImageFilter
filtcrlndc\C\)lorModel( )
ja\ a.awl.image
color table entry rather than a pixel value taken from the image, is being fil-
tered.
PARAMLITRS
i cm
RLTl'RNS
LXAMPl.l.
Л
В
C
D
E
F
G
H
1
J
К
L
M
N
s
T
и
V
w
X
Y
z
The index color model instance to be filtered.
/X new index color model representing the fil-
tered colors.
litis example implements a filter that allows
you to specif) a color in the color table and
highlight those pixels in an image that use that
color. The example changes the highlighted
pixels to red. Sec Figure 325.
The frame contains a canvas, which displays
the image. At the bottom of the frame is a text
FKII Rl 325: Color
Highlighting I sing
RGBImageFilter.
field in w hich you can type an index of a color in the color table.
P
Q
import java.awt.';
i mport j ava. awt. i mage . *;
import j ava. awt. event . ;
import java.net.-';
import java.uti I.';
class Main extends Frame implements ActionListener {
ImageCanvas icv;
TextField textField - new TextFieldO;
Main(String filename) {
super(“fi1terlndexColorModel Example”);
try {
add(icv = new ImageCanvas(getToolkit().getlmage(fi1 enamel),
BorderLayout.CENTER);
add(textFi eld, BorderLayout.SOUTH);
textField.addActi onLi stener’(thi s);
} catch (Exception e) {
e.pri ntStackTrace();
}
setSi ze(50, 100);
show();
}
public void actionPerformed(ActionEvent evt) {
i cv.seeColor(Integer.parseint(textField.getText()));
textField.setText(““);
}
static public void main(String[] args) {
if (args.length — 1) {
new Mai n(args[0]);
} else {
System.err.println(“usage: java Main <image file>”);
}
}
}
1314
RGBImageFilter
tlherlndexColorModeK)
java, awt .image
class ImageCanvas extends Component {
Image seeColorlmage;
Image image;
SeeColorFilter imgf = new SeeColorFilter();
ImageCanvas(Image image) {
this.image - image;
processImageO;
}
void seeColor(int colorindex) {
imgf.seeColor(colorindex);
processImageO ;
1
public void paint(Graphics g) {
g.drawImageCseeColorlmage, 0, 0, this);
1
void processImageO {
ImageProducer ip = image.getSourceO ;
ip = new Fi lteredImageSource(ip, imgf);
seeColorlmage = getToolкit().createlmage(ip);
repaintO;
}
}
class SeeColorFilter extends RGBImageFi1 ter {
int colorindex ». -1;
SeeColorFilter() {
canFiIterlndexColorModel - true;
}
void seeColor(int colorindex) {
this.colorindex = colorindex;
}
public IndexColorModel fi1terlndexColorModel(IndexColorModel icm) {
int mapsize - icm.getMapSize();
byte r[] = new byte[mapsize];
byte g[] = new byte[mapsize];
byte b[] « new byte[mapsize];
icm.getReds(r);
icm.getGreens(g);
icm.getBlues(b);
if (colorindex >= 0) {
r[colorindex] = (byte)255;
g[colorlndex] = 0;
b[colorlndex] = 0;
return new IndexColorModel (icm.getPixelSizeO , mapsize,
r, g, b, icm.getTransparentPixel());
}
public int fi1terRGB(int x, int yT int rgb) {
return rgb;
RGBImageFilter
java.awt.image
filterRGBO
filterRGBO
Pl’RPC )SE SYNTAX Override to filter each pixel value. public abstract int fi1terRGB(int x, int y, int rgb)
Л DESCRIPTION The rgb parameter is a pixel value encoded in the default color model (see
в ColorModel .getRGBdefault ()). x and у are lhe coordinates of the pixel
c value in the image.
D E PARAMETERS Subclasses must specify a method to convert a single input pixel in the default RGB ColorModel to a single output pixel.
F rgb l he pixel value encoded in the default color model.
G X fhe т-coordinate of lhe pixel value's location in the image; -1 if the color table
If У is being filtered. The y-coordinate of the pixel value's location in the image; -1 if the color table
I is being filtered.
J SHF AI .SO ColorModel .getRGBdefault() , filterRGBPixelsQ.
К EXAMPI E See the class example.
w
X
Y
Z
filterRGBPixeLsO
purpose Override to filter a batch of pixel values.
symax public void fi 1 terRGBPi xel s(i nt x, int y, int w, int h, intf]
pixels, int offset, int scansize)
description The pixel values in pixels are encoded in the default color model (see Col-
orModel .getRGBdefaul t). AH pixels flowing through this filter pass through
this method. By default this method simply takes each pixel value in the pix-
el s array and calls the filterRGBO method. It then stores the result back
into rhe same location in the pixel s array.
This method can be overridden to avoid calling filterRGBO for each pixel,
thereby making for a more efficient implementation.
parameters
h fhe height of the rectangle in which the pixels are destined.
model The non-null color model used to translate the pixel values.
offset The index of the first pixel in the pixel array pixel s.
pixels The non-nul 1 array of pixel values encoded in the default color model,
scansize The width to use when extracting pixels from the pixel array pixels,
w The w idth of the rectangle in w'hich the pixels are destined.
x The л-coordinate of the rectangle in which the pixels are destined.
у The Y-coordinate of the rectangle in which the pixels are destined.
1316
RGBImageFilter
fiherRGBPixelsO
java.awt J mage
SEE ALSO ColorModel .getRGBdefaultO , filterRGBO.
example:
This example is identical to the class
example, except that lhe filterRGB-
PixelsO method, instead of the fi 1 -
terRGBO method, is overridden. Note
that the filterRGBO method is defined
even though it is not used; this is done to
make the class nonabstract. See Figure
326.
HGtRE 326: Gradient Filter II
Using RGBImageFi 1 ter.
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import java.util.*;
class Main extends Frame {
Main(String filename) {
super(“fiIterRGBPixels Example”);
try {
add(new ImageCanvas(getToo1kitО.getlmage(fi1 ename)),
BorderLayout.CENTER);
} catch (Exception e) {
e.printStackTraceO;
}
setSize(50, 100);
show();
static public void main(String [] args) {
if (args.length == 1) {
new Main(args[0]);
} else {
System.err.println(“usage: java Main <image file>");
}
}
}
class ImageCanvas extends Component {
Image gradientimage;
ImageCanvas(Image image) {
GradientFilter imgf = new GradientFi1ter();
ImageProducer ip = image.getSourceO;
ip = new FilteredImageSource(ipT imgf);
gradientimage = getToolkit().createlmage(ip);
repaintO;
}
public void paint(Graphics g) {
g.drawlmage(gradientimage, 0, 0, this);
}
}
class GradientFiIter extends RGBImageFilter {
float[] hsb = new float[3J;
int width, height;
RGBImageFilter
new model
java.awt.image
/X
В
C
D
E
Г
G
H
J
J
К
I.
M
N
О
P
Q
s
T
и
V
w
X
Y
z
public void setDimensions(int w, int h) {
super.setDimensionsO, h);
width = w;
height = h;
}
public void fi 1 terRGBPi xel s(int x, int y, int w, int h,
int pixels[], int offset, int scansize) {
int i = offset;
for (int cy 0; cy < h; cy+O {
for (int ex =0; ex < w; cx++) {
Color c = new Color(pixels[i]);
Color.RGBtoHSB(c.getRed(), c. getCreenO . c.getBlueO, hsb);
hsb[2] += <5f - (float)x / width;
hsbT2] += .5f - (float)y / height;
hsb[2] = Math.max(0.0f, Math.min(1.0f, hsb[2]));
pixelsfi] = Color.HSBtoRGB(hsb[0], hsb[l], hsb[2J);
i-+;
}
i scansize - w;
}
consumer.setPixels(x, y, w, h, ColorModel.getRGBdefault(),
pixels, offset, scansize);
}
// Never called.
public int fi 1 terRGB(i nt x, int y, int rgb) {
return 0;
}
}
newmodel
purpose This field holds the convened color model.
protected ColorModel newmodel
description If canFilterlndexColorModel is true and the color model of the source
image is an index color model, this field holds the converted color model.
sei. also origmodel.
origmodel
purpose This field holds the color model passed to the setColorModel О method.
syniax protected ColorModel origmodel
1318
RGBImageFilter
setColorModelf)
java.awt.image
description If canFiIterlndexColorModel is true and the color model of the source
image is an index color model, this field holds the original color model. If this
field is not null, then the setPixelsO method checks whether the color
model it gets is the same as о rigmodel. If the field is null, then newmodel is
substituted and the pixels are not modified.
see also newmodel.
setColorModel()
purpose Called by the image producer to deliver the color model of the source image.
syntax public void setColorModel(ColorModel model)
description This method is called by the image producer to deliver the color model of the
source image to the image filter. Therefore it must not be called directly.
Instead, it can be overridden if necessary to introduce behavior different from
the default implementation. The default implementation checks the canFil-
terlndexColorModel field to see if it should set a new color model by calling
filterlndexColorModel(). If canFiIterlndexColorModel is true and
model is an index color model, a new color model is created and enabled by
calling substituteColorModel(). Otherwise, the image filter passes the
default color model to the image consumer.
PARAMETERS
model The non-null color model of the source image.
override* ImageFilter.setColorModel().
sei-also canFiIterlndexColorModel , ColorModel.getRGBdefaultO »
filterIndexColorModel(), substi tuteColorModel().
example See ImageConsumer.setColorModel().
setPixels()
purpose Called by the image producer to deliver pixels to the image filter.
syntax public void setPixels(int x, int y, int w, int h, ColorModel
model, byte[] pixels, int offset, int scansize)
public void setPixels(int x, int y, int w, int h, ColorModel
model, int[] pixels, int offset, int scansize)
description This method is called by the image producer to deliver pixels to the image fil-
ter. Therefore it must not be called directly, instead, it can be overridden if nec-
essary to introduce behavior different from the default RGBImageFilter
RGBImageFilter
java.awt.image
substituteColorModelf)
implementation. The default implementation creates a temporary buffer, trans
lates the pixel values in pi xel s to the default color model, saves the pixels in
the temporary buffer, and then calls fi 1 terRGBPixels() with the temporary
buffer of pixel values.
A PARAMETERS
В h The height of the rectangle in which the pixels are destined.
f ’ model The non-nul 1 color model used to translate the pixel values.
k. offset I'he index of the first pixel in the pixel array pixels.
D pixels I'he non-null array of pixel values.
E scansi ze The width to use when extracting pixels from the pixel array pi xel s
F w The width of the rectangle in which the pixels are destined.
X The л-coordinate of the rectangle in which the pixels are destined.
G У The v-coordinate of the rectangle in w hich the pixels arc destined.
H OVERRIDES ImageFi1 ter.setPixe 1 s().
1 SEE ALSO ColorModel .getRGBdefault() , filterRGBPixelsQ ,
J К EXAMPLE ImageConsumer.setPi xels(). See ImageConsumer.setPixelsQ.
substituteColorModel()
pi rpose Replaces the color model of the source image.
syntax public void substituteColorModel(ColorModel oldcm, ColorModel
newcm)
description As pixels flow through this filter via the setPixelsQ method, a check is
made to see if the pixels have been encoded with the oldcm color model. If so,
the pixels are not converted. They are simply forwarded to the image con-
sumer with newcm as the color model.
PARAMETERS
newcm The non-nul 1 color model to replace ol dem on the fly.
oldcm I hc color model to be replaced by newcm. May be null.
seealso setPi xel sQ.
W
X
Y
Z
1320
Syntax
public class Scrollbar extends Component implements Adjustable
Description
The Scroll bar component is used to specify
a particular integer value in a range of values.
A scrollbar has an orientation that can be
either vertical or horizontal. The orientation is
specified as the scrollbar is created and can be
changed at any time. Figure 327 shows a hori-
zontal scrollbar with labels on all of its parts.
Scrollbar Example ГЛ 1Г7
I \ \ Г
I\ Scroll Box I
PageUp PageDown I
LineUp LineDown
FIGURE 327: Parts of a Horizontal Scrollbar.
The Adjustable Value and Its Range
The scrollbar has an adjustable value, which controls the location of the scrollbar’s scroll box.
A scrollbar also has an adjustable value range, which is defined by two integer values: the
minimum and the maximum. The range can be any integer value, positive or negative. How-
ever, the maximum value must be greater than or equal to the minimum value. The range can
be modified at any time.
rhe adjustable value must be within the adjustable range. The actual location of the scroll
box within the scrollbar matches the relative position of the adjustable value within the scroll-
bar range. The adjustable value can be changed at any time, and the scroll box will move
accordingly. When the user moves the scroll box. the adjustable value is automatically updated
and an adjustment event is fired.
Scrollbar
java.awt
Proportional Indicator (Visible Amount)
If the scrollbar is used to pan around a large image, it is useful to have an indication of what
fraction of the entire image is visible. The size of the scroll box in relation to the size of the
entire scrollbar is typically used to indicate lhe size of the visible area in proportion to lhe
A entire image. For example, if the scroll box is about half lhe size of the scrollbar then about
half of the image is visible, l he scrollbar's "visible amount’4 property controls the size of the
scroll box (note that not all platforms support variable-sized scroll boxes), h also controls the
U actual maximum of the scrollbar's value» which is the difference between the scrollbar’s inaxi-
D mum and its visible amount.
Note lhat the adjustable value can never exceed the scrollbar’s maximum minus the size of
F' the scroll box. For example, if you create a scrollbar with a range of 0 to 100 and a scrollbar
F visible amount of 10 (scroll box is size 10), lhe scrollbar's value can be at most 90. To allow
~ the scrollbar with a scroll box size of 10 to return a value of 100, you must create the scrollbar
with a range of 0 to 110. The following rule is always followed:
H
I minimum <= adjustable value <= maximum-visible
j Block and Unit Increments
The scrollbar unit and block increments control lhe amounts bv which the adjustable value is
К ’
changed when the Line Up, Line Dow n. Page Up. or Page Dow n key is pressed. If applying
L the increment modifies the adjustable value outside the scrollbar range, the adjustable value is
M set to either the maximum or minimum value. The scrollbar unit and block increments can he
changed at any time.
N
0 Events
A scrollbar fires adjustment events w'hen its scroll box is dragged, when the Line Up. Line
p Down, Page Up. or Page Down key is pressed, or when the ends of the scrollbar are clicked.
q I'he scrollbar generally does not fire an event if the adjustable value does not change: the
exception is when the scroll box is dragged. So if the scroll box is at the bottom of the scroll-
bar. pressing the Line Down or Page Down key does not fire an event.
See the AdjustmentEvent class for details on adjustment events. In addition lo the
adjustment event, a scrollbar fires all of the events fired by the Component class. See the Com-
ponent class for details. See the AWTEvent class for general information on events and how to
tiller or handle them.
V
W
X
Y
1322
java.awt
Scroll bar
MEMBER SUMMARY
Constructor I
Scrol IbarO Constructs a new Scrol Ibar instance.
Orientation Constant Fields and Methods
getOri entationO Retrieves this scrollbar's orientation. I
HORIZONTAL The orientation constant specifying a horizontal scrollbar.
setOri entationO Sets this scrollbar's orientation. ( i
VERTICAL The orientation constant specifying a vertical scrolIbar. [
Scrollbar Values Methods I
getMaximumO Retrieves this scrollbar's maximum value. }
getMi nimumO Retrieves this scrollbar s minimum value.
getValue() Retrieves this scrollbar's adjustable value. (
getVi si bl eAmount() Retrieves this scrollbar's visible value. ।
setMaximumO Sets this scrollbar’s maximum value. 1
setMinimumO Sets this scrollbar’s minimum value.
setValue() Sets this scrollbar's adjustable value.
setVal uesO Sets various scrollbar values. ’
setVi si bl eAmount О Sets this scrollbar's \ isible \ al tie. 1
Unit and Block Increment Methods
getBlocklnerement() Retrieves this scroll bar’s block increment value.
getUnitIncrement() Retrieves this scrollbar's unit increment value.
setBlocklncrementO Sets this scrollbar’s block increment. I 1
setUni tlncrementO Sets the scroll bar's unit increment. 1
Event Methods
addAdjustmentLi stenerQ Adds a listener to receive this scroll bar’s adjustment
events. । 1
processEventO Processes an event enabled for this scrolIbar. 1
processAdjustmentEvent() Processes an adjustment event enabled for this scrollbar.
removeAdjustmentLi stenerO Removes a listener from receiving this scrollbar's adjust-
ment events.
Peer Method 1 1
addNotifyO Create the scroll bar’s peer.
Debugging Method
paramStri ng 0 Generates a string representing the scroll bar's state.
। Deprecated Method
getLi neIncrement() Replaced by getllni tlncrementO-
getPagelncrementO Replaced by getBl ocklnc rement О.
getVi si bleO Replaced by getVisi bl eAmount О.
setLi neTncrementO Replaced by setUni tlncrementO. 1
setPagelncrementO Replaced by setBl ocklncrement(). J
Scrollbar
ja\ a.awt
See Also
Adj ustable, java.awt.event.AdjustmentEvent,
java.awt.event.AdjustmentLi stener, Scroll Pane.
Example
This example creates a canvas that
paints a very large grid and two
scrollbars to pan around the grid. See
Figure 328. The maximum values of
the scrollbars are set to the pixel size
of the grid so that the value of the
scrollbar can be used to determine
the location of the visible area. For
simplicity, the paint() method
always paints the entire grid such
that the top-left corner is at (0. 0).
Also, the Graphi cs . transl ate()
method is used to adjust the graphics
context's origin so that the correct
part of the grid will be visible. A
more efficient implementation would
paint only the visible portion of the
grid.
Note: The Scroll Pane compo-
RRIE
Scrollbat Example
FIGURE 328: Scrollbar.
nent should be used for viewing large components. This example is for demonstration pur-
poses only.
See also the Color class example for a use of Scrol Ibar.
import java.awt.*;
import java.awt.event;
class Main extends Frame implements AdjustmentListener {
Scrollbar sbVer = new Scrol1bar(Scrol1 bar.VERTICAL);
Scrollbar sbHor = new Scrol1 bar(Scrol1 bar.HORIZONTAL);
MainCanvas cv = new MainCanvas(sbVer, sbHor);
Main() {
super (“Sc rol 1 bar Example’’);
add(cv, BorderLayout.CENTER);
add(sbVer, BorderLayout.EAST);
add(sbHor, BorderLayout.SOUTH);
// Add adjustment listener for scrollbars
sbVer.addAdjustmentLi stener(thi s);
sbHor.addAdjustmentLi stener(thi s);
setSize(200, 200);
show() ;
1324
java.awt
_ ScroHbar
}
public void adjustmentValueChanged(AdjustmentEvent evt) {
Scrollbar sb = (Scrollbar)evt.getSourceO;
System.out. println(((sb.getOrientation() Scrol 1 bar.VERHCAi ) ?
"ver” : “hor”)
+ “ li^" + sb. getUnitlncrement()
+ “ pi=" + sb.getBlocklncrementO
+ “ max=” + sb.getMaximumQ
+ “ vis=” + sb.getVisi bl eAmount О);
cv.sbChangedO ;
}
static public void mai n(St ring [] args) {
new Mai n();
}
}
// Creates a very large square grid.
// Fach grid cell is labelled to help with navigation.
class MainCanvas extends Component {
int gridSize = 1500;
int gridCells - 10;
int cellsize - gridSize/gridCells;
int originX, originY;
Scrollbar sbVer;
Sc roll bar sbHor;
MainCanvas(ScrolIbar sbVer, Scrollbar sbHor) {
this.sbVer - sbVer;
this.sbHor - sbHor;
setFont(new FontC'Courier”, Font.BOLD, 36)):
}
public void sbChanged() {
originY = -sbVer.getValueO;
originX = -sbHor.getValueO;
repai nt();
}
// If the size of the component changes, we need to update
// the scrollbar values.
public void doLayoutO {
super .doLayoutO ;
int w = getSizeO .width;
int h -x getSizeO .height;
sbVer. setValues(sbVer. getValueO , h, sbVer.getMinimum(), gridSize);
sbVer.setBlockIncrement(Math.min(cel 1 Size, h));
sbVer.setUni tlncrement(Math.mi n(cel1 Size, h/5));
sbHor.setValues(sbHor.getValueO, w, sbHor .getMinimumO , gridSize);
sbHor.setBlockincrement(Math.mi n(ce11 Size, w));
sbHor.setUnitlncrement(Math.min(cellSize, w/5));
// This ensures that if the grid is larger than the viewable
// area, you will never see space around the grid.
originX -Math.max(0, Math.min(gridSize-w, sbHor.getValue()));
originY - -Math.max(0, Math.min(gridSize-h, sbVer.getValueO));
1
Scrollbar
addAdjustmentListener()
java.awt
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetric$O I
// Using translateO simplifies the painting code
// since it doesn’t have to worry about origin changes,
g.translate(originX, originY);
g.set Col or(Color.red);
for (int i^0; i<gridCells; i*+) {
int c = i * cellSize;
g.drawLine(c, 0, c, gridSize);
g.drawLine(0, c, gridSize, c);
}
g.drawRect(0, 0, gridSize-1, gridSize-1);
for (int i-0; i<gridCells; i++) {
for (int j=0; j<gridCells; j+4) {
String str = ““ + i + “, ’’ + j;
int x — i * cel 1 Size;
int у - j * cellSize;
g.drawString(str, x+(celISize-fm.stringwidth(str))/2,
y+(cel 1 Size-fm.getHeight ())/2-«-fm. getAscentO) ;
}
}
}
}
addAdjustmentListener()
РГ RPOSI: Adds a listener for receiving this scrollbar's adjustment events.
SYNTAX public synchronized void addAdjustmentLi stener(Adjustmentt istener 1i stener)
DESCRIPTION Adjustment events are fired when the scrollbar's value is changed. See AdjustmentEvent for more details. After this method is called, the adjust- ment listener listener will receive adjustment events fired bv this scrollbar. If 1 i stener is nul 1. this method does nothing.
PARAMETERS listener I'he possibly null adjustment listener to add.
SLL .ALSO java.awt.event.AdjustmentEvent, java.awt.event.AdjustmentListener, removeAdjustmentLi stener().
EXAMPI F See the class example.
1326
java.awt
Scrollbar
addNoti fy ()
addNotifyO
PURPOSE Creates this scrollbar’s peer.
SYNTAX public void addNotifyO
DESCRIPTION This method creates the peer if it does not exist. The peer is created by calling the Toolkit .createScrollbarQ method. This method should never be called directly. It is normally called by the parent.
OVERRIDES Component.addNoti fy().
SEE ALSO Component, Toolkit.
getBlockIncrement()
PURPOSE Retrieves this scrollbar's block increment value.
SYNTAX public int getBlocklncrementO
DESCRIPTION The scrollbar's block increment value controls the amount by which the adjustable value is changed when the Page Up or Page Down key is pressed. If applying the increment modifies the adjustable value outside the scrollbar range, the adjustable value is set to either the maximum or minimum value. The scrollbar’s block increment value can be changed at any time using set- B1ocklnc rement О.
RETURNS The scrollbar’s block increment value.
SEE ALSO getUni tlncrementO, setBlocklncrementO.
EXAMPLE See the class example.
getLineincrement() deprecated
PURPOSE Replaced by getUni tlncrementO-
SYNTAX public int getLinelncrementO
RETURNS The scrollbar's line increment value.
DEPRIVATION Replace the usage of this deprecated method, as in int increment = scrolIbar.getLinelncrementO; with int increment = scrol Ibar.getUni tlncrementO ;
Scrollbar
getMaximum()
java.awt
getMaximumf)
PVR POSE Retrieves this scrollbar's maximum value.
SYNTAX public int getMaximumQ
A DESCRIPTION I'he maximum value (along with rhe visible amount) determines how large the
В scrollbar's value can be. See the class description for more information about
C the scrollbar's maximum value.
D RETI RNS This scrollbar's maximum value.
E SEI; ALSO getMinimumf), getValueQ , getVisibleAmountO , setMaximumO-
F EXAMPI E Sec the class example.
G
H getMinimum()
[ Pl RPOSL Retrieves this scrollbar s minimum value.
J SYNTAX public int getMinimumO
К DESCRIP HON The minimum value determines how small the scroll bar's value can be. See the
I. class description for more information about lhe scrollbar's minimum value.
M RETIRNS This scrollbar's minimum value.
N SEE ALSO getMaximumO, getValueO » getVi si bl eAmount О , setMinimumO.
0 EXAMPLE See the class example.
P
Q getOrientation()
R Pt RPOSE Retrieves this scrollbar's orientation.
SYNTAX public int getOrientation О
T DESCRIPTION A scrollbar has an orientation that can be either vertical or horizontal. The ori-
U entation is specified as the scrollbar is created and can be changed using set-
V OrientationO,
w RE.Tl RNS The scrollbar's orientation. This value can be either VERTICAl or HORIZON-
X TAL.
SEEALSO setOrientation().
Y
EXAMPLE See the class example.
z
1328
Scrollbar
getPage Increment!)
java.awt
getPageIncrement()
DEPRECATED
PURPOSE- Replaced by getBlocklncrementQ.
SYNTAX public int getPagelncrementO
RETURNS The scrollbar's page increment value.
DEPRECATION Replace the usage of this deprecated method, as in int increment =- scrol1 bar.getPagelncrement0; with int increment = scrol Ibar.getBlocklncrementO ;
PURPOSE-. Retrieves this scrollbar's unit increment value.
SYNTAX public int getUnitlncrement()
DESCRIPTION The scrollbar's unit increment value controls the amount by which the adjust- able value is changed w'hen the Line Up or Line Down key is pressed. If apply- ing the increment modifies the adjustable value outside the scrollbar range, the adjustable value is set to either the maximum or minimum value. The scroll- bar's unit increment value can be changed at any time by using settlnitln- crementO-
RE-TURNS The scrollbar's unit increment value.
Slit; ALSO getBlocklncrementQ- setUni tlncrementQ.
EXAMPLE See the class example.
getValue()
PURPOSE Retrieves this scrollbar’s adjustable value.
SYNIAX public int getValueO
DESCRIPTION See the clasS description for more information about the scrollbar’s adjustable value.
RETURNS This scrollbar's adjustable value.
SI:E Al SO getMaximumO. getMinimumO , getVisibleAmountO , setValueO.
EXAMPLE See the class example.
Scrollbar
getVisibleC)
java.awt
get Visible()
DEPKECATED
Hl RPOSE Replaced by getVisi ЫeAmount 0♦
SYNTAX public int getVisibleO
RETURNS The scrollbar's visible value.
DEPRECATION Replace the usage of this deprecated method, as in int vis = scrol 1 bar.getVisibleO ; with int vis scroll bar .getVi si bl eAmount() ;
getVisibleAmount()
PURPOSE Retrieves the scroll bar's visible amount.
SYNTAX public int getVisibleO
DESCRIPTION The scrollbar's visible amount controls the size of the scroll box. It is typically used to indicate how much of the document is visible. For example, if only one-third of the document is visible, the scrollbar's visible amount should be set to (getMaximumO-getMi nimum())/3 so that the size of the scroll box will be one third the size of the whole scrollbar.
RETURNS The scrollbar's visible value.
see: also getMaximumO, getMinimumQ, getValueQ, setVisi bl eAmountQ.
EXAMPLE See the class example.
HORIZONTAL
PURPOSE The orientation constant specifying a horizontal scrollbar.
SYNTAX public static final int HORIZONTAL
EXAMPLE See the class example.
paramStringl)
pi rposi: Generates a string representing the scrollbar s state.
symax protected String paramStringO
1330
java.awt Scrollbar
process Adjust men t Even t()
DESCRIPTION A subclass of this class should override this method and return a concatenation of its state with the results of super. paramStri ng(). This method is called by the toStringO method and is typically used for debugging.
RETURNS A non-nul 1 string representing the scrollbar's state.
OVERRIDES Component.paramStri ng().
SEE ALSO java.1ang.Object.toStri ng().
EXAMPLE See Component. paramStri ngO.
proces$AdjustmentEvent()
PURPOSE Processes an adjustment event enabled for this scrollbar.
SYNTAX protected void processAdjustmentEventfAdjustmentEvent evt)
DESCRIPTION Adjustment events are fired when this scrollbar's value changes. See the class description and AdjustmentEvent for more details. This method processes adjustment events for this scrollbar by calling any registered AdjustmentLi s- tener. This method is invoked only if adjustment events have been enabled for this scrollbar. This can happen either when an adjustment listener is added to this scrollbar or when Component.enableEvents() is called to enable adjustment events. Typically, a scrollbar controls how its adjustment events are processed by add- ing or removing adjustment listeners. It overrides processAdjustment- EventО only if it needs to do processing in addition to that performed by the registered listeners. When a subclass does override processAdjustmentEventQ. it should call super.processAdjustmentEventQ to perform the processing intended by its base class (such as dispatching the listeners).
PARAMETERS evt The non-nul 1 adjustment event.
SEEALSO addAdjustmentListenerО» Component,enableEventsO, Component.disablefventsO, java.awt.event.AdjustmentEvent, java.awt.event.Adjustment!istener, processEventO, removeAdjustmentLi stenerQ-
EXAMPLE See AWTEventMulti caster. ad justmentValueChangedQ.
Scrollbar
java.awt
processEvenU)
processEvent()
A PVRPOSI- SYNTAX DEPRECATION Processes an event enabled tor this scroll bar. protected void processEvent(AWIEvent evt) This method extends Component.processEventO by adding support for
В AdjustmentEvent. This method can be overridden to handle new types of
c events for this scrollbar. When a subclass does override processEventO. it
D should call super.processEventО to perform the processing intended by its base class (such as dispatching the listeners for different event types).
E PARAMETERS
F evt The non-null event to be processed.
G OVERRIDES Component.processEventO.
II SEE ALSO AWTEvent, processAdjustmentEventO-
1 E-X AMPLE: See lhe Component class example.
J К removcAdjustmentListener()
1, PURPOSE: Removes a listener from receiving this scrollbar's adjustment events.
M SYNTAX public synchronized void removeFocuslistener(Adjustmentlistener
N 1i stener)
0 DESCRIPTION Adjustment events are fired when this scrollbar's value is changed. See
p AdjustmentEvent for more details. After this method is called, the adjust-
Q ment listener listener will no longer receive adjustment events from this scrollbar. If listener is null, this method does nothing.
R PARAMETERS
listener The possibly null adjustment listener to remove.
T SE:E: ALSO addAdjustmentListenerO, java.awt.event.AdjustmentEvent,
и EXAMPLE java.awt.event. Adjustment!.! stener. See removeActionListenerO in Menuitem.disableEventsO.
V w X Scrollbar()
Y PURPOSE: Constructs a new Scrol 1 bar instance.
z SYNE'AX public Scrollbar()
public Scrollbar(int orientation)
1332
java.awt
Scrollbar
Scrol lbar()
public ScrolIbar(int orientation, int value, int visible, int
minimum, int maximum)
description This constructor creates a new ScrolIbar instance that has the orientation
orientation and initial values and range. If orientation is not specified, it
defaults to VERTICAL. If value and mi nimum are not specified, they default to
0. If visible is not specified, it defaults to 10. If maximum is not specified, it
defaults to 100. The line increment defaults to 1, and the page increment
defaults to 10. The supplied values are adjusted if necessary to satisfy the fol-
lowing constraint:
minimum <= value <= maximum
The constraint is achieved with the following rules. If maximum < minimum,
maximum is set to minimum. If value > maximum, val ue is set to maximum; if
value < minimum, value is set to minimum. If the visible amount is larger
than lhe range between maximum and minimum, the visible amount is set to
this range and the scroll box is made as large as the scrollbar, thereby prevent-
ing the scrollbar from generating any events.
PARAMETERS
maximum The scrollbar's maximum value.
minimum The scroll bar’s minimum value.
orientation The scrollbar's orientation. Must be one of HORIZONTAL or VERTICAL.
value The scrollbar’s initial value.
vi si bl e The scrollbar’s visible amount.
EXCEPTIONS
IllegalArgumentException
If orientation is not valid.
example. This example creates a horizontal
scrollbar and prints out all events fired
by the scrollbar. See Figure 329.
FIGURE 329: Scroll bar О
import java.awt.*:
import java.awt.event;
public class Main extends Frame implements AdjustmentListener {
MainQ {
super(“Scrol1 bar Example”);
ScrolIbar sb = new Scrol1 bar(ScrolIbar.HORIZONTAL, 0, 50, 0, 100);
sb.addAdjustmentLi stener(this);
add(sb, BorderLayout-SOUTH);
packO;
show();
Scrollbar Example |~Г~1
public void adjustmentValueChanged(AdjustmentEvent evt) {
Scrollbar
java.awt
setBlockIncrement()
System.out.println(evt);
}
static public void main(String[] args) {
new MainО;
}
A }
В
C
D
E
F
G
H
1
J
К
L
M
setBlockIncrement()
purpose Sets this scrollbar’s block increment.
syntax public synchronized void setBlockTncrement(int increment)
description This method sets the scrollbar's block increment value to be increment. The
scrollbar's block increment value controls the amount by which the adjustable
value is changed when the Page Up or Page Down key is pressed. If applying
the increment modifies the adjustable value outside the scrollbar range, the
adjustable value is set to either the maximum or minimum value.
parameters
increment The non-negative block increment.
seealso g et Bl ocklnc rement О T setUnitinerement().
example See the class example.
setLineIncrement()
DEPRECATED
и
V
w
X
Y
Z
purpose Replaced by setUnitinerementО.
syntax public void settinelncrement(int increment)
PARAMETERS
increment The non-negative line increment.
deprecation Replace the usage of this deprecated method, as in
scroll bar.setLinelncrement(increment);
with
scroll bar.setUnitinerement(increment);
set Maxi mum()
purpose Sets this scrollbar's maximum value.
syntax public synchronized void setMaximum(int max)
1334
j;iv ;i ;iut
Scrollbar
seiMinimumi )
ni s('Rir i io\ This method sets the maximum value possible for this scrollbar to be max. The
scrollbar's adjustable value max be adjusted if its current value is greater than
max. The scrollbar's maximum may be adjusted (to be 1 greater than the mini-
mum) if it is less than the scrollbar's minimum value.
PAR.W1l-.il RS
max The scrollbar's new maximum value.
SEE Al SO getMi ni mum(), setMaxi mumValue(), setVi si bl eAmount(), setValueQ.
EX AM PI.1 See setMi nimum().
setMinimum()
Pi RPOsi. Sets this scrollbar's minimum value.
SYviax public synchronized void setMinimum(int min)
di-.s( ripiiox This method sets lhe minimum value possible for this scrollbar to be min. The
scrollbar's value may be adjusted if its current value is less than min. The
scrollbar's maximum may be adjusted Ho be 1 greater than mini if it is less
than mi n.
parameiers
min The scrollbar's new minimum value.
sei. Ai so getMi ni mum О , set Maxi mumVal ue () , setVi si bl eAmount () ,
setValue().
exampi i. This example creates a set of buttons for controlling the \ isibility amount, ori-
entation. maximum, and minimum of a scrollbar. See Figure 330.
I ’ Scrollbar.set... BI3E|
Xl i
Ma.::- 1 1 0 Max-5 d Max+5
Min -5 | Min-5 | Min +5
VIS— JU Vis -5 Vis+5
vh rti c a! Vertical Horizonta .
< Scrollbar.set... В№9ЕЗ
FIGI RE 330: Changing a Scroll bar's properties.
Scrollbar
java.awt
setMinimum()
import java.awt.* \
import java.awt.event;
class Main extends Frame implements ActionListener, AdjustmentListener {
Scrollbar scroll bar = new Scrol1 bar(Scrol1 bar.VERTICAL, 0, 10, 10, 100):
Label max, min, vis, posn;
Main О {
super(“Scrol 1 bar.setMi nimum”) ;
Panel p - new Panel(new GridLayout(4, 0));
max - new Label (“Max-” + scrol 1 bar .getMaximumO) :
p.add(max);
Button b - new Button("Max -S");
p.add(b);
b.addActi onLi stener(thi s);
b -= new Button(“Max +5”);
p.add(b);
b.addActionL istener(this);
min = new Label(“Min=” + scrol 1 bar.getMinimumO) ;
p.add(mi n);
b = new Button(“Min -5”);
p.add(b);
b.addActionL istener(this);
b r- new Button(“Min +5’’);
p.add(b);
b.addActionL!stener(thi s);
vis - new Label(“Vis-” + scrol 1 bar.getVi sibleAmountO) ;
p.add(vis);
b = new Button(“Vis -5”);
p.add(b);
b.addActionL istener(this);
b = new Button(“Vis *5”);
p.add(b);
b.addActionLi stener(this);
posn - new Label(“vertical”);
p.add(posn);
b - new Button(“Vertical”);
p.add(b);
b.addActionL!stener(this) ;
b = new ButtonC'Horizontal”);
p.add(b);
b.addActionL!stener(thi s);
add(p, BorderLayout.SOUTH);
add(scrollbar, Borderl ayout.EAST);
scroll bar.addAdjustment! i stener(this);
pack();
show();
}
public void actionPerformed(ActionEvent evt) {
String cmd = evt .getActionCommandO ;
if (cmd.equals("Max -5”)) {
1336
java.awt
Scroll bar
setOrientation()
scrolIbar.setMaximum(scrol 1 bar. getMaximumO-5) ;
max.setText(“Max-" + scrol 1 bar .getMaximumO) ;
} else if (cmd.equals("Max +5”)) {
scrolIbar.setMaximum(scrolIbar.getMaximumO+5);
max . setText("Max='’ + scrol Ibar .getMaximumO) ;
} else if (cmd.equals(“Min -5")) {
scrol1 bar.setMinimum(scrol Ibar .getMinimumO - 5) ;
min.setText(“Min=" + scrolIbar.getMinimumO);
} else if (cmd.equals(“Min t5")) {
scrolIbar.setMi nimum(scroll bar.getMi nimum()+5);
min.setText(“Min-” + scroll bar .getMi nimumO) ;
} else if (cmd.equals(“Vis -5’’)) {
scrollbar.setVi si bl eAmount(scrolIbar.getVisi bl eAmount()-5);
vis.setText(“vis=" + scrol 1 bar .getVi sibleAmountO) ;
} else if (cmd.equals("Vis +5")) {
scrol 1 bar. setVi si bl eAmount (scrol 1 bar. getVi si bl eAmount 0+5) ;
vis.setText("vis='’ + scrolIbar.getVisibleAmountO) ;
} else if (cmd.equals(“Horizontal”)) {
if (scrollbar.getOrientation() != ScrolIbar.HORIZONTAL) {
scroll bar.setOrientation(Scro1Ibar.HORIZONTAL);
posn. setText(“horizontal ’’) ;
remove(scrolIbar);
add(scrolIbar, BorderLayout.NORTH);
validate();
}
} else if (cmd.equals(“Vertical")) {
if (scrol 1 bar.getOrientationO Scrol Ibar.VERTICAL) {
scrolIbar.setOri entation(ScrolIbar.VERTICAL);
posn. setText(“verticaT') ;
remove(scrollbar);
add(scrollbar, BorderLayout.EAST);
val idateO;
}
}
1
public void adjustmentValueChanged(AdjustmentEvent evt) {
System.out.println(“value = “ + scrollbar.getValueO +
“ visible ~ scrolIbar.getVisibleAmountO +
“ min = " + scrol Ibar.getMinimumO +
“ max = “ + scrol Ibar .getMaximumO) ;
}
public static void mai n(St ri ng[l args) {
new MainO I
}
}
DESCRIPTION
setOrientationf)
pcrposi; Sets this scrollbar’s orientation.
syntax public synchronized void setOrientation(int orientation)
A scrollbar has an orientation that can be either vertical or horizontal. This
method sets this scrollbar’s orientation to be orientation. If the scrollbar
Scrollbar java.awt set Page Increme nt() already has (his orientation, this method docs nothing. Otherwise, the scroll- bar's peer is re created with the new orientation. PARAMETERS
л orientation The scrollbar's orientation, which can be either VERTICAL or HORIZONTAL.
В LXCLPIIOVS Il 1 egal ArgumentFxcepti on
С If orientation is neither VERTICAL nor HORIZONTAL.
D Е see also getOri entation(). example See setMi ni mum 0-
F G setPagelncrementf) depkec.ited
Н pi rpose Replaced by setBlocklncrement().
I syntax public void setPagelncrementfint increment)
J PARAMETERS
К increment The non negative page increment.
L dlprlcaiion Replace the usage of this deprecated method, as in scrolIbar.setPageIncrement(i ncrement);
М with
N scrolIbar.setBlockinc rement(increment);
и р setL'nitIncrement()
Q R purpose Seis the scrollbar's line increment. syntax public synchronized void setUnitlncrement(int increment) description This method sets the scroll bar's unit increment value to increment. The
т scrollbar's unit increment value controls the amount by which the adjustable
и value is changed when the Line Up or Line Down key is pressed. If applying
V the increment modifies the adjustable value outside the scrollbar range, the adjustable value is set to either the maximum or minimum value.
W PARAMFTI RS
X increment The non-negative unit increment.
Y see. also getUni tlncrement C) » setBl ocklncrement ().
Z ex am pi i See the class example.
1338
java.awt
Scroll bai
sctValue(
setValue()
- — — — — —
PURPOSE Seis this scrollbar's value.
syntax public synchronized void setValue(int value)
DESCRIPTION This method updates the position of the scrollbar's scroll box to be value, value is adjusted if necessary1 to be greater than or equal to the scrollbar's minimum value and less than or equal to the scrollbar's maximum value. Call- ing setValueО does not fire an AdjustmentEvent.
PARAMETERS val ue The scrollbar's new value.
SEE A ESQ getValueQ.
EXAMPLE See the Color class example.
set Vainest)
— — —-
PURPOSE Sets various scrollbar values.
SYNTAX public synchronized void setValues(int value, int visible, int minimum, int maximum)
DESCRIPTION The supplied values are adjusted if necessary to satisfy the following con- straint: minimum <= value <= maximum-visible. rhe constraint is achieved with the following rules. If maximum < minimum, maximum is set to minimum. If value > maximum-visible, value is set to maximum-visible: if value < minimum, value is set to minimum. If the vis- ible amount is larger than the range between the maximum and the minimum, it is set to the range and the scroll box is made as large as the scrollbar. thereby preventing the scrollbar from generating any events.
PARAMEI ERS maximum minimum value visible The scrollbar's maximum value. The scrollbar's minimum value. The scrollbar's value. The sc roll bar’s visible area.
SEE Al SO setMaximumO , set^inimumQ, setValueQ, setVi si bl eAmount ().
EXAMPLE See the class example.
Sc rol] bar
java.awt
setVisihleAmounU)
setVisibleAmount()
PLRPOSL Sets this scrollbar's visible amount.
SYNTAX public synchronized void setVisi ble(int vis)
DESCRIPTION See the class description tor details on a scrollbar's visible amount. This method sets this scrollbar's visible amount to the maximum of 1 and vi s.
PARAMETERS vi s The scrollbar's new visible amount.
SEE ALSO getMaximumO » getMinimumО, getValue(), getVi sib1 eAmount О
example: See setOrientationf).
VERTICAL
PURPOSE The orientation constant specifying a vertical scrollbar.
syntax public static final int VERTICAL
EXAMPLE See the class example.
1340
java. awl. ре с г
ScrollbarPeer
Syntax
public interface ScrollbarPeer extends Componentpeer
Description
The scrollbar (see Scrol Ibar class) in the AWT uses the platform's native implementation of
a scrollbar. So that (he AWT scrollbar behaves the same on all platforms, the scrollbar is
assigned a peer, whose task is to translate the behavior of the platform's native scrollbar to lhe
behavior of the AWT scrollbar
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
j ava. awt counterparts.
See Component and Toolkit for additional information about component peers.
.
Peer Methods
setLi nelncrement() Sets the scrollbar’s unit increment.
setPagelncrementO Sets the scroll bar’s block increment.
setValuesO Sets various scrolIbar values.
Scroll bar Pee г
java.awt.peer
seiLinelncremenl()
See Also
java.awt.Component, java.awt.Scrol1 bar, java.awt.Toolkit.
setLineIncrement()
Pt’RPOSE Sets the scrollbar's unit increment.
SVM-W void setLinelncrement(int increment)
PARAMETERS
increment I’he non-negative unit increment.
SEE ALSO java.awt.Scrol1 bar.setUni tinerement().
setPageIncrement()
PVR POSE Sets the scrollbar's block increment.
SYNTAX void setPagelncrement(int increment)
PARAMETERS
i ncrement The non-negative block increment.
SI 1 Al so j ava.awt.Scrol1 bar.setBlocklnc rement().
setValues()
PERPOSE Sets various scrollbar values.
SA VI AX void setValues(int value, int visible, int minimum, int maximum)
PARAMETERS maximum minimum value vi sible I'he scrollbar's maximum value. The scrollbar's minimum value. The scrollbar's value. The scrollbar's visible size.
SEE Al,SO java.awt.Scro11 bar.setVa1ues().
1342
java.awt
Scroll Pane
Syntax
public class Scroll Pane extends Container
Description
A scroll pane is a con-
tainer that contains a
single child compo-
nent and displays it
through the viewport
(see Figure 331). The
dimensions of the
viewport can be
smaller than the child
component. In this
case, not all of the
child component is
visible. The scroll
pane contains a hori-
zontal scrollbar and a
vertical scrolIbar
horizontal scrolIbar
FIGURE 331: Parts of a Scrol 1 Pane.
vertical scrollbar that
the user can use to
view different parts
of the child component.
The main purpose of the scroll pane is to simplify the work needed to implement a scrolla-
ble component. Using a scroll pane, you need only insert the component into lhe scroll pane;
much of the work involved in scrolling the component is handled by the scroll pane. However,
the child component may need a couple of small changes in order to behave properly. These
changes are discussed in the following sections.
ScrollPane
java.awt
Viewport
You can view different parts of the child component by moving the scroll pane's viewport. The
viewport can be moved in one of three ways: by setting values on the scrollbars (through the
Adjustable interface), by calling setScrol iPosition(), or by the user's interacting with
the scrol I bars.
The dimensions of the viewport, which can be retrieved by calling getVi ewportSizeO,
do not include the scroll pane's scrollbars or other borders. The viewport bounds are exactly
the scroll pane bounds, reduced by the scroll pane’s insets (see Container.getlnsetsO).
Preparing the Child Component
To behave properly in a scroll pane, a child component must do two things. First, it must
implement getPreferredSizeO and return the dimensions needed to fully display itself. For
example, if the child displays a IOO-x-IOO image, it should return new Dimension(100,
100). This information is used by the scroll pane to control the scrollbars.
Second, the child must handle the case in which its bounds are larger than its preferred
size. To do its work, the scroll pane modifies the child’s bounds as (he viewport bounds
change. The child's bounds are never made smaller than its preferred size, but if the viewport
is larger than the child's preferred size, the scroll pane stretches the child’s bounds to Till lhe
viewport. The child must therefore paint its contents somewhere in this larger space and then
fill the extra space with something. For example, if the child is showing an image, it could
paint the image in the center of the space and till lhe extra space with a gray color.
Scroll Position
The viewport has a properly called the scroll
position, which is a position relative to lhe
child. For example, if the scroll position is (0,
0), lhe northwest comer of the child will be
visible. On the other hand, if the scroll posi-
tion is (1, 1), the left-most column and top-
most row of pixels will be hidden. The scroll
position values are bounded. In particular, the
л-coordinate is
x = Math.max(0,
chi Id. getPreferredSizeO . width-
getVi ewportSi ze() . width) ;
у = Math.max(0,
chi Id.getPreferredSizeO . height-
getViewportSizeO height) ;
FIGURE 332: Scroll Position.
This means that if the child is fully visible, the scroll position will not change from (0, 0).
When the viewport is smaller than the child’s preferred size, the scroll pane implements
the ability to see different parts of the child by modify the child's location. (See Compo-
nent. getLocati on ().) In particular, the location of the child is exactly
chiIdLocation = (0-scrol 1 PositionX, 0-scroH Posi tionY).
1344
java.awt
Scroll Pane
The Scrollbars
The scroll pane has a horizontal and vertical scrollbar whose values make up the scroll posi-
tion. In particular, lhe scroll position s v-coordinate is lhe identical to the horizontal scrollbar's
adjustment value. Likewise for the scroll position’s y-coordinate. The scroll pane’s scroll posi-
tion can be updated by modifying (he scrollbar’s adjustment values.
The scroll pane scrollbars fire adjustment events (see AdjustmentEvent) whenever the
scroll position changes. Unlike all other components, which fire events only when the user
interacts with them, the scroll pane scrollbars fire events if the program changes the scroll
position. However, the adjustment type is always AdjustmentEvent-TRACK no matter how
the scrollbars are used. See AdjustmentEvent for more information on adjustment events.
Since the scroll pane itself does not generate any events, if you want to know when the
scroll position changes, you need to listen for adjustment events on both scrollbars. The scroll-
bars always exist and can fire events even if they are not visible.
Scrollbar Display Policies
There are three ways in which lhe scrollbars can be made to appear in the scroll pane. These
three scrollbar display policies must be specified at the time (he scroll pane is created and can-
not be changed later. See Table 23.
SCROLLBARS.ALWAYS
SCROLLBARS_AS__NEEDED
SCROLLBARS-NEVER
ITic scroll bars are always displayed.
The scrollbars appear only when needed.
The scrollbars are never displayed.
TABLE 23: Scrol 1 Pane Display Policies.
Member summary
Constructor Scrol iPaneO Constructs a new Scroll Pane instance.
Component Method addlmplО Adds a component to this scroll pane.
Viewport Methods J getScrol 1 PositionO : getViewportSizeO setScrol1Posi ti onО Retrieves the viewport’s scroll position. Retrieves lhe dimensions of this scroll pane’s viewport. Moves the viewport’s scroll position.
Continued
ScrollPane
java.awt
MEMBER SUMMARY
A В C D E F Ci II 1 J К 1. M N () P Q R T Scroll bar Methods getHAdjustableO Retrieves this scroll pane's horizontal scrollbar. ' getHScrol 1 barHeightQ Retrieves the height of this scroll pane's horizontal scroll bar. | getVAdjustabl eО Retrieves this scroll pane's vertical scrollbar. j getVScrol IbarWidthQ Retrieves the width of this scroll pane's vertical scroll- bar. Scrollbar Display Policy Method and Constants getScrollbarDisplayPolicyО Retrieves this scroll pane's scrollbar display policy. SCROLLBARS_ALWAYS The scroll bar display policy specifying that scrollbars are always displayed. SCROLLBARS. AS.NFEDED The scrollbar display policy specifying that scrollbars are displayed as needed. SCROLLBARS-NFVFR I'he scrollbar display policy specifying that scrollbars are never displayed. Layout Methods doLayourQ Invokes this scroll pane’s layout manager. 1 setl ayout О This method does nothing. ' Print Method pri ntComponentsO Prints this scroll pane and its child. Peer Method addNoti fy() Creates this scroll pane’s peer. , Debugging Method paramStri ngQ Generates a string representation of this scroll pane's state. Deprecated layoutO Replaced b> doLayoutO.
I’
V
w See Also
Y Adjustable, java.awt.event.AdjustableEvent, Scrol1 bar.
Example
A scroll pane provides scrollbars for the user to view different parts of the child component.
This example demonstrates how you can implement another way to move the scroll pane’s i
viewport: by “grabbing." The grabbing gesture is made by clicking the child component and
i
1346
java.awt
ScrollPane
dragging. For example, when you drag left, the child component moves left (which means that
the viewport moves right). See Figure 333.
I'he program retrieves the scroll
pane's scrollbars and increases their
unit increment to 2.
Notice that in the image compo-
nent mouseDraggedO method, the
scroll pane is retrieved by calling
getParentQ twice. This is because
when a lightweight component is
added to a scroll pane, the component
is not added to the scroll pane. What
actually happens is that a new panel is
created and the component is added to
the panel. The panel is then added to
the scroll pane. It might be more pru-
dent to pass the scroll pane reference F1GI’RE333: ScrollPane.
to the child to avoid any problems if
this changes in the future.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame {
Main(String filename) {
super("Scroll Pane Example1’);
Image image;
ScrollPane sp - new Scrol1Pane();
// Increase the scrolIbar unit increments to 2.
sp.getHAdjustable().setUnitlncrement(2);
sp.getVAdjustable() . setUnitlncrement (2) ;
// Add the canvas to the scroll pane.
sp.add(new ImageComponent(get toolkit О.getlmage(fi lename)));
// Add the scrollpane to the frame and show.
add(sp, BorderLayout.CENTER);
setSize(200, 150);
show();
}
public static void main(String args[]) {
if (args.length 1= 1) {
System.err.println("Usage: java Main <image-file>");
System.exi t(l);
}
new Main(args[0]);
}
}
class ImageComponent extends Component {
Scroll Pane
java.awt
Image image;
Imagecomponent(Image image) {
this.image -= image;
setBackground(Color.1ightGray);
A // Set the cursor to be a hand cursor.
setCursor(Cursor.getPredefinedCursor(Cursor.HAND CURSOR));
В
// Use the media tracker to retrieve the dimensions
C // of the image since we need them immediately,
try {
D MediaTracker tracker - new Medialracker(this) ;
E tracker-addlmage(image, 0);
tracker,waitForAl 1(0);
F } catch Exception e) {
e. printStackTraceO;
G }
H // Listen for mouse events.
addMouseListener(new MouseEventHandlerO);
I addMouseMotionListener(new MouseMotionFventHandlerO);
}
J
public Dimension getPreferredSizeO {
К return new Di mens ion(image.getWidth(nul 1)f image.getHeight(nul1));
}
L
public void paint(Graphics g) {
M int iw = image.getWidth(this);
int ih = image.getHeight(this);
N
// Only if the dimensions are available do we draw the image.
О if (iw >= 0 && ih >= 0) {
g.setColor(getBackgroundO) ;
P g.clearRect(0T 0, size().width, size(),height);
Q // Draw the image centered,
g. drawl mage (image, (getSizeO wi dth- iw)/2 ,
R (getSi ze() - hei ght ih)/2, this);
}
}
T Point downPt;
class MouseEventHandler extends MouseAdapter {
U public void mousePressed(MouseEvent evt) {
// Record the location of the down click.
V downPt = evt.getPoint О;
}
W }
X class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent evt) {
Y ScrollPane sp = (Scrol IPane) (getParent() .getParentO);
Point pt - sp.getScrol 1 PositionO ;
Z Dimension sz = sp.getViewportSize();
// Calculate new position of viewport.
pt.translate(downPt.x-evt.getX() , downPt«у-evt.getYQ);
1348
java.awt
ScrollPane
addlmplt
// Ensure that the new position is in the valid range. pt.x = Math.max(0. Math.min(getSizeO-width-sz.width, pt.x)); pt.у = Math.max(0, Math.min(getSizeO-height sz.height, pt.y)); // Update the position of the viewport.
} } } sp.setScrol1Posi tion(pt);
addlmpK)
-
PURPOSE Adds a component to this scroll pane.
SYNTAX protected final void addlmpI(Component comp, Object constraints, int pos)
DESCRIPTION This method is called whenever Container.addO is called; it adds a child component to the scroll pane. I he scroll pane can contain only one child com- ponent at a time. If the scroll pane already contains a component, that compo- nent is removed before comp is added. If comp is a lightweight component, a new panel (see Panel) is created and comp is added to the panel. The panel is then added to the scroll pane. This is important to note if comp wants io use getParentQ to retrieve a handle to the scroll pane. In this case, a lightweight component must call getParentQ twice.
PARAMETERS comp constraints pos fhe non-nul 1 component to be added io the scroll pane. This parameter is ignored. The value of this parameter is irrelevant, except that it must be <= 0.
EXCEPTIONS
IllegalArgumentLxeeption
If pos is > 0.
OVERRIDES Contai ner.addlmpl().
SEE ALSO Container.addO.
EXAMPLE See the class example.
addNotifyO
— —.
PURPOSE Creates this scroll pane's peer.
SYNTAX public void addNotifyO
java.awt
ScrollPane
doLayoutO
DESCRIPTION This method creates the peer if it does not exist. The peer is created by a call lo Toolkit.createScrollpaneО. The addNotifyO method should never he called directly. It is normally called by the scroll pane's parent. Contai ner.addNoti fуО.
OVERRIDES
A EXAMPLE See Component.setVi sible().
В C
D doLayoutO
[• Pl’RPOSE Invokes this scroll pane's layout manager
F SYNTAX public void doLayoutO
DESCR1PTK )N Ensures that the child component is at its preferred size. This method also
H updates the viewport location (see the class description) and scrollbar values.
if necessary'.
1 This method is not normally called. It is called by the system whenever the
J size of the scroll pane changes. However, it can be overridden to detect
К changes in the viewport dimensions. The override must call super.doLay-
L outO.
\л OVERRIDES Contai ner .doLayoutO.
Л1 41 SEEALSO Component.validate().
N () EX/XMPLE See getViewportSi zeO.
P
o getHAdjustableO
R Pl'RPOSE Retrieves this scroll pane's horizontal scrolIbar.
Ц SYNTAX public Adjustable getHAdjustableO
T DESCRIPTION i; This method returns an adjustable object that represents this scroll pane's hori- zontal scrollbar. See the Adjustable interface for more information about how to manipulate the scrollbar. However, three Adjustable methods—set-
V Mi nimumO < setMaximumO. and setVi sibleAmountO—must not be called;
w if any is called, it throws an AWTError exception.
X REH RNS Л non-nul 1 adjustable object representing the horizontal scrollbar.
Y SEE ALSO getVAdjustableO.
1350
java.awt
Sc roil Pane
getHAdjustablc()
i f This example demonstrates how to
change the scroll posit ion of the view-
port by modifying the scroll pane's
scrollbars, t set Sc rol 1 Posi ti onO<
however, is a more convenient
method.) The program creates one hun-
dred buttons. Clicking a button causes
the viewport to shift such that the but-
ton is displayed in the top-left corner of
the viewport. See Figure 334.
< getH Adjustable Ex... ВВЕЗ
UUUUI 1 vJ’-T UUllUlt
2 Button 43 Button 44 But
2 Button 53 Button 54 But 1
2 Button 63 Button 64 But 1
2 Button 73 Button 74 But-vj
4 1 il.
FIGI RE 334: Changing the
Viewport's Scroll Position.
import java.awt.'';
import java.awt.event . *;
class Main extends Frame implements ActionListener {
ScrollPane sp = new ScrollPaneQ;
MainQ {
super(“getHAdjustable Example");
Panel p = new Panel(new GridLayout(10, 0));
// Create a hundred buttons and add them to the panel.
for (int i=0; i<100; i++) {
Button b = new Button(“Button “+i);
b.addActionLi stener(this);
p.add(b);
}
// Layout and show components.
sp.add(p);
add(sp, BorderLayout.CENTER);
setSize(200, 150);
show();
}
public void actionPerformed(ActionEvent evt) {
Rectangle r = ((Component)evt .getSourceO) .getBoundsO :
Adjustable hadj = sp.getHAdjustableO;
Adjustable vadj = sp.getVAdjustableQ ;
hadj.setValue(r.x):
vadj.setValuefr.y);
}
public static void main(String argsQ) {
new MainQ;
ScrollPanc java.awt
getHScro)lharHeight()
getHScrollbarHeight()
PURPOSE Retrieves the height of this scroll pane's horizontal scrollbar.
SYNTAX public int getHScrollbarHeightO
DESCRIPTION This method returns ihe height of this scroll pane s horizontal scrollbar. This number is typically used in size calculations that involve the scroll pane s viewport. The returned value is independent of whether the scrollbar is cur- rently being displayed. If the scroll pane's peer is not created, this method returns 0.
RE It RNS Fhe non-negative pixel height of the horizontal scrollbar.
SLL ALSO getVScrol1barWi dth().
EXAMPI I Sec getViewportSize().
getScrollbarDisplayPolicyO
PURPOSE Retrieves this scroll pane's scrollbar display policy.
SYNTAX public int getScrol 1 barDi spl ayPol i cyQ
DESCRIPTION See the class description for more information about scrollbar display policies.
RETURNS One of SCROLLBARS-ALWAYS. SCROLLBARS_AS_.NEEDED. or SCROLLBARS.NEVER.
EXAMPLE Sec SCROLLBARS__ALWAYS.
getScrollPosition()
PURPOSE Retrieves the \ iewporf s scroll position.
SYNTAX public Point getScrollPositionO
DESCRIPTION The scroll position is the location of the viewport relative to the child. It can have values in this range: x = Math.max(0t chi Id.get PreferredSi zeO .width - getViewportSizeO .width); у = Math.max(0, chi Id.getPreferredSizeO.height getviewportSizeO.height); See the class description for more details.
RETURNS A non-null point containing the viewport's scroll position.
EXAMPLE See the class example.
1352
java.aw i
ScroilPan
get VAdju st ablet
getVAd ju.stable()
Bl rposi Retrieves this scroll pane's vertical scrollbar.
svxiw public Adjustable getVAdjustable()
descriptiox This method returns an adjustable object that represents the scroll pane's verti-
cal scrollbar. See the Adjustable interface for more information on how to
manipulate the scrollbar. However, three Adjustable methods—setMini-
mumO . setMaximumO. and setVi si bl eAmount О—must not be called: if
any is called, it throw s an AWTError exception.
reti rxs A non-null adjustable object representing the vertical scrollbar.
see also getHAd j ustabl e().
exampi I. See getHAdjustableO.
getViewportSize()
Pt RPOSL.
SY.X I A.X
Retrieves the dimensions of this scroll pane's viewport.
public Dimension getViewportSize()
descripiiox The viewport dimensions do not
include the scroll pane's scrollbars or
other borders. The viewport bounds
arc exactly the scroll pane bounds,
reduced by the scroll pane's insets
isee Container .getlnsetsO ).
reti rxs A non-null Dimension object con-
taining the dimensions of the view-
port.
exampi E This example demonstrates how to
resize a frame so that the child com-
FIGl RE 335: Scrol 1 Pane’s Viewport.
ponent within a scroll pane is complete!} visible. It does this by first compar-
ing the si/e of the viewport with the si/e of the child and then enlarging the
frame by the difference in si/e. See Figure 335.
import java . awt . ;
import java.awt.event.';
class Main extends Frame implements ActionListener {
ScrollPane sp = new Scrol1 PaneC);
Button fullviewBtn = new Button("Ful1 View”;;
circle circle new Circlet;;
java.awt
Scroll Pane
get View port Sized
Main() {
super("getViewportSize Example");
ful1viewBtn.addActionListener(thi s);
// Layout and show the components.
sp.add(c i rcle);
add(sp» BorderLayout.CENTER);
add(fu1IviewBtn, BorderLayout.NORTH);
setSize(200, 150);
show():
}
public void actionPerformed(ActionEvent evt) {
Dimension d - sp.getViewportSize();
Dimension cd = circle.getSize();
int dW - cd.width - d.width;
int dH = cd.height - d.height;
// Take into account the width of the scrollbar if necessary.
dw -- (dH > 0) ? sp.getVScrol1barWidth() : 0;
dH -- (dW > 0) ? sp, getHScrol IbarHeightO : 0;
setSize(getSize().width + dw, getSizeO.height + dH);
vali date();
fu11 viewBtn.enable(false);
}
public void doLayoutO {
super. dot ayoutO ;
Dimension d = sp.getViewportSize();
ful1v i ewBtn.enable(
d.width < circle.getPreferredSizeO.width
I d.height < circ1e.getPreferredSize().height);
}
public static void main(String argsLJ) {
new Mai n() ;
}
}
class Circle extends Component {
Dimension size - new Dimension(200, 200);
public Dimension getPreferredSizeO {
return si/e;
}
public void paint(Graphics g) {
g.setColor(Col or.lightGray);
g. fi 11 Rect(0, 0, getSi zeO .wi dth, getSi zeO . height);
// Center the painted circle.
g.setCol or(Color.red);
g.fi1lOval((getSizeO.width-size.width)/2,
(getSizeO . height -si ze. hei ght) /2, size.width-1, size, hei ght 1);
}
}
1354
java.awt
Scroll Pane
getVScrollbarWidthf)
getVScrollbarWidth()
PURPOSE Retrieves the width of this scroll pane’s vertical scrollbar.
SYNTAX public: int getVScrol 1 barWidthО
DESCRIPTION This method returns lhe width of this scroll pane’s vertical scrollbar. This num- ber is typically used in si/e calculations that invoke the scroll pane’s viewport. The returned value is independent of whether the scrollbar is currently being displayed. If the scroll pane’s peer is not created, this method returns 0.
RETl’RNS The non-negative pixel width of a vertical scrollbar.
SEE ALSO getHScrol1barHei ght О.
EXAMPLE; See getViewportSi zeO.
layoutO DEPRECATED
PURPOSE Replaced by doLayoutQ.
SYMAX public void layoutO
OVERRIDES Container.layoutQ.
DEPRECAIION See Container .1 ayoutQ.
paramStringO
PURPOSE Generates a string representation of this scroll pane's state.
SYNTAX public String paramStringO
DESCRIH ION A subclass of this class should override this method and return a concatenation of its state with the results of super. paramStringO. This method is called by toStringO and is typically used for debugging.
OVERRIDES SEE ALSO Contai ner. paramStringO. java.lang.Object.toString().
EXAMPLL See Component.paramStringO.
printComponents()
PURPOSE
Prints this scroll pane and its child.
ScrollPane
ja\ a.aw t
SCROTI.В ARS_ALWAYS
SYNTAX public void printComponents(Craphics g)
DESCRIPTION 'This methods prints the scroll pane and its child on q. The g parameter is lx pi call} a PrintGraphics object.
PARAMETERS
g /X non-null graphics context.
OVERRIDES Contai ner.pri ntComponents ().
Si l: Al SO Component.pri nt(), Component.pri ntAl1().
EXAMPI E See Component.pri ntAl1().
SCROLLBARS.ALWAYS
purposi The scrollbar displa} policx specifying that scrollbars arc alwa\s displac'd.
SYNTAX public static final int SCROlLBARS.ALWAYS
seealso SCROLLBARS.AS.NEEDED, SCROLLBARS.NEVER.
example This example demonstrates the three different scrollbar display policies. \
choice object is used to select between the policies. Since \ou cannot change
the scrollbar display policy on an existing scroll pane, a new scroll pane must
be created whenever the policy is changed. Ihc current scroll pane in the
frame is then replaced by the new scroll pane, Tigure 316 shows the scroll
pane when SCROLLBARS.NEVER and SCROLLBARS.NEFDED arc used.
FIGI RE 336: Examples of Scrollbar Display Policies.
import java.awt.';
import java, awt .event.-';
class Main extends Frame implements ItemListener {
Choice policyCh = new ChoiceO;
ScrollPane sp - new Scrol1Pane(Scrol1 Pane.SCROLLBARS.ALWAYS);
1356
ScrollPane
SCROLLBARS_AIAVAYS
java.awt
CircleComponent circle = new CircleComponentО;
MainO {
super (’’SCROLLBARS,. ALWAYS Example”) ;
// Initialize policy choice.
poi icyCh. addItem(’,SCROLLBARS_ALWAYS") ;
poiicyCh.addItem(”SCROLLBARS AS_NEEDED”);
poiicyCh.addItem(”SCROLLBARS_NEVER");
policyCh.select(0);
poiicyCh.additeml istener(this) ;
// layout and show components.
sp.add(ci rcle);
add(spt BorderLayout.CENTER);
add(poli cyCh, BorderLayout.NORTH);
setSize(200, 150);
showO;
}
public void itemStateChanged(TtemEvent evt) {
int p = sp.getScrolIbarDisplayPolicy();
if (''SCROL LBARS-ALWAYS”. equals(evt. getltemQ)) {
p = Scroll Pane.SCROLLBARS-ALWAYS;
} else if (”SCROLLBARS_AS_NEEDED".equals(evt.getltemQ)) {
p = Scroll Pane.SCROLLBARS_AS_NEEDED;
} else if ("SCROLLBARS_NEVER" . equal s(evt .getTtemQ)) {
p - Scroll Pane.SCROLLBARS.NEVER;
}
if (sp.getScrollbarDisplayPolicyQ 1= p) {
// Create a new scroll pane with the new display policy.
remove(sp);
sp » new Scrol 1 Pane(p) ;
sp.add(circle);
add(sp, BorderLayout.CENTER);
val idateQ;
System.out. print In(sp. getHAd justableQ);
System.out.pri ntln(sp. getVAd justableQ);
}
public static void main(String argsf]) {
new MainO ;
}
class CircleComponent extends Canvas {
public Dimension getPreferredSizeO {
return new Dimension(200, 200);
}
public void paint(Graphics g) {
g.setColor(Color.lightCray);
g.fi1lOval(0, 0, 200, 200);
g.setColor(Color.black);
g.drawOva1(0, 0, 200, 200);
ScrollPane
SCROLLBARS AS NEEDED
java.awt
SCROLLBARS„AS NEEDED
PURPOSE- The scrol Ibar display policy specifying that scroll bars are displayed as needed.
SYMAX public static final int SCROLLBARS_AS_NLLDED
A DLSCR1PIION Under this scrollbar display policy, the horizontal scrollbar appears only when
В the child’s preferred width is wider than the viewport's width. The vertical
C scrolIbar appears only when the child's preferred height is higher than the
n viewport s height.
Lf SEE ALSO SCROl 1 BARS_ALWAYS, SCROLLBARS_NEVER.
E F EXAMPLE; See SCROLLBARS_ALWAYS.
G
„ SCROLLBARS NEVER
I purpose The scrollbar display policy specifying that scrollbars are never displayed.
J symax public static final int SCROLLBARS_NEVER
К DESCRIPTION Under this scrollbar display policy, the scrollbars are never displayed. How-
I ever. the scrollbars do exist and can be retrieved using getHAdjustableQ or
1 „ getVAdjustableQ.
M SEE Al SO getHAdjustableQ, getVAdjustable()t SCROLLBARS_ALWAYS,
N SCROLLBARS_AS_NEEDED.
О example: See SCROLLBARS_ALWAYS.
ScrollPaneO
pi rpose: Constructs a new Scrol 1 Pane instance.
symax public ScrollPaneO
public Scrol1Pane(int sbPolicy)
description This constructor creates a new scroll pane that has a scrollbar display policy of
sbPolicy. If sbPolicy is not specified, the constructor defaults to
SCROLLBARS AS_NEEDED. The dimensions of the new scroll pane are 100-x-
100 pixels.
PARAMETERS
sbPol i cy Must be one of the scrollbar display policies.
SEE ALSO SCROLLBARS_ALWAYS, SCROLLBARS^S_NEEDED, SCROLLBARS.NEVFR.
example: See the class example.
1358
ScrollPane
setLayoutO
java.awt
setLayoutO
PURPOSE This method does nothing.
SYNTAX public final void setLayout(LayoutManager mgr)
DESCRIPTION The scroll pane has a built-in layout manager and should not be changed. This method is overridden and declared final so that any attempt to override this method or set the layout manager will be ignored.
parameters mgr This parameter is ignored.
OVERRIDES Contai ner. setLayoutO
setScrollPositionO
PURPOSE Moves the viewport's scroll position.
SYNTAX public void setScrollPosition(int x, int y) public void setScrollPositionfPoint pt)
DESCRIPTION This method moves the viewport's scroll position to the location pt. If pt is not specified, the new scroll position is (x, y). If (he scroll position is not in the range: x = Math.max(0, chi Id .getPreferredSizeO .width-getViewportSizeO .width); у = Math,max(0, chi Id.getPreferredSizeO . height-getViewportSizeO .height) ; it is silently moved within this range. For example, if the coordinate is nega- tive. it becomes 0. See the class description for more information about the scroll position. A call to this method is only valid if the scroll pane contains a child otherwise Null Poi nterException is thrown.
PARAMETERS Pt X У A non-null point container the scroll position. The л-coordinate of the scrol! position. The y-coordinate of the scroll position.
example: See the class example.
java.awt.peer
ScrollPanePeer
A
В
C
D
Г
Syntax
public interface ScrollPanePeer extends ContainerPeer
Description
The scroll pane (see the Scrol IPane class) in the AWT uses the platform’s native implemen-
tation of a scroll pane. So that the AWT scroll pane behaves the same on all platforms, the
scroll pane is assigned a peer. whose task is to translate the behavior of the platform’s native
scroll pane to the behavior of the AWT scroll pane.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the /\WT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java. awt counterparts.
See Component and Tool ki t for additional information about component peers.
MEMBER SUMMARY
Peer Methods
childResizedO
; getHScrollbarHeightО
« getVScrol1barWidth()
setSc roll Pos i tionO
setUni tlncrement()
setValue()
Notifies the peer that the child component has been resized.
Retrieves the height of the scroll pane's horizontal scrollbar.
Retrieves the width of the scroll pane's vertical scrollbar.
Sets the scroll pane’s coordinates.
Sets the scroll pane's unit increment.
Sets this scroll pane’s value.
See Also
java.awt.Component, java.awt.Scrol1 Pane, java.awt-Toolkit.
1360
java.awt.peer
ScrollPanePee
childResized(
childResized()
purpose Notifies the peer that the child component has been resized.
syntax void chiIdResized(int w, int h)
PARAMETERS
h The height of the scroll pane's child component.
w The width of the scroll pane s child component.
see also java.awt .Scrol 1 Pane. doLayoutO.
getHScrollbarHeight()
purpose Retrieves the height of lhe scroll pane's horizontal scroll bar.
syntax int getHScrolIbarHeightO
returns The height of the scroll pane's horizontal scroll bar.
see also java.awt. ScrollPane.getHScrol IbarHeightO.
getVScrollbarWidth()
purpose Retrieves the width of the scroll pane's vertical scroll bar.
syntax int getVScrollbarWidthO
returns The width of the scroll pane's vertical scroll bar.
see At so java.awt.Scrol1Pane.getVScrolIbarWidthf).
setScrollPosition()
purpose Scrolls to a position w ithin the child component in the scroll pane.
syntax void setScroTIPositionCint x, int y)
parameters
x The л-coordinate to which to scroll.
у The y-coordinate to which to scroll.
sei also java.awt.ScrollPane.setScroll Posit ion().
ScrollPanePeer
setUnit Increment!)
java.awt.peer
setUniuncrement()
Pl RPOSL SYNTAX Sets the scroll pane's unit increment. void setUnitIncrement(Adjustable adj. int increment)
PARAMETERS
в adj The adjustable (scroll pane) to increment.
c i ncrement I'he non-negative unit increment.
D SEE XLSO java.awt.Adjustable, java.awt.Scrol1 Pane.setUnitIncrement().
E Г setValue()
Cl Pl RPOSI Sets the value of an adjustable in this scroll pane.
H SYNTAX void setVa1ue(Adjustable adj, int value)
I PARAMETERS
J adj The adjustable whose value to set.
к val ue I’he adjustable’s new value.
I. M N 0 P Q R SEE. Al.SO java.awt.Adjustable, java.awt.Scrol1 Pane.setValue0.
T
V
V
w
X
Y
Z
1362
java.awt
Shape
Syntax
public interface Shape
Description
The Shape interface is used to represent a geometric shape, such as a circle or a rectangle, on a
2D plane. Currently, the only supported shape in the AWT is Rectangle. This interface is sub-
ject to change in future releases and should not be used directly.
MEMBER SUMMARY
Shape Method
get Bounds О Retrieves the bounding rectangle of this shape.
See Also
Rectangle.
Example
This example defines two new shapes: a square and a circle. It creates three instances of differ-
ent shapes (square, rectangle, and circle) and then prints out their bounds.
import java.awt.-;
class Square extends Rectangle {
public Squarefint x, int y, int length) {
super(x, y, length, length);
}
}
class Circle implements Shape {
int x, y, radius;
// circle centered at x, y, with radius ‘radius*
public Circlefint x, int y, int radius) {
t h i s. x - x;
this.у = у;
this.radius = radius;
1
java.awt
Shape
gclBoundsf)
public Rectangle getBoundsO {
// (x, y) is center of circle; offset x and у by circle's radius
return new Rectan>le(x-radius, y-radius, radius*2, radius*2);
}
}
class Main {
public static void mai n(Stri ng[] args) {
Shape si = new Square(15, 20, 50);
Shape s2 - new Rectangle(65, 20, 25, 30);
Shape s3 = new Circle(115, 20, 10);
System.out.println(“square: “ * si.getBoundsO);
System.out.printl n(’‘rectangle: “ s2 .getBoundsO) ;
System.out.println(“circle: “ + s3.getBoundsO) ;
getBoundsf)
Pl RPOSE Retrieves the bounding rectangle of this shape.
SYNTAX public Rectangle getBoundsO
RETl’RNS The non-null bounding rectangle of this shape.
SEE ALSO Rectangle. getBoundsO.
EXAMPLE See the class example.
1364
java.beans
SimpleBeanlnfo
j SigyleBeemiafg
Syntax
public class SimpleBeanlnfo implements Beaninfo
Description
When a bean editor loads a bean, it asks the introspector (see Introspector) to construct a
set of feature descriptors (see FeatureDescriptor) that contain information used by a bean
editor to create an interface for editing the bean. By default, the introspector uses a process
called introspection to discover the feature descriptors for a bean. This process basically
involves detecting signature patterns in the bean’s public methods (see Introspector for
more details). However, some feature descriptors created by introspection may not have the
desired values (since there arc some things that the introspector cannot determine). In this
case, the bean must provide explicit feature descriptors for the introspector. These explicit fea-
ture descriptors are packaged in an object called a bean-info.
This class provides a convenient superclass for building a bean-info, h provides simple
defaults for all of the bean-info methods. See Beaninfo for complete information on bean-
infos and how to build them.
MEMBER SUMMARY
Descriptor Methods getBeanDescriptorO getEventSetDesc riptorsO getMethodDescri ptorsO getPropertyDesc riptorsO Retrieves the bean-info’s bean descriptor. Retrieves the bean-info’s event set descriptors. Retrieves the bean-info’s method descriptors. Retrieves the bean-info's property descriptors.
Additional Info Method getAddi tionalBeanlnfoO Retrieves a set of additional bean-info objects.
Default Index Methods getDefaul tEventlndexO getDefaul tPropertylndexO Retrieves the index of the bean-info's default event set. Retrieves the index of the bean-info's default property.
Image Methods getlconO loadlmageO Retrieves the bean-info’s icon. Loads an image relative to the bean-info.
SimpleBeanlnfo
java, bean
See Also
BeanDescriptor, Beaninfo, EventSetDescriptor, IndexedPropertyDescriptor,
MethodDescri ptor, PropertyDescri ptor.
A
В
C
I)
E
E
G
H
I
J
К
E
M
N
О
Example
<BeanBox
File Edit View Help
< Too IB ox
BeanBox
i Bean®
PropertySheet
FKJI'RE 337: SimpleBeaninfo.
P
Q
R
s
T
I1
V
w
zX
Y
This example is a simple demonstration of how to provide implementations lor all ol the meth
ods in a bean-info. The bean loads and displays an image. T he image is scaled lo fit exactly in
the bounds of the bean. The bean also has number of dummy methods used to demonstrate
various methods in the bean-info. See Figure 337.
The image used by the bean is bundled in the same jar file as the bean. The bean must use
Cl ass . getResourceQ to find and load it.
'The bean-info defines feature descriptors for each of the four categories (bean descriptor,
event set descriptor, method descriptor and property descriptor). Two property descriptors are
defined so that one of them can be set to be the default. Also, two event set descriptors are
defined so that one of them can be set to be the default.
The bean-info also contains images foi each of the icon types (Bean-
Info .IC0N_C0L0R16xl6. Beaninfo.ICON_COLOR32x32. Beaninfo.ICON_MONOI6xl6.
Beaninfo.ICON_MONO32x32).
1366
java.beans
SimpleBeanlnfo
Bean.java
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
public class Bean extends Canvas {
Image image;
public BeanO {
try {
URL url = getClassO .getResource(,,duke.gif’1);
Toolkit tk - Toolkit.getDefaultToolkit();
image = tk.createImage((ImageProducer)url.getContentQ);
} catch (lOException e) {
e.printStackTraceO;
}
}
public void paint(Craphics g) {
if (image != null) {
g.drawlmage(image, 0, 0, size().width, size().height, this);
}
public void method() {
}
public int getPropertylO {
return 0;
}
public void setPropertyl(int s) {
}
public int getProperty2O {
return 0;
}
public void setProperty2(int s) {
}
public void addlumpListener()umpListener evt) {
}
public void removelumpListenerQumpListener evt) {
}
}
/*
manifest.txt:
Name: Bean.class
lava-Bean: True
jar command:
jar cfm bean.jar manifest.txt *.class *.gif
V
Bean Bean Info, java
import java.beans.*;
public class BeanBeanlnfo extends SimpleBeanlnfo {
public Beanlnfo[] getAdditionalBeanlnfoQ {
try {
BeanlnfoEJ bi = new Beanlnfo[l];
SimpleBeanlnfo
java.beans
bi[0] = Introspector.getBeanlnfo(Bean.class.getSuperclassO);
return bi;
} catch (IntrospectionException e) {
e. pri ntStackTraceO ;
}
return null;
}
public BeanDescriptor getBeanDescriptorО {
BeanDescriptor bd new BeanDescriptor(Bean.class);
bd.setDisplayName(”Bean\u00a9"); // Copyright symbol
return bd;
}
public MethodDescriptor[] getMethodDescriptorsO {
try {
MethodDescriptor md[] - new MethodDescriptor[1J;
md[0] - new MethodDescri ptor(Bean. class .getMethodCmethod’1, null));
return md;
} catch (NoSuchMethodException e) {
e.printStackIraceO ;
}
retu rn nul1;
}
public int getDefaultPropertylndexO {
return 1;
}
public PropertyDescriptor[] getPropertyDescriptorsO {
try {
PropertyDescriptor pd[] = new PropertyDescriptor[?];
// The getter and setter methods are derived from the property name.
pd[01 = new PropertyDescri ptor (’'propertyl" , Bean, class);
pd[l] = new PropertyDescriptorC'property?", Bean.class);
return pd;
} catch (IntrospectionException e) {
e. pri ntStackTraceO ;
}
return null;
}
public int getDefaultEventlndexQ {
return 1;
}
public EventSetDescriptor[] getEventSetDescriptorsO {
try {
EventSetDescriptor[] esd = new EventSetDescriptor[2];
esd[0] = new EventSetDescriptor(Bean.class,
,reventl", JumpListener.class, "beanJumped");
esd[l] = new EventSetDescriptor(Bean.class,
"eventZ’1, JumpLi stener .class, ’’beanJumped");
return esd;
1368
SimpleBeanlnfo
get Additional Bean I nfof)
java.beans
} catch (IntrospectionException e) {
e.printStackTraceO ;
}
return null;
}
public java.awt.Image getlcon(int iconKind) {
switch (iconKind) {
case TCON_COLOR_16xl6:
return loadlrpage(”duke-color-16x!6.gi f”);
case ICON_COLOR_32x32:
return loadimage("duke-color-32x32.gif");
case ICON-MONO .16x16:
return Ioadlmage("duke-mono-l6xl6.gif’');
case ICON_MONO_32x32:
return loadimage("duke-mono-32x32.gif");
default:
return null;
}
}
}
JumpListener.java
import java.awt.';
public class JumpListener {
public void beanlumped(AWTEvent evt) {
}
1
getAdditionalBeanInfo()
purpose Retrieves a set of additional bean-info objects.
syntax public BeanlnfoLJ getAddi tionalBeanlnfoO
descrip no\ A bean may provide bean-info objects in addition to its own. This gives a bean
editor more information for editing the bean. In practice, the additional bean-
info objects are typically of the bean’s superclasses. For example, if a bean
extends from Component, it may include the component's bean-info in the list
of additional bean-info objects. In this way, the user will be able to edit not
only the bean’s features (properties, methods, and so on) but also the features
of component.
This method returns null. If additional bean-info objects are available, this
method should be overridden to return them in an array. If there are any con-
flicts between the bean-info objects in the returned array, the bean-info object
with the highest index takes precedence (for example, one property descriptor
says a property is bound, while the other says it is not). However, the descrip-
SimpleBeanlnfo java.beans
getBeanDeseriptor()
tors in this bean-info object take precedence over the bean-info objects in lhe returned array.
RETl RNS A possibly null array of bean-info objects. The length of the array indicates the number of bean-info objects.
LX AMP! E See the class example.
getBeanDescriptorO
Pl RPOSE Retrieves the bean info\ bean descriptor.
SYN'IA.X public BeanDescriptor getBeanDescriptor()
DESCRIP 1 ION This method returns null. If an explicit bean descriptor is available, this method should be overridden to return it. This method is typically called by lhe introspector (see Introspector}. When it returns null, lhe introspector determines the bean descriptor through intro- spection.
RET! 'RS S A possibly null bean descriptor.
SEE A I.SO BeanDescri ptor.
EXAMPI F See the BeanDescri ptor class example.
getDefaul tE ventindex ()
pi rpose: Retrieves the index of the bean-info s default event set.
SYNTAX public int getDefaultEventlndex()
DESCRIPTION This method returns -1. which informs the caller that a default event set does not exist. If a default event set does exist, this method should be overridden to return the index of the event set descriptor (for the default event set) within the array returned by getEventSetDescri ptorsQ. If getEventSetDescriptorsO returns null, this method must return -1.
RE.Tl’RNS The index of the default event set in the getEventSetDescriptorsO array; 1 if no event set exists.
SEE ALSO getEventSetDescri ptorsC)» EventSetDescri ptor.
EXAMPLE. See the class example.
1370
java.beans SimpleBeanlnfo geiDefau!tProperlylndcx( 1
getI)efaultPropertyIndex()
PURPOSE Retrieves the index of the bean info's default property.
SYNTAX public int getDefaultPropertylndexO
DESCRIPTION This method returns 1. which informs the caller that no default property exists. If a default property does exist, this method should be overridden to return the index of lhe property descriptor (for the default property) within lhe array returned by getPropertyDescriptorsQ. If getPropertyDescriptorsQ returns null, this method must return -1.
RETI RNS The index of default property in the getPropertyDescri ptors Q array: -1 if no default property exists.
SEE Al SO getPropertyDescriptors, PropertyDescriptor.
EXAMPLE See the class example.
getEv entSetDescriptors()
PVRPOSE Retrieves the bean-info s event set descriptors.
SYNTAX public LventSetDescriptor[] getEventSetDescriptorsQ
DESCRIPTION This method returns null, which informs the caller that no explicit event set descriptors are available. If the bean-info has any explicit event set descriptors, this method should be overridden to return them in an array. This method is typically called by the introspector (see Introspector). When it returns null, lhe introspector determines the bean's event sets through intro- spection.
RETI RNS Л possibly null array of event set descriptors. The length of the array indi- cates the number of event set descriptors.
SEEALSO EventSetDescriptor.
EXAMPLE See lhe EventSetDescriptor class example.
getlconO .
PURPOSE Retrieves the bean-info's icon.
SYNTAX public java.awt.Image getlcon(int iconKind)
DESCRIH ION This method always returns null, which informs the caller that no icons are available.
SimpleBeanlnfo
getMethodDescriptorsO
java.beans
You should override this method to return an image that a bean editor can use to represent the bean, I'he method should return nul 1 if ihe requested icon tv pe is not available. If the requested icon type is a color image but is not available, the method can return a monochrome image in the requested size. The background pixels of the returned image should be transparent.
PARAMETERS i conKi nd The desired icon type. Must be one of Bean Info.IC0N_C0L0R_16xl6. Bean- Info. ICON—COLOR—32x32. Beaninfo.ICON_MONO_16xl6. or Bean- Info. ICON_MONO_32x32.
SEE Al.SO java.awt.Image.
EXAMPLE See the class example.
getMethodDescriptorsO
PUR POST: Retrieves the bean-info*s method descriptors.
SYS 1 AX public MethodDescriptorГ1 getMethodDescriptorsO
DESCRIPTION This method returns null, which informs the caller that no explicit method descriptors are available. If the bean-info has any explicit method descriptors, this method should be overridden to return them in an array. This method is typically called by the introspector (see Introspector). When it returns null, the introspector determines the bean's methods through intro- spection.
RETURNS Л possibly null array of method descriptors. I'he length of the array indicates the number of method descriptors.
SEE ALSO MethodDescri ptor.
EXAMPLE See the MethodDescriptor class example.
getProperty DescriptorsO
PURPOSE Retrieves the bean-info's property descriptors.
SYNTAX public PropertyDescriptorLI getPropertyDescriptorsO
DESCRIPTION This method returns null, which informs the caller that no explicit property descriptors are available. If the bean-info has any explicit propert) descriptors, this method should be overridden to return them in an arrav.
1372
java.beans SimpleBeanlnfo loadlmageQ Any indexed property descriptors should also be included in the returned array. I’he caller can determine which property descriptors are indexed property descriptors by using the instanceof operator. This method is typically called by the introspector (see Introspector). When it returns null, the introspector determines the bean’s properties through intro- spection.
RETURNS A possibly null array of property descriptors. lhe length of the array indi cates the number of properly descriptors.
SEE ALSO Proper tyDesc ri ptor.
EXAMPLE See the PropertyDescri ptor class example.
loadlmageQ
PURPOSE Loads an image relative to the bean-info.
SYNTAX public java.awt.Image loadimage(String resourceName)
DESCRIPTION This method is used to load an image that has a location relative to lhe bean- info class file. For example, if the bean-info class file is in directory D and the image is located in D/images/image .gif. then resourceName should be images/image.gif. This method is used most often when the image is con- tained in the same jar file as lhe bean-info (and bean).
PARAMETERS
resourceNameThe non-null relative pathname of an image.
RETURNS A possibly null image object containing an icon.
example: See the class example.
j a v a. a wt .datatran sfer
StringSelection
A
В
c
Syntax
public class StringSelection implements Transferable, ClipboardOwner
E
i Description
G The most common data type that appears on the clipboard is the string, However strings can-
not be placed on the clipboard directly, since a clipboard can hold only transferable objects
H (see Transferable). /X string must first be placed inside a transferable object before it can be
1 placed on the clipboard.
This class makes it convenient to place strings on the clipboard. It implements a transfer-
able object called a siring selection that holds strings. You need only to create a string selec-
K tion containing the desired string and place the string selection on the clipboard using
I Clipboard. setContentsO- Other applications can then retrieve the string selection from
the clipboard using Clipboard.getContentsO See Clipboard for more details.
N Data Flavors
When an application stores some data on the clipboard, it also must include with lhe data all of
the data flavors that are supported. See the DataFlavor class for a detailed discussion on data
P flavors.
q A string selection supports two data flavors: string and plain text. When an application
specifies string flavor, the string is returned as a String object. When an application specifies
plain text flavor, a string reader (see StringReader) is returned that contains lhe string. With
either data flavor, the resulting strings are identical.
T These two data flavors are provided, by default, in the DataFlavor class. The name of the
string flavor is DataFl avor. stri ngFl avor. The name of the plain text flavor is DataFla-
vor. pl ai nTextFl avor.
V
x ^MEMBER SUMMARY ~~
Y I Constructor
I Stri ngSelectionO Constructs a new Stri ngSelection instance.
Data Method
getTransferDataO Retrieves the string contained in the string selection.
1374
java. awt. datatransfer
StringSelectior
MEMBER SUMMARY
Data Flavor Methods
getTransferDataFl avorsО
1 sDataFlavorSupportedO
Clipboard Method
lostOwnershipO
Returns an array of supported data flavors.
Determines if this string selection supports a data flavor.
Called when this string selection loses ownership of the
clipboard.
See Also
Clipboard, DataFlavor, java.iо.StringReader, Transferable.
Example
This example creates a list of text items. Selecting an
item causes a string selection to be created for that
item and to be set on the system clipboard. This makes
the text item available to be copied by any other appli-
cation on the desktop. See Figure 338.
For an example that demonstrates how to retrieve
the string stored in a string selection, see the
getTransferData() example.
* StringSelection Ex... ИРГ'
Apple
Blueberry
Cantaloupe
Durian
J
FIGURE 358: Putting a String on the
System Clipboard.
import java.awt.*;
import java.awt.datatransfer;
import java.awt.event.v;
class 4ain extends Frame implements ItemListener {
List 1 = new Li st О;
Main() {
superCStringSelection Example11);
// Ini ti ali ze list.
1.addItem("Apple");
1 . addltemC’Bl ueberry") ;
1 .addltemC’Cantaloupe") ;
1.addltemC’Durian”);
add(l , BorderLayout.CENTER);
// Listen for item events.
1.addltemListener(this);
setSize(100, 150);
show();
StringSelection
getTransferDataO
java.awt.datatransfer
public void itemStateChanged(ItemEvent evt) {
// Retrieve item index.
int item - ((Integer)evt.getltemQ).intValueQ ;
// Retrieve handle to clipboard.
A Clipboard clipboard - getTool ki t() .getSystemCl ipboardQ ;
В // Create the string selection.
StringSelection ss ~ new StringSelection(l.getltem(item));
C
// Set contents of clipboard with string selection.
I) clipboard,setContents(ss, null);
}
E
public static void main(String[] args) {
F new Mai n();
}
G }
H
I
j getTransferData()
Pl rpose Retrieves the string contained in the string selection.
I. SYNTAX public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, lOException
M DESCRIPTION The string selection supports two data flavors: DataFlavor.stringFlavor
N and DataFlavor.pl ai nTextFlavor.
() If the requested data flavor is DataFlavor.stringFlavor. this method
P returns a non-null String object. If the requested data flavor is DataFla-
Q vor. pl ai nTextFlavor. this method returns a Stri ngReader from which the string can be read.
R Note: In Java 1.1.2, the representation class of DataFlavor. plainTextFla-
vor is java. io. Input St ream: it should be java. io. Stri ngReader.
T
и
v
w
x
Y
Z
PARAMETERS
flavor The non-nul 1 requested data flavor.
reiurns A non-nul 1 data flavor.
EXCEPTIONS
lOExcepti on If rhe data is no longer available.
UnsupportedTlavorExcepti on
If flavor is neither DataFlavor.stringFlavor nor DataFlavor.plain-
TextFlavor.
seealso DataFlavor, java.lang.String, java.io.StringReader.
1376
_________StringSelection
getTransferDataFlavorsf
ja v a. a wt. dalat ransfe г
example This example assumes that a string selection is on the clipboard and shows
how io print its contents:
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.w;
class Main {
// getTransferData Example
public static void main(String[] args) {
int numRead;
char buffer[] - new char[1024];
Printwriter out = new PrintWriter(System.out);
// Retrieve handle to clipboard and contents
Clipboard clipboard =
loolkit.getDefaultToolki t().getSystemClipboard() ;
Transferable t clipboard.getContents(nu11);
if (t == null) {
// Clipboard is empty,
return;
}
try {
// Retrieve as string flavor.
String s = (String)t.getTransferData(
DataFlavor.stringFlavor);
System, out.printlnC'Clipboard Contents = ”+s) ;
// Retrieve as plain text flavor.
StringReader r = (StringReader)t.getTransferData(
DataFlavor.plai nlextFlavor);
while ((numRead = r.read(buffer, 0, buffer.length)) >= 0) {
out,write(buffer, 0, numRead);
}
} catch (lOException e) {
} catch (UnsupportedFlavorException e) {
J
}
getTransferDataFla vors()
PURPOSE Returns an array of supported data flavors.
SYM’AX public synchronized DataTlavorf] getlransferDataFlavorsO
DESCRIPTION The string selection supports two data flavors: DataFlavor.stringFlavor and DataFlavor. plai nTextFl avor. This method returns a two-element array containing these flavors.
RETURNS A non-nul 1 array of the two supported data flavors.
StringSelection
isDataHavorSupported()
ja\ a.aw t.datatran sfer
SR-Also DataFlavor.
ex xmpi i This example prints lhe data flavors supported by the current content of the
system clipboard. If the content is a string selection, the output is shown as fol-
low s:
import java.awt.*;
import java.awt.datatransfer. *;
import java.io.";
class Main {
// get!ransferDataFlavors Example
public static void main(StringГ1 args) {
// Retrieve reference to clipboard and contents
Clipboard clipboard -
Toolkit.getDefaultTool kit О.getSystemClipboard();
Transferable t <= с Iipboard.getContents(nul1);
if (t -= null) {
// Clipboard is empty,
return;
}
DataFlavor flavorsf] = t .getTransferDataFl avorsO;
for (int i-0; i<flavors.1ength; i++) {
System.out.pri ntln(flavors Гi1.getHumanPresentableName());
Syst em.out. pri ntl n(*' ” + f 1 avors [i J .getRepresentationClassO);
System.out.println(" "*flavors[i].getMImeTypeO):
}
}
}
огтрсг This output would appear if the system clipboard contained a string selection.
Note that this output has been doctored to show correct results. In Java 1.1.2. the
text class java. iо. Stri ngReader actually comes out as nu 11. There is a
bug where the representation class is null.
Unicode String
class java.1ang.String
application/x-java-serial ized object
Plain lext
class java.io.StringReader
text/plain; charset^unicode
V
isDataFlavorSupportedO
pi rpose Determines if this string selection supports a data flavor.
syntax public boolean isDataFlavorSupported(DataFlavor flavor)
description The string selection supports two data flavors; DataFlavor.stringFlavor
and DataFl avor. plai nTextFlavor.
1378
java.awt.datatransfer
StringSelection
lostOwnershipO
PARAMETERS flavor The non-null requested data flavor.
RETURNS true if flavor is supported by this string selection; false otherwise.
SEE ALSO DataFlavor.
EXAMPLE: This code fragment shows how to check for the two flavors that a string selec- tion supports:
// Retrieve handle to clipboard and contents
Clipboard clipboard =
Toolkit .getDefauItToolkitO .getSystemCl ipboardO ;
Transferable t * clipboard.getContents(nul1);
if (t == null) {
// Clipboard is empty.
return;
}
if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
System.out.println("yes");
}
if (t.isDataFlavorSupported(DataFlavor.plainTextFlavor)) {
System.out.pri ntln("yes");
}
lostOwnershipO
PURPOSE Called when this string selection loses ownership of the clipboard.
SYNTAX public void lostOwnershipfClipboard clipboard, Transferable contents)
DESCRIPTION This method is called by the AWT system when this string selection is no longer in clipboard. The contents parameter should be equal (have the same reference as) to this siring selection object. This method, as defined in Stri ngSel ection, does nothing. For this method to do something useful, it must be overridden by a subclass.
PARAMETERS clipboard contents The non-null handle to a clipboard. The non-null old contents of lhe clipboard.
EXAMPIE See Cli pboardOwner.lostOwnershi p().
java.awt.datatransfer
StringSelection
StringSeleciionO
StringSelectionO
PURPOSE Constructs a new StringSelection instance.
SYNTAX public StringSelection(String str)
A DESCRIPTION This method creates a transferable object containing str. The string can be
В C retrieved using Transferable.getTransferDataO in either string format (see DataFlavor. stringFlavor) or in plain text format (see DataFla- vor. plai nTextFl avor).
D E PARAMETERS If str is null, it is first modified to be the empty string
F str A possibly null string.
G SEE ALSO DataFlavor, Transferable.getTransferDataO-
H EXAMPLE See the class example.
J
к
L
M
N
О
P
Q
R
S
T
U
V
w
X
Y
z
1380
java.awt
SystemColor
Syntax
public final class SystemColor extends Color implements Serializable
Description
The SystemColor class contains most of lhe colors that are used by the platform to paint
native components. For example, the background color of a button and the color of its text arc
retrieved from this class. The availability of these colors enables you to create components that
blend with the native components. Figure 339 contains a map of the colors defined by this
class.
i nacti veCapti onBorder textInactiveText
i nactiveCapti onText\ \__________i 1nacti veCapti on
acti veCapti onTexW
menuText
wi ndow
windowBorder -
j'Vi n d ow T ext
wi ndowText
control
controlText
controlDkShadow
control Shadow
control Hi ghli ght
Active Window
enu
Up Button
Down Button
controlLtHighli ght
Inactive Window
acti veCapti onBorder
acti veCapti on
item C
item 1
item
item 3
scrol1 bar
textHi ghli ght
textHi ghli ghtText
text
textText
desktop
i nfo
infoText
menu
I КД RE 339: Map of System Colors»
SystemColor
java.awt
A
В
C
I)
E
I;
G
H
1
J
К
I.
M
N
()
P
Q
R
T
I
V
w
X
On some platforms, the system-w ide colors of these w indowing system parts is dynami-
cally configurable by the user. Гог example, the user can choose the background color of his
desktop, the background color of menu bars, and so on. When such changes are allowed, the
colors in this class are updated to reflect those changes. Note: In Java 1.1.2, this is not yet
working; the Java program must be restarted in order to see the new’ system colors.
Info-tags
An info-lag is a small w indow that displays a short description of an object. Info-lags are topi-
cally displayed near the cursor when you roll over the object. Гог example, if you roll over a
Cancel button, the info-tag might say, "Stops the printing process." In Windows, info-tags are
called Tooltips: on a Macintosh, they are called Balloon Help.
Note’. Info-tag is not an official name for these little windows. Since JavaSoft has not yet
named them, w e picked a name in order to talk about them.
Component Colors
When painting a component outline, you need four colors to achieve a 3D look. The four col-
ors are (in the order of brightest first) the control LtHighl ight. controlHighlight, con-
trol Shadow, and control DkShadow. The background of the component should be painted in
the control color. See the control example for a typical way in which these colors are used.
System Color Cache
For efficiency, the SystemColor class maintains a cache of the system colors that contains the
colors' RGB values. The SystemColor entries in this cache use the private fields of the Color
class in a slightly different way. Hence, when comparing a SystemColor with a Color
instance that is not a SystemColor, you should check forequality using getRCBQ- instead of
equalsO.
MEMBER SUMMARY
RGB Method
getRGBQ Retrieves the RGB value of this system color.
System Color Constants
activeCaption
acti veCapti onBorder
act i veCapt i onT ext
control
controlDkShadow
controlHighlight
controlLtHighlight
control Shadow
controlText
The background color for the title bar of an active window.
The border color of an active window.
The color of text in the title bar of an active window.
The background color of a component.
The darkest color of a 3D component's outline.
The second brightest color of a 3D component's outline.
The brightest color of a 3D component's outline.
The second darkest color of a 3D component s outline.
The color of text in a component s label.
1382
java.awt
SystemColoi
MEMBER SUMMAltF
desktop The background color of the platform\ window system desk-
top.
inactiveCaption The background color for the title bar of an inactive window.
i nacti veCaptionBorder 'I'he border color of an inactive window.
inactiveCaptionText The color of text in the tide bar of an inactive window.
info The background color of an info-tag.
infoText The color of text in an info-tag.
menu The background color of a menu component.
menuText The color of text in a menu component.
scrollbar The background color of a scroll bar.
text The background color of text components.
textHighlight The background color of highlighted text. •
textHighlightText The color of highlighted text.
textlnactiveText The color of inactive text.
textText The color of text in a text component.
wi ndow The background color of a window. ;
windowBorder The border color of a window.
wi ndowText The color of text in a window.
Debugging Method
toStri ngO Generates a string representing this system color.
Constants Lsed for System Color Cache*
ACTIVE,CAPTION Index of the background color of active captions in window borders.
ACTTVEJ2APTI0N BORDER Index of the border color of active captions in window bor- ders.
ACTIVE CAPTION-TEXT CONTROL CON IROL_DK_SHADOW CONTROL_HTGHl I GHT CONTROL_LT_HIGHLIGHT CONTROL-SHADOW CONTROL,TEXT DESKTOP INACTIVE-CAPTION Index of the text color of active captions in window borders. . Index of the background color of control objects. Index of the dark shadow color of control objects. Index of the color of highlighted control objects. Index of the color for lightly highlighted control objects. Index of the shadow color of control objects. Index of the color for the text of a control. Index of the background color of the desktop. Index of the background color of inactive captions in window borders
INACTIVE_CAPTION_BORDF R Index of the border color of inactive captions in window bor- ders.
INACTIVE CAPTION.ГЕХТ INFO INFO. TEXT Index of the text color of inactive captions in window' borders. Index of the background color of help components. Index of the text color of help components.
Continued
SystemColor
java.awt
MEMBER SUMMARY
Constants Used tor System Color Cache (Continued)
MENU Index of the backgroui
MENU_TEX1 Index of lhe text color
NUM_COI ORS Fhe number of system
SCROLLBAR Index of lhe backgroui
TEXT Index of lhe backgroui
TEXT HIGHTl TGHT Index of the backgroui
TEXT_HTGHL IGHI_TEXT Index of the text color
TEXT-INACTIVE TEXT Index of lhe text color
TFXT_TEXT Index of the text color
WINDOW Index of the backgroui
WINDOW-BORDER Index of the border co
WINDOW-TEXT Index of the text color
Index of the background color of menus.
Index of lhe text color of menus.
The number of system colors.
Index of the background color of scrollbars.
Index of lhe background color of text components.
Index of the background color ol highlighted text components.
Index of the text color of highlighted text components.
Index of lhe text color of inactixe text components.
Index of the text color of text components.
Index of lhe background color of windows.
Index of the border color of windows.
Index of the text color of windows.
a. See lhe method description of toStri ng() for the numeric \allies of these constants.
These constants arc not described elsewhere in this book because they are not intended
to be used directly. Use lhe System Color constants instead.
See Also
Color, java.io.Serializable.
Example
This example implements various "fake" components that use the system colors. The left side
of the display shows the fake components. On the right side is a set of a checkbox buttons, one
for each system color. When you select a checkbox button for a sy stem color, those pans of lhe
fake components that use that system color will start to blink. See Figure 340.
The fake desktop container contains all of the fake components. It implements double-
buffering in order to eliminate the Hashing that would otherwise occur as all of the fake com-
ponents are updated.
This example uses many different source files to implement the various fake components.
Showing all of lhe files here would be make the listing too long and unwieldy, so instead, we
scattered lhe fake component source files among the various system color descriptions. Only
lhe Main, java source file is shown here. The fake component source files are located in the
following system color field descriptions:
• FakeTitleBar. java is located in activeCaption
• FakeWindow. java is located in activeCaptionBorder
• FakeMenuBar. j ava is located in menu
• FakeLi st. java is located in text
• FakeButton. j ava is located in control
• FakeScrollbar. java is located in scrolIbar
java.awt
SystemColo
. SystemColor Example
C desMop C activeCaption
С a c ti ve C a pti о nT eM C active С а р t i о п В о rd е г
Inactive Window
С inactive'Caption
С । n a ct;ve С a pti о п В о rd е г
С windows order
С menu
С te.4
С textHigh light
С teMlnactiveTeM
С i ontrulTeM
С с ontrolLtHighlight
C iontrolC'kShadO'w
(• 'info.
C mactiveCaptionText
C window
C windowText
C menuText
C teMText
C teMHighlightText
C control
C controlHighlight
C controlshadow
C scrollbar
C infoText
I IGl RE 340: Component System Colors.
import java, awt. *;
import java.awt.event. ;
class Main extends Frame implements Runnable {
FakeDesktop desktop = new FakeDesktopO;
Mainf) {
super(“SystemColor Example”):
// Set up first window.
FakeWindow w = new FakeWindow(
SystemColor.WINDOW, SystemColor.WINDOW-TEXT, true):
w.setBounds(40, 40, 200, 100);
desktop.add(w);
// Set up second window.
w = new FakeWindowf
SystemColor.WINDOW, SystemColor.WINDOW-TEXT, false);
w.setBounds(20, 10, 200, 100);
desktop.add(w);
// Set up first button.
FakeButton b = new FakeButton(true);
b.setBounds(20. 150. 80. 25;;
desktop.addfb);
// Set up second button.
b = new FakeButton(false;;
b.setBounds(20. 185, 80, 25;;
desktop.addfb);
// Set up list.
FakeList 1 = new FakeListf);
SystemColor
java awt
I.setBounds(140, 150, 100, 70);
desktop.add(l);
// Set up the desktop.
add(desktop, BorderL ayout.CENTER);
// Set up control panel.
add(new ControlPanel(this)f BorderLayout.EAST);
setSize(590, 260);
// Show the whole thing.
show() ;
// Start the blinking thread.
(new Thread(this)). startO ;
}
static Color[] colors = {
SystemColor.desktop, SystemColor.activeCaption,
SystemColor.activeCaptionText, SystemColor.activeCaptionBorder,
SystemColor.inactiveCaption, SystemColor.inactiveCaptionText,
SystemColor.inactiveCaptionBorder, SystemColor.window,
SystemColor.windowBorder, SystemColor.windowText,
SystemColor.menu, SystemColor.menuText,
SystemColor.textf SystemColor,textText,
SystemColor.textHighli ght t SystemColor.text Hi ghli ghtText,
SystemColor.textlnactiveText, SystemColor.control,
SystemColor.controllext, SystemColor.controlHighlight,
SystemColor.controlLtHighlight, SystemColor.control Shadow,
SystemColor.controlDkShadow, SystemColor.scrollbar,
SystemColor.info, SystemColor.infoText,
};
int curColor;
void setCur(.olor(i nt c) {
curColor - c;
}
public void run() {
Colorf] savedColors = (Color)colors.cloneO ;
boolean on = false;
int c = curColor;
while (true) {
// curColor changed so restore it before
// blinking new color,
if (c !- curColor) {
colors[c] = savedColors[c];
c = curColor;
}
try {
if (on) {
colorsLc] = savedColors[c];
} else {
colorsfcj - Color.red;
}
on = !on;
repai ntAl1(desktop);
Thread.sleep(500);
1386
java.awt
SystemColot
} catch (Exception e) {
}
}
}
public void update(Graphics g) {
super.pai nt(g);
}
public void repaintAll(Component c) {
if (c instanceof Container) {
Container cont = (Container)c;
ComponentLJ children - cont.getComponentsO;
for (int i^0; i<chiIdren.length; i + *) {
repai ntAll(chiIdren[iJ);
}
}
c.repaint();
}
public static void mai n(String [J args) {
new Mai n();
}
}
class FakeDesktop extends Container {
FakeDesktopO {
setLayout(nul1);
// listen for events.
addMouseListener(new MouseEventHandler());
addMouseMotionListener(new MouseMotionEventHandlerO);
}
public void paint(Graphics g) {
update(g);
}
Image bbuf;
Graphics bbufG;
public void update(Graphics g) {
FontMetrics fm ~ g.getFontMetrics();
int w = getSizeO .width;
int h = getSizeO .height;
if (bbuf -= null
II bbuf.getWidth(null) < w
Il bbuf.getHeight(nul1) < h) {
bbuf = createlmage(w, h);
bbufG = bbuf.getGraphicsO;
}
bbufG.setColor(Main.colors[SystemColor.DESKTOP]);
bbufG.fi1lRect(0, 0, w, h);
bbufG.clipRect(0, 0, w, h);
// Paint all of the lightweight’s children.
super.paint(bbufG);
// Paint Info-tag.
SystemColor
java.awt
if (mousePt null) {
w = fm.stringwidth("Info tag”)*4;
h = fm.getHeight()+4;
// Paint Info-tag background color.
bbufG.setColor(Mai n.colors[SystemColor.INFO1);
bbufG.fi1!Rect(mousePt.x, mousePt.y, w, h);
// Paint Info-tag text.
bbufG.setColor(Mai n.colors[SystemColor.INFO-ГЕХТ]);
bbufG. drawStri ngC'Info-tag'1,
mousePt. x+2, mousePt. у+2+fm.get AscentO) ;
bbufG.drawRect(mousePt.x, mousePt.y, w-1, h-1);
g.drawlmage(bbuf, 0, 0, this);
}
// If non null, holds current location of mouse
Point mousePt;
class MouseEventHandler extends MouseAdapter {
public void mouseFxited(MouseEvent evt) {
mousePt - nul1;
repaint();
}
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
mousePt evt,getPoint();
repai nt();
}
}
}
class Controlpanel extends Panel implements ItemListener {
CheckboxGroup cbg = new CheckboxGroupO ;
Main frame;
Control Pane 1(Main f) {
frame = f;
set!ayout(new GridLayout(0, 2));
for (int i=0; i <SystemColor.NUM-COLORS; i <+) {
Checkbox cb = new Checkbox(colorNames[i], i==0. cbg);
cb.setName(““+i);
cb.addltemLi stener(thi s);
add(cb);
}
}
public void itemStateChanged(ItemEvent evt) {
frame.setCurColor(
Integer.parselnt(cbg.getSelectedCheckbox().getNameO));
}
static String[] colorNames = {
“desktop”, “activeCaption”,
1388
SystemColo:
activeCaptio
java.awt
“acti veCaptionlext”, “act iveCaptionBorder",
“inactiveCaption”, “inactiveCaptionText”,
"inactiveCaptionBorder”, “window”,
“wi ndowBorder", “windowText”,
“menu”, “menuText”,
“text”, "textfext”,
“textHighlight”, “textHighlightText”,
“textInactiveText”, “control”,
“controlText", "controlHigh Ii ght”,
"controlL tHighlight", “controlShadow”,
“controlDkShadow”, “scrolIbar”,
“info”, "infoText”,
};
}
activeCaption
PCRPOSi- The background color for the title bar of an active window.
syntax public final static SystemColor activeCaption
description If a component has an area that lhe user can grab with the mouse in order to
drag the component (e.g., a title bar), this color is typically used to color the
area when the window is active.
The default value for activeCaption is
0XFF00008 // activeCaption = new Color(0,0,128);
hxa.mpi.e This class implements a fake title bar for a window. It uses the various caption
system colors to paint the different parts of the title bar. See the class example
to see how this class is used.
import java.awt.*;
class FakeTitleBar extends Component {
boolean active;
FakeTitleBar(boolean active) {
this.active - active;
}
public Dimension getPreferredSizeO {
return new Dimension(Math.max(l, getSize().width), 20);
public void paint(Craphics g) {
FontMetrics fm = g.getFontMetrics();
int w - getSize().width;
int h - getSize()height;
if (active) {
// Paint caption background.
g.setColor(Mai n.colors[SystemColor.ACTIVE-CAPTION]);
SystemColor
act i veCapt ion В оrder
jaxa.awt
g.fi1lRect(0, 0, w, h);
// Paint window title.
g. setColor(Mai n. colors [SystemColor. ACTIVE,_CAPTION_TEXT^);
g.drawString(“Active Window”,
(h fm. getHei ghtO )/2 ,
(h-fm.getHeight())/2+fm.getAscentO);
} else {
// Paint caption background.
g.setColor(Main.colors[SystemColor.INAC1IVE_CAPTION]);
g.fi11Rect(0, 0, w, h);
// Paint window title.
g.setColor(Main.colors[SystemColor. 1NACTIVE_CAPTION_TI-XT]) ;
g.drawString(“Inactive Window”,
(h-fm.getHeight())/2,
(h fm.getHeightO)/2+fm.getAscentO) ;
activeCaption Border
Pl’RPC )SE The border color of an active window.
S> M AX public final static SystemColor activeCaptionBorder
DESCRIPTION Lhe border of a window consists of pixels along the perimeter of the window. A window may have two borders: an active border, which changes color depending on whether the window is active, and a regular window border, which does not change color, activeCaptionBorder is the color of lhe active border w hen the window is active. The default value for acti veCapti onBorder is 0xFFC0C0C0 // activeCaptionBorder = Color,lightCray;
EXAMPLE This class implements a fake window. It uses the various window border and background system colors to paint the different parts of the window. The w in- dow also uses a fake title bar and fake menu bar. See the class example lo see how this class is used.
import java.awt.';
class FakeWindow extends Container {
int bgColor;
int textColor;
boolean active;
FakeScrol1 bar scrollbar - new FakeScrol1bar();
FakeWindowHeader header;
FakeWindowOnt bgColor, int textColor, boolean active) {
this.bgColor = bgColor;
1390
SystemColor
activeCaption Border
java.awt
this.textColor -= textColor;
this.active = active;
setLayoutfnew BorderLayout());
add(scrolIbar, BorderLayout.EAST);
header = new FakeWindowHeader(active);
add(header, BorderLayout.NORTH);
}
public Insets getlnsetsO {
return new Insets(4, 4, 4, 4);
}
public void paint(Craphics g) {
FontMetrics fm - g.getFontMetrics();
int w = getSize().width;
int h = getSizeO .height;
// Paint window background color.
g.setColor(Mai n.colors[bgColor]);
g.fi1lRect(0, 0, w, h);
if (active) {
// Paint active window border.
g.setColо r(Mai n.col о rs Г SystemColor.ACTIVE.CAPTION „BORDER]);
} else {
// Paint inactive window border.
g. setCol or (Mai n. colors [SystemColor. INAC1IVE.„CAP1 ION_BORDFR] ) ;
}
g.drawRect(0, 0, w-1, h-1);
g.drawRect(l, 1, w-2, h-2);
// Paint window border.
g.setColor(Mai n.colors[SystemColor.WINDOW-BORDER]);
g.drawRect(2, 2, w 5, h-5);
g.drawRect(3, 3, w-7, h-7);
// Paint text color
g.setColor(Mai n.colors[textColor]);
g.drawString("Window Text”, 40, 70);
// Needed to paint lightweight container’s children,
super.paint(g);
}
}
class FakeWindowHeader extends Container {
FakeWindowHeader(boolean active) {
setLayout(new CridLayout(0, 1));
add(new FakeTitleBar(active));
add(new FakeMenuBarQ);
SystemColor
actheCaptioiiTexi
java.awt
activeCaptionText
Pi’RPOSE The color of text in the title bar of an active window.
A syntax public final static SystemColor activeCaptionText description If a component has an area that the user can grab with the mouse in order to
В drag the component (e.g.. a title bar), this color is used to paint any text that
C appears in that area when the window is active.
D The default value for activeCaptionText is 0xFrFFFFFF // activeCaptionText = Color.white;
Г* F example See activeCaption,
control
If ’ —
1 pi rposl The background color of a component.
J syntax public final static SystemColor control
К description This color is used to paint the background of a component. The outline of the
L component is painted with four other system colors. See the class description for details.
M N The default value for control is 0xEEC0C0C0 // control = Color.1ightGray;
0 example This class implements a fake button. It uses the various component system col- ors to paint the different parts of the button. See the class example to see how
P this class is used.
Q import java.awt.-:
R import java.awt.event.; class FakeButton extends Component { boolean up;
T U FakeButtonCboolean up) { thi s,up = up;
V // Listen for mouse clicks. addMouseLi stener(new MouseEventHandler());
w }
X public void paint(Graphics g) { FontMetrics fm - g.getFontMetrics();
Y Z int w - getSize().width; int h - getSize().height; String label = up ? ?llp Button" : "Down Button"; // Paint control background. g.setColor(Mai n.colors TSystemColor.CONTROL]);
1392
SystemColor
control
java.awi
g.fi11Rect(0, 0, w, h);
// Paint 3D outline.
draw3D0utline(g, up, w, h) ;
// Adjust the position of the text.
//
int adjust = up ? -1 ; 0;
// Paint component text.
g.setColor(Mai n.colors[SystemColor.CONTROL-TEXT]);
g.drawString(label, adjust+(w-fm.stringWidth(label))/2,
adjust+(h-fm.getHeight())/2 + fm.getAscentO);
}
// Paint a 3D outline using the system colors.
public void draw3D0utline(Graphics g, boolean up, int w, int h) {
Color cl Main.colors[SystemColor.CONTROL_LT_HIGHLIGHT];
Color c2 = Main.col ors[SystemColor.CONTROL-HIGHLIGHT];
Color c3 = Main.colors[SystemColor.CONTROL-SHADOW];
Color c4 - Main.colors[SystemColor,CONTROL„DK_SHADOW];
if (lup) {
Cl = Main.colors[SystemColor.CONTROL_DK_SHADOW];
c2 = Main.colors[SystemColor.CONTROL-SHADOW];
c3 = Main.colors[SystemColor.CONTROL_LT„HIGHLIGHT];
c4 = Main.colors[SystemColor.CONTROL-HIGHLIGHT];
}
// Paint outer left and top edge.
g.setColor(cl);
g.drawLine(0, 0, w-1, 0);
g.drawLine(0, 0, 0, h-1);
// Paint inner left and top edge.
g.setColor(c2);
g.drawLine(l, 1, w-2, 1);
g.drawLine(l, 1, 1, h-2);
// Paint inner shadow right and bottom edge.
g.setColor(c3);
g.drawLine(w-2, h-2, w-2, 1);
g .drawLine(w-2t h-2t 1, h-2);
// Paint outter shadow right and bottom edge.
g.setColor(c4);
g.drawl ine(w-I, h-1, w-1, 0);
g.drawLine(w-l, h-1, 0, h 1);
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
up - ‘up;
repai nt();
1
SystemColor java.awt
control DkShadow
controlDkShadow
PURPOSE The darkest color of a 3D component’s outline.
SYNTAX public final static SystemColor controlDkShadow
DESCRIPTION This is one of the lour colors used to paint a component’s outline. Sec the class description for more information. The default value for controlDkShadow is 0xFF000000 // controlDkShadow = Color,black;
EXAMPLE See control.
controlHighlight
Pl RPOSI; The second brightest color of a 3D component's outline.
SYNTAX public final static SystemColor controlHighlight
DESCRIPTION This is one of the four colors used to paint a component's outline. See the class description for more information. The default value for controlHighlight is OxFFFFFFFF // controlHighlight = Color.white;
EXAMPLE See control.
controlLtHighlight
PURPOSE. The brightest color of a 3D component's outline.
SYNTAX public final static SystemColor controlLtHighlight
DESCRIPTION This is one of the four colors used to paint a component’s outline. See the class description for more information. The default value for control LtHi ghl i ght is 0xFFE0E0E0 // controlLtHighlight = new Color(224f224,224);
EXAMPLE See control.
controlshadow
PURPOSE The second darkest color of a 3D component's outline.
SYNTAX public final static SystemColor control Shadow
1394
SystemColor java.awt
inactiveCaption
OVERRIDES Color.getRCBC).
EXAMPLE See the Color class example.
inactiveCaption
PURPOSE The background color for the title bar of an inactive window.
SYNTAX public final static SystemColor inactiveCaption
DESCRIPTION If a component has an area that the user can grab with the mouse in order to drag the component (e.g., a title bar), this color is typically used to color the area when the window is inactive. The default value for inactiveCaption is 0xTF808080 // inactiveCaption = Color.gray;
EXAMPLE See activeCaption.
inactiveCaptionBorder
PURPOSE The border color of an inactive window.
SYNTAX public final static SystemColor inactiveCaptionBorder
DESCRIPTION The border of a window consists of pixels along the perimeter of the window. A window' may have two borders: an active border, which changes color depending whether the window is active, and a regular window border, which does not change color. inactiveCaptionBorder is the color of lhe active border w hen lhe window is inactive. The default value for inactiveCaptionBorder is 0ХГГС0С0С0 // InactiveCaptionBorder = Color.1ightGray;
EXAMPLE See acti veCapti onBorder.
inactiveCaption Text
PURPOSE The color of text in the title bar of an inactive window.
SYNTAX public final static SystemColor inactiveCaptionText
DESCRIPTION If a component has an area that the user can grab with the mouse in order to drag the component (e.g., a title bar), this color is used to paint any text that appears in that area when the window is inactive. The default color for inactiveCaptionText is 0xFFC0C0C0 // inactiveCaptionText = Color.1ightGray;
example: See activeCaption.
1396
java.awt _ ______ System Coh
controlTe
DESCRIPTION This is one of the four colors used io paint a component's outline. See the class description for more information. The default value for cont rol Shadow is 0xFF808080 // control Shadow = Color,gray;
F-XAMPLI: See control.
controlText
PURPOSE The color of text in a component's label.
SYNTAX public final static SystemColor controlText
description When a component is enabled, this color is used to paint the label. When a component is disabled, the color of the text should be textlnacti veText. The default value for controlText is 0xFF000000 // controlText = Color.black;
EXAMPLE See control.
desktop
PURPOSE I’he background color of the window system desktop.
SYNTAX public final static SystemColor desktop
DESCRIPTION This color is typically used by a top-level window when it wants to make it appear that the desktop is “showing through*' parts of (he window. However, some platforms allow the background to be painted with an image, and in this case, the desktop color will not be accurate. I’he default value of desktop is 0xFF005C5C // desktop = new Color(0,92,92);
EXAMPLE See the class example
getRGBQ
PURPOSE Retrieves the RGB value of this system color.
SYNTAX publ ic int getRGBO
DESCRIPTION This method is used to compare for equality this system color with a Color instance that is not a SystemColor instance.
RETURNS T he 24-bit RGB representation of this system color
java.awt
SystemColor
info
info
Pl RPOSE The background color of an info-tag.
SYNTAX public final static SystemColor info
DESCRIPTION An info-tag is a small window that displays a short description of a visible object. It is typically displayed near the cursor when you roll over the object. This is the background color of info-tag windows. The default value for info is 0xFFE0E000 // info = new Color(224,224,0);
EXAMPLE See acti veCaptionBorder.
infoText
PL RPOSE The color of text in an info-tag.
SYNTAX public final static SystemColor infoText
DESCRIPTION An info-tag is a small window that displays a short description of a visible object. It is typically displayed near lhe cursor when you roll over the object. This is the color of the text in info-tag windows. The default value for infoText is 0xFF000000 // infoText = Color.black;
EX/AMPLE See activeCaptionBorder.
menu
PURPOSE The background color of a menu component.
SYNTAX public final static SystemColor menu
DESCRIPTION This is the background color of menu components such as menu bars (see MenuBar), popup menus (see PopupMenu), and menu items (see Menuitem). The default value for menu is 0xFFC0C0C0 // menu = Color.1ightGray;
EXAMPLE This class implements a fake menu bar. It uses the various menu system colors to paint the different parts of the menubar. See the class example to see how this class is used.
import java.awt.*;
import java.awt.event.*;
class FakeMenuBar extends Component {
SystemColor
menuText
java.awt
public void paint(Graphics g) {
} } FontMetrics fm - g.getFontMetrics(); int w = getSize().width; int h = getSize().height; // Paint menu background. g.setColor(Main.colors[SystemColor.MENU]); g.fillRect(0, 0, w, h); // Paint menu text. int x = (h fm.getHeight())/2; g.setCol or(Mai n.colors[SystemColor.MENU JEX1]); g.drawString("Menu”, x, (h-fm.getHeight())/2+fm.getAscent()); x +- fm. stringWidth(“Menu '*); g.setColо r(Mai n.col оrs[Sys temColor.TEXT_INACTIVE_TEXT]); g.drawString("Inactive”, x, (h-fm.getHeight())/2+fm.getAscentO);
menuText
PURPOSE The color of text in a menu component.
SYNTAX public final static SystemColor menuText
DESCRIPTION This color should be used for painting the text in menu components such as menu bars (see MenuBar), popup menus (see PopupMenu). and menu items (see Menuitem). The default value for menuText is 0xFF000000 // menuText = Color.bl ack;
EXAMPLE See menu.
scrollbar
PURPOSE The background color of a scrollbar.
SYNTAX public final static SystemColor scrollbar
DESCRIPTION This color is used to paint the background of adjustable objects such as scroll- bars (see Scroll bar) and sliders. The default value for scroll bar is 0XFFE0E0E0 // scrollbar = new Color(224,224,224);
FXAMPLF This class implements a fake scrollbar. It uses the various scrollbar and com- ponent system colors to paint the different parts of the scrollbar. See the class example to see how this class is used.
1398
java.awt SystemColor
scrollbar
import java.awt.*;
import java.awt.event.*;
class FakeScrolIbar extends Component {
public void paint(Graphics g) {
int w - getSizeO-width;
int h =- getSize().height;
g.setColor(Main.colors[SystemColor.SCROt LBAR]);
g.fi11Rect(0, 0. w, h);
draw3D0utIine(g, false, 0, 0, w, h);
draw3D0utline(g, true, 2, 2, w 4, w 4);
draw3D0utline(g, true, 2, hw+2t w-4, w-4);
}
public Dimension getPreferredSizeO {
return new Dimension(18, Math.max(l, getSizeO .height));
}
// Paint a 3D outline using the system colors.
public void draw3D0utline(Graphics g, boolean up,
int x, int y, int w, int h) {
Color cl = Main,colors[SystemColor.CONTROL-LT_HIGHl IGHT];
Color c2 == Main, colors [SystemColor. CONTROL .HIGHLIGHT] ;
Color c3 =? Main.colors[SystemColor.CONTROL_SHADOW];
Color c4 = Main.colors[SystemColor.CONTROL_DK_SHADOW];
if Oup) {
cl - Main.colors[SystemColor.CONTROL.DK.SHADOW];
c2 ~ Main.colors[SystemColor.CONTROL.SHADOW];
c3 = Main.colors[SystemColor.CONTROL_LT_HIGHLIGHT];
c4 = Main.colors[SystemColor.CONTROL-HIGHLIGHT];
}
// Paint outer left and top edge.
g.setColor(cl);
g.drawLine(x, y, x+w 1, y);
g.drawLine(x, y, x, y+h-1);
// Paint inner left and top edge.
g.setColor(c2);
g.drawLine(x+l, y+1, x+w-2, y+1);
g.drawLine(x+l, y+1, x+1, y+h-2);
// Paint inner shadow right and bottom edge.
g.setColor(c3);
g.drawLine(x+w-2, y+h-2, x+w-2, y-i-1);
g.drawl ine(x+w 2, y-i-h-2, x+1, y+h-2);
// Paint outer shadow right and bottom edge.
g.setColor(c4);
g.drawLine(x+w-l, y+h-1, x+w-1, y):
g.drawLine(x+w-1, y+h-1, x, yi-h-1) ;
SystemColor
text
java.awt
g.setColor(Mai n.colors[SystemColor.TEXT]);
g.fi1lRect(0, 4+i*fm.getHeight(), w, fm.getHeightO);
g.setColor(Main.colors[SystemColor.TEXT-TEXT]);
}
// Paint item label.
// The 4 is to adjust for the border.
g.drawStri ng(i tem, 4+(h - fm. getHeight())/2 ,
4+i* fir. getHei ght () fm.getAscentO) ;
}
}
// Paint a 3D outline using the system colors.
public void draw3D0utline(Graphics g, boolean up,
int x, int y, int w, int h) {
Color cl = Main.colors[SystemColor.CONTROL J_T_HIGHLIGHT];
Color c2 = Main, colors[SystemColor.CONTROL__HICHLICHT] ;
Color c3 = Main.colors[SystemColor.CONTROL-SHADOW];
Color c4 = Main.colors[SystemColor.CONIROL-DK_SHADOWj;
if ( ! up) {
cl = Main.colors[SystemColor.CONTROL_DK_SHADOW];
c2 = Main.colors[SystemColor.CONTROL-SHADOW];
c3 = Main.colors[SystemColor.CONTROL_LT_HIGHLIGHT];
c4 = Main.colors[SystemColor.CONTROL .HIGHLIGHT];
}
// Paint outer left and top edge.
g.setColor(cl);
g.drawLine(x, y, x+w-1, y);
g.drawl ine(x, y, x, y+h-1);
// Paint inner left and top edge.
g.setColor(c2);
g.drawLine(x+l, y+1, x+w-2, ytl);
g.drawLine(x+l, y+1, x-1, y+h-2);
// Paint inner shadow right and bottom edge.
g.setColor(c3);
g.drawline(x*w-2, y+h-2, x-h/v-2, y+1);
g.drawLine(x+w-2, y+h-2, x+1, y+h-2);
// Paint outer shadow right and bottom edge.
g.setColor(c4);
g.drawLine(x+w-l, y+h-1, x*w-l, y);
g.drawLinefx+w-1, y*-h-l, x, y+h-1) ;
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
if (fm null) {
// The 4 is to adjust for the border pixels.
curltem = (evt.getY()-4)/fm.getHeight();
repai nt();
1
SystemColor
text
java.awt
text
A
В
c
D
E
Г
G
H
I
J
К
L
M
N
О
P
Q
R
T
Г
V
w
X
Y
Z
pi rposi-. The background color of text components.
syntax public final static SystemColor text
descripт ion This color should be used for painting the background of components that have
selectable text, such as a text field (see TextField) and a list (see I i st).
The default value for text is
0xFFC0C0C0 // text - Color.IightGray;
example This class implements a fake list. It uses the various text and component sys-
tem colors to paint the list border and items in the list. See the class example to
see how this class is used.
import java.awt.*';
import java.awt.event.*;
class FakeList extends Component {
FontMetrics fm;
int curltem;
FakeListQ {
// Listen for mouse clicks.
addMouset i stener(new MousetventHandlerO);
}
public void paint(Graphics g) {
int w = getSize().width;
int h = getSizeO .height;
if (fm -- null) {
fm = g.getFontMetrics();
}
// Paint control background.
g.setColor(Mai n.colors[SystemColor.CONTROL]);
g.fi1IRect(0, 0, w, h);
// Paint 3D outline.
draw3D0utline(g, true, 0, 0T w, h);
draw3D0utline(g, false, 2, 2, w-4, h-4);
// Don’t paint over the borders.
g.setClip(4, 4, w-8t h-8);
for (int i-0; i<=h/fm.getHeightО; i++) {
String item = '‘item “+i;
if (i curltem) {
// Paint the select item background.
g.setColor(Mai n.colors[SystemColor.rFXT_HIGHLIGHT]);
g.fi11Rect(0, 4+i*fm.getHeight(), w, fm.getHeight());
g.setColor(Mai n.colors[SystemColor.TEXT_HIGHLICHT_TEXTJ);
} else {
// Paint the select item background.
1400
SystemColor
textHighlight
java.awt
textHighlight
P( ’RPOSE The background color of highlighted text.
SYNTAX public final static SystemColor textHighlight
DESCRIPTION This color should be used for painting the background of selected tex’ in com- ponents that have selectable text, such as a text field (see TextField) or a list (see List). The default value for textHighlight is 0xFF000080 // textHighlight - new Color(0,0,128);
EX AMPLE See text.
textHighlightText
Pt RPOSE The color of highlighted text.
SYNTAX public final static SystemColor textHighlightText
DESCRIИ ION This color should be used for painting selected text in components that have selectable text, such as a text field (see TextField) or a list (see List). The default value for textHighlightText is 0xFFFFFFFF // textHighlightText = Color.white;
EXAMPLE See text.
textlnactiveText
Pl RPOSE The color of inactive text.
SYNTAX public final static SystemColor textlnactiveText
DLS('RIPTt(>\ When a component or item is disabled so that it cannot be activated or selected, the color of lhe text should be painted in this color. In the case of a component, lhe background color should be control; for an item, the back- ground color should be text. The default value for textlnactiveText is 0xFF808080 // textlnactiveText = Color.gray;
EXAMPLE See menu.
1402
textTc
textText
PURPOSE The color of text in a text component.
SYNTAX public final static SystemColor textText
DESCRIPTION This color should be used for painting the text in components that have select- able text. such as a text field (see TextField) and a list (see List). The default value for textText is 0xFF000000 // textText = Color.black;
EXAMPLE See text.
toStringt) — .
PURPOSE Generates the siring representation of this system color.
SYNTAX public String toStringO
DESCRIPTION Fhe string representation of a system color consists of the color's class name and its index position in the system color cache. Table 24 shows the index positions of lhe system color values in the system color cache. This method is typically used for debugging purposes.
0 DESKTOP 14 TEXT_HIGHTLIGHT
1 ACT1VE_CAPTION . 15 TEXT-HIGHLIGHT.TEXT
2 ACTIVE.. CAPTION-TEXT 16 TEXT_INACTIVE_TEXT
3 ACTIVE.CAPTION_BORDER 17 CONTROL
4 INACTIVE-CAPTION 18 CONTROL-TEXT
5 INACTIVE_CA P TION_TEXT 19 CONTROL-HIGHLIGHT
6 INACTIVE-CAPTION-BORDLR 20 CONTROL-LI.HIGHLIGHT
7 WINDOW 21 CONTRO1.SHADOW
8 WINDOW_BORDLR . 22 CONTROL-DK-SHAOOW
9 WINDOW-TEXT 23 SCROLLBAR
10 MENU 24 INFO
11 MENU-TEXT : 25 INFO_TEXT
12 TEXT 14 TEXT-HIGHT1 IGH1
13 TEXT-TEXT
TABLE 24: Index Positions of System Colors Values in the System Color Cache.
returns The non-nul 1 string representation of this system color.
overrides Color. toStr i ngO-
example See java.lang.Object.toStringО.
java.awt
SystemColor
window
window
PL RPOSI: The background color of a window.
SYNTAX public final static SystemColor window
DESCRIPTION Unless a window's background color has been explicitly set using Compo- nent. setBackgroundO, the window's background should be painted in this color. The default value for window is ©xFFFFFFFF // window == Color.white;
EXAMPLE See acti veCaptionBorder.
windowBorder
PURPOSE I he border color of a window.
SYNTAX public final static SystemColor windowBorder
DESCRIPTION I'he border of a window consists of pixels along the perimeter of the window. A window' may have two borders: an active border, which changes color depending whether the window is active, and a regular window border, which does not change color, wi ndowBorder is the color of the regular window bor- der. The default value for wi ndowBorder is 0xFF000000 // windowBorder « Color.black;
EXAMPLE See activeCaptionBorder.
windowText
PURPOSE The color of text in a w indow.
SYNTAX public final static SystemColor windowText
DESCRIPTION Unless the foreground color of a window has been explicitly set using Compo- nent . setForegroundO, text painted in a window should be painted in this color. The default value for wi ndowText is 0xFF000000 // windowText = Color.bl ack;
EXAMPLE See activeCaptionBorder.
1404
java.awt
TextArea
Syntax
public class TextArea extends TextComponent
Description
The tex? area is a text component that displays editable
text. The text area is similar lo the text field compo-
nent, except that the text area can display multiple lines
and has vertical and horizontal scrollbars.
The text area component is typically used for
entering text messages or comments to a program and
for displaying text output from a program.
Figure 341 shows an example of text area.
FIGURE 341: TextArea.
Preferred Number of Rows and Columns and Preferred Size
A text area can be created with a preferred number of rows and columns that determines the
preferred size of the component. The preferred size is based on the average size of a character,
which is a platform-dependent value. Tile preferred number of rows and columns can be
changed at any time using setRowsO and setColumnsO Calling these methods causes the
text area's preferred size to be recalculated.
The preferred number of rows and columns in a text area does not limit the number of
characters or lines that can be entered. Also, resizing lhe text area does not change its preferred
number of rows or columns. A text area can be resized to be larger or smaller than its preferred
number of rows and columns.
Scrollbars and IJne-wrapping
A text area can be created with either a horizontal scrollbar, a vertical scrollbar, or both.
If the horizontal scrollbar is absent, the text area is set in line-wrapping mode. This means
that any line that is longer than the width of the text area is automatically broken into multiple
lines, each line wide enough to fil within the text area's width. However, the line breaks are not
permanent; if the text area was made wide enough, these lines would be displayed unbroken
Л
В
C
D
E
E
G
H
I
J
К
L
M
N
О
P
Q
R
S
U
V
w
X
Y
Z
TextArea
java.awt
again. Line breaking is strictly a visual effect and does not affect the update methods in any
way. That is, although the number of visual lines may have increased, the number of true lines
in the text area has not changed. In fact, it is not possible for a program to tell whether a line is
broken.
A If the horizontal scrolIbar is present, long lines are never broken. You can use the horizon-
lai scrollbar to see different parts of a long line.
The presence of a vertical scrollbar allows you to move up and down a long document by
f using the scrollbar. However, regardless of whether a vertical scrollbar is present, you can still
p move up and down the text area by using lhe UpArrow and DownArrovv keys.
Note: In Java 1.1, there is no way to obtain a handle on the text area's scrollbars.
P Newlines
The text of a text area can consists of multiple lines. Each line is separated by a single newline
character (\n). This is true for all platforms, even when the platform may internally use other
H representations for newlines (such as \n\r).
Events
J Л text area fires the events fired by a text component. See TextComponent for details.
к
L
MEMBER SUMMARY T 1
Constructor FextAreaQ Constructs a new TextArea instance.
Scroll bar Method and Constants getScrol1 barVisibili ty() SCROLLBARS—BOTH SCROLLBARS HORIZONTAL-ONLY ' SCROLLBARS-VERIICAL_0NLY I SCR01LBARS.NONE Retrieves which scroll bins are displayed tor this text area. Display both vertical and horizontal scrollbars. Display only the horizontal scrollbar. Display only the vertical scrollbar. Display no scrollbar.
Row and Column Methods 1 getColumnsO | getRows() setColumnsO setRows() Retrieves the preferred number of columns in this text area. Retrieves the preferred number of rows in this text area. ; Sets the number of columns in this text area. Sets the number of row s in this text area.
1 .ayout Methods getMi n i mumSi ze() getPreferredSize() Calculates the minimum dimensions of this text area. Calculates the preferred dimensions of this text area
1406
MEMBER SUMMARY 4^
Text Update Methods append О insertO replaceRangeO Appends a string to this text area. Inserts a string in this text area. j Replaces a range oi characters in this text area with another range of characters.
Peer Method addNoti fyO Creates the text area’s peer. ’
Debugging Method paramStringO Generates a string representing the text area's state.
Deprecated Methods appendTextO insertTextO mi nimumSizeO preferredSizeO 1 replaceTextO i - .. 1 Replaced by append О. Replaced by insertO. Replaced by getMinimumSize(). Replaced by getPreferredSizeO. । Replaced by replaceRangeO,
Example
This example creates a text area and displays it in a frame. See Figure 341 for a screen shot of
the example.
import java.awt.*;
class Main extends Frame {
TextArea ta *= new TextArea(l, 1);
MainO {
super(“TextArea Example’);
add(ta, BorderLayout.CENTER);
pack();
show() ;
}
static public void main(String[] args) {
new MainO ;
?
TextArea
java.awt
addNotify()
addNotifyO
PURPOSE Creates this text area's peer.
SYNTAX public void addNotifyO
A DESCRIPTION This method creates the text area's peer if it does not yet exist. The text area's
В peer is created by calling the Tool ki t. createTextAreaQ method. This
C method should never be called directly. It is normally called b\ the text area's
D parent.
E OVERRIDES Component.addNoti fy().
SEE ALSO Component, Toolkit.
E EXAMPLE Component.show().
G H I appendO
PURPOSE
SYNTAX
DESCRIPTION
PARAMETERS
text
SEE ALSO
EXAMPLE
Appends a string to this text area.
public synchronized void append(String text)
This method appends the siring text to (he end of the (ext area.
The non-null string to be Appended
insertO, replaceRange().
This example creates a frame con-
taining a text area and a text field.
The text typed in the (ext field is
appended to the text area when you
press Return. See Figure 342.
append!ext Example
This text has been appended. JJ
Here's some text about to be appended
FIGURE 342: Appending Text to a
TextArea.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ActionListener {
TextField tf = new TextFieldO;
TextArea ta = new TextAreaO;
MainO {
super(“append Example”);
ta.setEdi table(fal se);
addfta, BorderLayout.CENTER);
addftf, BorderLayout.SOUTH);
// Add listener for text field
1408
tf.addActionListener(this);
pack О:
show();
public void actionPerformed(ActionEvent evt) {
ta.append(tf.getTextO + “\n’*);
tf. setText C“);
static public void main(String[] args) {
new MainO;
appendTextf)
DEPRECATED
PURPOSE Replaced by append().
SYNTAX public void appendText(String text)
PARAMETERS text The non-nul 1 string to be appended.
DEPRECATION Replace the usage of this deprecated method, as in textarea.appendText(text); with textarea.append(text) ;
getColumns()
PURPOSE
SYNTAX
DESCRIPTION
RETURNS
SEE ALSO
Retrieves the preferred number of
columns in this text area.
public int getColumnsO
The preferred number of columns
determines the text area’s preferred
width. See the class description for
details.
The preferred number of columns
in this text area.
getRows() f
getPreferredSizeO,
setColumns(), TextArea().
T extArea getColumnsO .
Some text in the text area. Is tlJ8j|
FIGURE 343: Rows and Columns of a
TextArea.
java.awt
TextArea
getColumns()
A
В
C
D
E
E
H
I
J
К
L
M
N
()
P
Q
R
S
example This example creates a text area whose tows and columns are controlled by
some buttons at the bottom of the frame. See Figure 343.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements ActionListener {
TextArea ta = new TextAreaO;
Label rows, cols;
Main() {
super(“TextArea.getColumns() Example”);
Panel p = new Panel(new GridLayout(2, 0));
rows = new Label (“Rows-” * ta. getRowsO);
p.add(rows);
Button b - new Button ("Rows -51’);
p.add(b);
b.addActionLi stener(this);
b - new Button(“Rows +5”);
p.add(b);
b.addActionLi stener(this);
cols = new Label(“Cols-” + ta.getColurrnsO);
p.add(cols);
b - new Button(‘‘Cols -51’);
p.add(b);
b.addActionListener(this);
b = new Button(“Cols +5”);
p.add(b);
b.addActi onLi stener(thi s);
add(p, BorderLayout.SOUTH);
add(ta, BorderLayout.CENTER);
pack();
show();
t;
v
w
X
Y
Z
public void actionPerformed(ActionEvent evt) {
String cmd evt.getActionCommandO;
if (cmd.equals(“Rows -5”)) {
ta.setRows(ta.getRowsO-5);
rows.setText("Rows-” + ta.getRowsO) ;
} else if (cmd.equals("Rows +5”)) {
ta.setRows(ta.getRows()+5);
rows.setText(“Rows=” 4 ta. getRowsO);
} else if (cmd.equals(“Cols -5”)) {
ta. setCol umns(ta. getColumnsO -5) ;
cols. setText(“Cols-" + ta.getColumnsO) ;
} else if (cmd.equals(“Cols 4-5”)) {
ta.setColumns(ta.getColumns()+5);
cols.setText(“Cols-” ta.getColumnsO) ;
}
}
public static void main(String[] args) {
new Main О;
}
}
1410
getMinimumSize()
PURPOSE Calculates the minimum dimensions of this text area.
SYNTAX public Dimension getMinimumSize() public Dimension getMinimumSize(int rows» int cols)
DESCRIPTION The minimum dimensions of a text area are based on the dimensions needed to display the specified number of rows and columns of characters. The size of a character depends on the text area's current font. If the text area's font has vari- able-width characters, then lhe width is based on the average size of a charac- ter and the result is an approximation. The average width of a character is a platform-dependent value. If rows and cols are not specified, they default to the current preferred number of rows and columns. if the text area’s peer is not yet created, the resulting dimensions are (0, 0). On most platforms, the minimum and preferred dimensions are the same.
PARAMETERS cols rows A non-negative integer specifying the width in characters. A non-negative integer specifying the height in character lines.
RETURNS A new non-null Dimension instance containing the minimum dimensions of the text area.
OVERRIDES Component.getMi ni mumSi ze().
SEE ALSO getColumnsO, getPreferredSize(), getRows().
EXAMPLE See the LayoutManager class example.
getPreferredSize()
PURPOSE Calculates the preferred dimensions of this text area.
SYNTAX public Dimension getPreferredSizeO public Dimension getPreferredSize(int rows, int cols)
DESCRIPTION The preferred dimensions of a text area are based on the dimensions needed to display the specified number of rows and columns of characters, l he size of a character depends on the text area's current font. If the text area's font has vari- able-width characters, the width is based on the average size of a character and the result is an approximation, l he average width of a character is a platfonn- dependent value. If rows and col s are not specified, they default to the current preferred number of rows and columns. If the text area's peer is not yet created, the resulting dimensions are (0, 0). On most platforms, lhe minimum and preferred dimensions are the same.
TextArea
java.awt
getRows()
J
К
L
M
N
О
P
Q
R
S
PARAMETERS
col s A non-negative integer specifying the width in characters.
rows A non-negative integer specifying the height in character lines.
RETURNS A new non-null Dimension instance containing the preferred dimensions of the text area.
OVERRIDES Component .getPreferredSizeO.
SEE ALSO getColumnsO, getMinimumSizeO, getRowsO.
EXAMPLE See the LayoutManager class example.
getRowsf)
PURPOSE Retrieves the number of rows in this text area.
SYNIAX public int getRowsO
DESCRIPTION The preferred number of rows determines the text area's preferred height. See the class description for details.
RETURNS The preferred number of rows in this text area.
SEE: ALSO getColumnsO, getPreferredSizeO < setRowsO, TextAreaO.
exampit: See getColumnsO.
getScrollbarVisibility ()
purpose Retrieves which scrollbars are displayed for this text area.
syntax public int getScrollbarVi sibi 1 i tyO
DESCRIPTION
U
V
X
Y
Z
SEEALSO
This method returns a constant
specifying which scrollbars are
being displayed for this text area.
This value is identical to the one
used to create the text area. One of
SCROLLBARS_BOTH,
SCROLLBARS-NONE,
SCROLL BAR S_HOR IZONTAL.ON L Y.
or SCROLLBARS_VERTICAL_ONLY.
SCROLLBARS_BOTH,
SCROLLBARS-NONE,
SCROLLBARS_HORIZONTAL_ONLY,
SCROLL BARS.VER1 ICAL_ONLY.
< getScrollbarVisibility Ex.
Both horizontal ^Horizontal only
Vertical only No horizontal or
| vertical
FIGURE 344: Scrollbars in a TextArea.
1412
^mUUJJUdl VIM IM I
ample This example creates a frame that has four text areas. The text areas are distin-
guished by (he types of scrollbars they have. Modifying the text in a text area
causes a message to be displayed indicating (he text area in which lhe change
occurred. See Figure 344.
import java.awt.*;
import java.awt.event;
class Main extends Frame implements TextListener {
Main О {
super(“getScrol1 barVisi billty Fxample”);
Panel p =
new Panel(new GridLayout(2, 2));
TextArea both * new TextArea(”Both horizontal and vertical”,
10, 10, TextArea.SCROLLBARS.BOTH);
TextArea hor = new TextAreaC'Horizontal only”,
10, 10, TextArea.SCROLLBARS J10RIZ0NTAL_ON1 Y);
TextArea ver = new TextAreaC'Vertical only”,
10, 10, TextArea.SCROLLBARS_VERF1CAL_ONLY);
TextArea none = new TextArea(“No horizontal or vertical”,
10, 10, TextArea.SCROLLBARS_NONE);
p.add(both);
p.add(hor);
p.add(ver);
p.add(none);
both.addTextListenerfthis);
hor.addTextLi stener(thi s);
ver.addTextLi stener(thi s);
none.addTextl istener(this);
add(p);
pack();
show();
}
public void textValueChanged(TextEvent evt) {
TextArea src = (TextArea)evt.getSourceO;
switch (src.getScrollbarVisibility()) {
case TextArea.SCROL I BARS.BOTH:
System.out.println(“both");
break;
case TextArea.SCROLLBARS_HORIZONTAL_ONLY:
System.out.println("horizontal only”);
break;
case TextArea.SCROLLBARS_VERTICAL_ONLY:
System.out.printl n(“vertical only”);
break;
case TextArea.SCROLLBARS-NONE:
System.out.println(“none”);
break;
}
}
static public void main(String[] args) {
new Mai n();
TextArea
java.awt
inserh)
insertO
PUR Pt )SE
SYNTAX
DESCRIPTION
PARAMETERS
pos
text
SEE ALSO
EXAMPLE
Inserts a string in this text area.
public synchronized void insert(String text, int pos)
This method inserts the string text at index pos of this text area.
The zero-based index at which to
insert the text.
The non-null text to be inserted.
appendO, replaceRangeC).
This example creates a frame contain-
ing a text area and a choice. The
choice contains a number of words
that can be inserted into the text area
when selected. See Figure 345.
FIGURE 345: Inserting Text into a
TextArea.
import java.awt.-:
import java.awt.event.-;
class Main extends Frame implements ItemListener {
String[] keywords =
{“class”, “extends”, “import”, “interface”, “synchronized"};
TextArea ta = new TextAreaQ ;
Choice c = new ChoiceQ;
Main() {
super(“insert Example”);
for (int i=0; i<keywords.1ength; i++) {
c.additem(keywords[i]);
}
add(ta, BorderLayout.CENTER);
add(c, BorderLayout.SOUTH);
// Add listener for choice
c.addltemLi stener(thi s);
pack();
show();
}
public void itemStateChanged(ItemEvent evt) {
ta. i nsert ((St ri ng)evt. getltemQ , ta. getSelecti onEndQ) ;
ta. requestFocusO ;
}
static public void mai n (St ri ng [] args) {
new Mai n();
}
}
1414
insert к
insertTextO deprecated
PURPOSE Replaced by insertO.
SYNTAX public void insertText(String text, int pos)
PARAMETERS
pos text 1Ъе zero-based index at which to insert the text. I'he non-nul 1 text to be inserted.
deprecation Replace the usage of this deprecated method, as in
textarea.insertText(text, pos); with textarea.1nsert(text, pos);
minimumSizeO deprecated
PURPOSE Replaced by getMini mumSi ze 0.
SY VI AX public Dimension minimumSizeO public Dimension minimumSize(int rows, int cols)
PARAMETERS cols A non-negative integer specifying the width in characters.
rows A non-negative integer specifying the height in character lines.
RETURNS A new' non-null Dimension instance containing the minimum dimensions of the text area.
OVERRIDES Component .mi nimumSizeO.
DEPRECATION Replace the usage of this deprecated method, as in Dimension dim = textarea.minimumSizeO ; Dimension dim2 = textarea.minimumSizeCrowsr cols); with Dimension dim = textarea.getMinimimSizeQ ; Dimension di m2 = textarea.getMinimumSize(rows, cols);
paramStringt)
PURPOSE Generates the string representing this text area's state.
SYNTAX protected String paramStringO
DESCRIPTION The string representation of a text area consists of the string representation of TextComponent, plus the text area’s preferred number of rows and columns, and which scrollbars are displayed. A subclass of this class should override this method and return a concatenation of its state with the results of
java.awt
TextArea
preferredSizet)
super.paramString(). This method is called by the toStri ng () method
and is typically used for debugging.
returns A non-null string representing the text area's state.
overrides Textcomponent. paramStri ng().
sn: also Component.toString()t java,1ang.Object.toString().
example See Component. paramStri ng().
D
preferredSize() deprecated
F Pl RPC ISE Replaced by getPreferredSize().
G SYNTAX public Dimension preferredSize()
H public Dimension preferredSize(int rows, int cols)
PARAMETERS
1 cols A non negative integer specifying the width in characters.
J rows A non-negative integer specifying the height in character lines.
К RL (URNS Л new non-null Dimension instance containing lhe preferred dimensions of
L the text area.
M (A ER RIDES Component.preferredSize().
N DEPRECATION Replace the usage of this deprecated method, as in
Dimension dim = textarea.preferredSize();
0 Dimension dim2 = textarea.preferredSize(rows, cols);
with
P Dimension dim = textarea,getPreferredSize();
Q Dimension dim2 = textarea.getPreferredSize(rows, cols);
replaceRangeC)
purpose Replaces a range of characters in this text area with another string.
symax public synchronized void replaceRangefString str, int startPos,
int endPos)
description This method replaces the text between startPos and endPos with str in this
text area. The length of the range is endPos - startPos.
PARAMETERS
endPos The zero-based end position of lhe range, l he character at end is not included
in the range.
startPos The zero-based index of the first character in the range.
str The non-null replacement string.
1416
replace Ran
silxiso appendO, insert().
exampi.i This example demon-
strates searching and
replacing text by creating a
text area and two text
fields. See Figure 346. In
one text field, you specify a
search string and in the
other, you specify a
replacement string. When
you press Return while in
either text field, the first
occurrence of the search
string after the caret in lhe
text area is replaced by the
replacement string.
import java.awt.-';
import java, awt. event . ;
Here's more|random words
Search: some
Replace: more
FIGI RE 346: Search and Replace in a TextArea.
class Main extends Frame implements ActionListener {
TextField tfSearch = new TextFieldO;
TextField tfReplace = new TextFieldO;
TextArea ta = new TextArea(10, 40);
MainQ {
super("replaceRange Example”);
Panel southPanel = new Panel(new GridLayout(2, 1));
Panel p = new Panel(new BorderLayout());
p.add(new Label(“Search:”), BorderLayout.WEST);
p.add(tfSearch, BorderLayout.CENTER);
southPanel.add(p);
p = new Panel (new BorderLayoutQ) ;
p.add(new Label("Replace:”), BorderLayout.WEST);
p.add(tfReplace, BorderLayout.CENTER);
southPanel.add(p);
add(ta, BorderLayout.CENTER);
add(southPanel, BorderLayout.SOUTH);
// Add listeners for search and replace text fields
tfRepl ace.addActi onLi stener(thi s);
tfSearch.addActi onListener(this);
pack();
show();
public void actionPerformed(ActionEvent evt) {
TextArea
java.awt
replaceTexU)
Л
В
C
D
f*
b
G
String str г- tfSearch.getTextO ;
int s « ta.getTextO -indexOf (str, ta.getSelectionStart O) ‘
if (s < 0 && ta.getSelectionStartQ > 0) {
// Let’s try from the beginning.
s - ta. getTextO . i ndexOf(str, 0);
}
if (s >" 0) {
String strRep = tfReplace.getTextO;
ta. replaceRange(strRep, s, s + str. lengthO);
ta.select(s + strRep.lengthO , s ч strRep.lengthO);
ta. requestFocusO;
}
static public void main(String[2 args) {
new MainO ;
}
replaceTexK) deprecated
purpose Replaced by replaceRangeO.
syntax public void replacefextCString str, int startPos, int endPos)
PARAMETERS
endPos The zero-based end position of the range, rhe character at end is not included
in the range.
startPos I'he о-based index of the first character in the range.
str I'he non-null replacement string.
deprecation Replace the usage of this deprecated method, as in
textarea.replaceText(str, startPos, endPos);
with
textarea.replaceRangeCstr, startPos. endPos);
SCROLLBARS_BOTH |
purpose Display both vertical and horizontal scrollbars.
SYNTAX public static final int SCROLLBARS-BO7H j
description This constant indicates that the text area is to have both horizontal and vertical 1
scrollbars. See the class description for details on a text area’s scrollbars. It is
used as a parameter to the TextAreaO constructor. Its value is 0.
seealso getScrolIbarVi sibili ty()» SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS-NONE, SCROLL BAR S._VERTICAL„ONLY, TextAreaO.
example See TextAreaO.
1418
SCROLLBARS HORIZONTAL_ONl
SCROLLBARS HOR1ZOMAL QNLY
PURPOSE Display only the horizontal scrollbar.
SYNTAX public static final int SCROLLBARS. HORIZONTAL-ONLY
DESCRIPTION This constant indicates that the text area is to have only a horizontal scrolIbar. See the class description for details on a text area's scrollbars. It is used as a parameter to the TextAreaO constructor. Its value is 2.
SEE ALSO getScrolIbarVisibility(), SCROLLBARS_BOTH, SCROLLBARS.NONE, SCROLLBARS_VERTICAL_ONLY, TextAreaO.
EXAMPLL See TextAreaO.
SCROLLBARS.NONE
PURPOSE Display neither horizontal nor vertical scrollbars.
SYMAX public static final int SCROLLBARS.NONE
DESCRIPTION This constant indicates that the text area is to have no scrollbars. See the class description for details on a text area s scrollbars, h is used as a parameter to the TextAreaO constructor. Its value is 3.
SEE ALSO getScrol1barVi si bi 1i tyО. SCROLLBARS_BOTH, SCROLLBARS-HORIZONFAL .ONLY, SCROLLBAR5_VERTICAI-ONLY, TextAreaO.
EXAMPLE See TextAreaO.
SCROLLBARS. VERTICAL-ONLY
PURPOSE Display only the vertical scrollbar.
SYNTAX public static final int SCROLLBARS_VERTICAL_ONLY
DESCRIPl ION This constant indicates that the text area is to have only the vertical scrollbar. See the class description for details on a text area's scrollbars. It is used as a parameter to the TextAreaO constructor. Its value is 1.
SEE ALSO getScrol1barVisi bi 1i tyO, SCROLLBARS.BOTH, SCROLLBARS_HORIZONTAL_ONLYT SCROLLBARS NONE, TextAreaO.
EXAMPLE See TextAreaO.
java.awt
TextArea
setCol umnsO
PURPOSE Sets the number of columns in this text area.
SYNTAX public void setColumns(int cols)
DESCRIPTION The preferred number of columns determines the text area’s preferred width and does not limit the number of columns that can be entered in the text area. See the class description for details.
PARAMETERS cols The number of columns.
EXCEPTIONS
IllegalArgumentException
If cols < 0.
SEE ALSO getColumns(), TextArea().
EXAMPLE See getCol umns ().
setRows()
PURPOSE. Sets the number of rows in this text area.
SYNTAX public void setRowsfint rows)
DESCRimON The preferred number of rows determines the text area’s preferred height and does not limit the number of rows that can be entered in the text area. See the class description for details.
PARAMETERS
rows I’he number of rows.
EXCEPTIONS
IllegalArgumentExcept!on
If rows < 0.
SEE Al so getRowsO, TextAreaQ.
EXAMPLE See getColumns().
1420
TextArea!)
п rposi
Creates a new TextArea instance.
s\\i\\ public TextAreaQ
public TextArea(String text)
public TextArea(int rows, int cols)
public TextArea(String text, int rows, int cols)
public TextArea(String text, int rows, int cols, int scrol1barVis)
descriptiox This constructor creates a new editable TextArea initialized b\ using the
siring text. If text is not specified, it defaults to
rows and cols specify the preferred number of rows and columns of the text
area. See the class description for details. If rows and cols are not specified,
the defaults are chosen by the platform.
scrollbarVis specifies which scrollbars to display with the text area. If
scrol 1 barVi s is not specified, it defaults to SCROLLBARS.BOTH. Sec the class
description for details on a text area's scrollbars.
PARAMETERS
cols A non-negative integer specifying the preferred width in characters.
rows A non-negative integer specifying the preferred height in character lines.
scrol 1 barVi sSpecifies which scrollbars to display, one of SCROLLBARS_BOTH.
SCROLLBARS_HORIZONTAL_ONLY. SCROLLBARS_VERTICAL_ONLY. or
SCROLLBARS_NONE.
text fhe siring specifying the initial text for the text component. May be null.
SEE ALSO
getRowsQ, getCol umns () ,
getScrol1barVi si bi 1i ty().
< TextArea Example ЩБ1ЕЗ
EXAMPI E
This example creates four text areas, each
with a different scrollbar \ isibilily setting.
Resize lhe window and see how the for-
matting differs for each text area depend-
ing on which scrollbars it has. See Figure
347.
import java.awt.
HGIRE 347: TextArea and its
Scrollbars.
class Main extends Frame {
Main C) {
superTextArea Example";;
Panel p =
new Panel(new GridLayout(2, 2));
TextArea both = new TextArea("Both horizontal and vertical",
10, 10, TextArea.SCROLlBARS_BOIHj;
textArea For - new Трхг Area (l’Hori zon+’al only",
10, 10. TextArea.SCROLLBARS_HORIZONTAL_ONLY);
java.awt
TextArea
TextArea()
TextArea ver = new TextArea(“Vertical only”,
10, 10, TextArea.SCROLLBARS_VERTICAL_ONLY) ;
TextArea none new TextArea(uNo horizontal or vertical",
10, 10, TextArea.SCROLLBARS_NONE);
p.add(both);
A p.add(hor);
p.add(ver);
В p.add(none);
C add(p);
pack();
D show();
}
E
static public void mai n (Stri ng [] args) {
F new Mai n();
}
G }
H
I
J
К
M
1422
| LI > U . U V V L . | 7 VV I
TextAreaPeer
Syntax
public interface TextAreaPeer extends TextComponentPeer
Description
The text area component (see the TextArea class) in the AWT uses the platform’s native
implementation of a text area. So that the AWT text area behaves the same on all platforms,
the text area is assigned a peer, whose task is to translate the behavior of the platform’s native
text area to the behavior of the AWT text area.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
See Component and Toolkit for additional information about component peers.
MKMBER SUMMARY If.
Peer Methods getMinimumSizeO getPreferredSizeO insertO replaceRange() Calculates the minimum dimensions of the text area. Calculates the preferred dimensions of the text area. Inserts some text in the text area. Replaces a range of characters in the text area with another range of characters.
Deprecated Methods | insertTextO ' minimumSizeO preferredSize() replaceText() Replaced by i nsert(). Replaced by getMinimumSizeO. Replaced by getPreferredSizeO. Replaced by replaceRangeO.
java.awt.peer
Text AreaPeer
gctMinimumSize()
See Also
java.awt.Component, java.awt.TextArea, java.awt,Toolkit.
a getMinimumSize()
В PURPOSE' Calculates the minimum dimensions of the text area.
c SYNTAX Dimension getMinimumSize(int rows, int cols)
D PARA Ml I1.R.S
E col S Л non-negative integer specifying the width in characters.
F rows A non-negative integer specifying the height in character lines.
G RETURNS The non-nul 1 minimum dimensions for the text area.
II SEE ALSO java.awt .Text Area. getMi nimumSizeO.
getPreferredSize()
purpose Calculates the preferred dimensions of the text area»
syntax Dimension getPreferredSizeOnt rows, int cols)
PARAMETERS
col s A non-negative integer specifying the width in characters.
rows A non-negative integer specifying the height in character lines.
returns The non-null preferred dimensions for the text area.
sf.f. ai so java.awt. TextArea.getPreferredSizeO.
insert()
purpose Inserts some text in the text area.
syntax void insert(String text, int pos)
parameters
pos The zero-based position at which to insert the text.
text The non-null text to be inserted.
sit ai so java. awt. I ext Area. insertO.
1424
insert it
Pt IR POSE Replaced by insertO.
ntax void insertText(String text, int pos)
PARAMETERS pos text The zero-based position at which to insen the text. The non-null text to be inserted.
DEPRECATION Replace the usage of this deprecated method, as in peer.insertText(text, pos); with peer.1nsert(text, pos);
DEPRECATED
minimumSizeO
PCRPOSI
SYNTAX
PARAMETERS
cols
rows
Rlil CRN'S
DEPRECATION
Replaced by getMinimumSizeO.
Dimension minimumSize(int rows, int cols)
A non-negative integer specifying the width in characters.
A non-negative integer specifying the height in character lines.
The non-nul 1 minimum dimensions for the text area.
Replace the usage of this deprecated method, as in
Dimension min = peer.minimumSize(rows, cols);
with
Dimension min = peer.getMinimumSize(rows, cols);
preferredSize()
Pt RPOSE Replaced by getPreferredSizeO.
SYNTAX Dimension preferredSize(int rows, int cols)
PARAMEI ERS col s rows A non-negative integer specifying the width in characters. A non-negative integer specifying the height in character lines.
RETl RNS The non-nul 1 preferred dimensions for the text area.
DEPRECA1К )N Replace the usage of this deprecated method, as in Dimension min = peer.preferredSize(rows, cols); with Dimension min peer.getPreferredSize(rows, cols);
TextAreaPeer java.awt.peer
replaceRangeC)
replaceRangeC)
PURPOSE Replaces a range of characters in the text area with another range of characters.
SYNTAX void replaceRangefString str, int start, int end)
PARAMETERS end start str The zero-based exclusive end position. The zero-based inclusive start position. The non-null replacement string.
SEE ALSO java.awt.TextArea.replaceRangeC).
replaceTextC)
PURPOSE Replaced by replaceRangeC).
SYNTAX void replaceText(String str, int start, int end)
PARAMETERS end start str The zero-based exclusive end position. The zero-based inclusive start position. The non-null replacement string.
DEPRECATION Replace the usage of this deprecated method, as in peer.replaceText(str, start, end); with peer.replaceRange(str, start, end);
1426
TextComponent
Syntax
public class TextComponent
extends Component
Description
The text component is a component that displays edit-
able text. The text can be modified by either the user
or a program. There are two text components in the
AWT package: the text field and the text area. Both are
subclasses of TextComponent. The TextComponent
class itself is not instantiated. Its main purpose is to
encapsulate the functionality that is common between
the text field and text area components. Figure 348
shows a frame containing a text area and text field.
FIGURE 348: TextArea and TextField.
The Editable Property
A text component has an editable property that controls whether the user can edit the text in
the text component. The editable property affects only edits by the user; edits by a program are
still allowed. On some platforms, the rext component has some distinguishing visual feature to
indicate its editable state.
Text Component
ja\ a. awt
/X
В
C
D
E
F
G
H
I
J
К
L
M
N
О
P
Q
R
S
Text Component Positions
Text component positions refer to a character in the text. A position is /его-based. meaning the
position of the first character in the text is 0 and the position of the last character is the length
of the text minus 1. A newline entered b\ the user to the text component is treated as a single
character (\n) regardless of the newline's representation in its native platform (which, for
example, would be \r\n on Windows).
Two positions specify a range of characters. The start position refers to the first character
in the range. The end position also refers to a character in the text, but that character is not
included in the range; the text before the character at the end position is included in the range.
Therefore, when the start and end positions are the same, the range is empty. Moreovei. to
select the last characters in the text, you should set the end position to the length of the text,
(end start) is the number of characters in the range.
TextComponent Ex. №E3
This ЯЯЯis selected.
The Selection and Caret
A selection is a range of text in the text component.
Both the user and a program can set and change the
selection. There is only one selection per text compo-
nent. The appearance and exact behavior of the selec-
tion is platform-dependent, hut on most systems, only
one selection is allowed in the entire system. Typically,
the active selection is in the text component that is
receiving keyboard input. Although the selections in
other text components are not active, a program can
still operate on the selection, modifying the range or
the text in the range. Figure 349 shows the selection on the text “word" in the text area compo-
nent.
A selection can become empty. It still has a position in the text component, but it does not
contain any text. In fact, both the start and end positions are equal. When the active selection is
empty, it becomes the “caret." The caret indicates where in the text component characters will
u
V
w
X
Y
Z
appear as the user types, marking the text component's test insertion point. 'I'he caret moves
forward with each character typed. As with the active selection, there is only one caret in the
entire system.
Figure 350 shows the caret between the words
“these words." On most platforms, when the user types
a character at the active selection, the text in the selec-
tion is deleted, the active selection is turned into a caret,
and then the character is inserted.
Events
К text component not only generates basic component
events (focus, key. mouse, mouse motion, and compo-
TextComponent Ex... ЯНЕЗ I
The caret is between 3
these | words.
< | IK
I IGl'IU 350: I he Card.
1428
nent), but also fires a text event when the text of the text component changes. See the Tex-
tEvent and Component classes for details.
If the text component is not editable, key events are still fired, but they are not inserted
into the text component.
SUMMARY чу «. . ,
Text Methods getTextO setText() Retrieves the text in this text component. Replaces the text of this text component.
Selection Methods getSel ectedTextQ getSelectionEndО getSelectionStartO selectO selectAllО setSelectionEndQ setSelectionStartO Retrieves the selected text in this text component. Retrieves the end position of this text component’s selection. Retrieves the start position of this text component's selection. Sets the selection in this text component. Selects all of the text in this text component. Retrieves the end position of this text component's selection. Retrieves the start position of this text component's selection.
Editable Methods isEditableO setEdi tableO Retrieves (his text component’s current editable state. Sets this text component's editable state.
Caret Methods getCaretPosi tion() setCaretPosi ti on() Retrieves this text component's text insertion point. Sets this text component's text insertion point.
Event Methods addTextLi stenerO processEventO processTextEventO removeTextLi stenerO Adds a listener to receive this text component’s text events. Processes an event enabled for this text component. Processes a text event enabled for this text component. Removes a listener from receiving this text component's text events.
Peer Method removeNotifyO Destroys this text component's peer.
Debugging Method paramStri ng О Generates a string representation of this text component’s slate.
TextComponent
jav a.aw t
addTcxtListener()
See Also
java.awt.event.TextEvent, java.awt.event.TextLi stener, TextArea,
TextFi el d.
Example
This example creates a frame containing both kinds of text components: a (ext field and a text
R area. See Figure 34S for a screen shot of the example.
C
import java.awt.*;
p class Main {
p; static public void main(String[] args) {
Frame f = new Frame(“TextComponent Example”);
P' f.add(new TextFieldO, BorderLayout. SOUTH);
f.addfnew TextAreaO, BorderLayout. CENTER);
G f.packO;
f.show();
I
addTextListener()
purpose Adds a listener for receiving this text component's text events.
syntax public synchronized void addTextLi stener (TextLi stener listener)
description Text events are fired when the component's text is changed. See TextEvent
for more details. After this method is called, the text listener listener will
receive text events fired by this text component. If listener is null, this
method does nothing.
PARAMETERS
1 i stener The possibly nul 1 text listener to add.
see also j ava.awt.event.TextEvent, java.awt.event.TextListener,
removeTextLi stenerO.
EXAMPLE
This example
creates a frame
containing two
text areas.
Changes made in
one text area are
automatically
made in the other
text listener via
the use of a text
listener. See Fig-
ure 351.
I ’ addTextListener Exampli s _
FIGURE 351: Echoing TextAreas.
1430
getcaretFositi
import java.awt.*;
import java.awt.event.*;
class Main extends Frame implements Textlistener {
TextArea tai = new TextArea(nul 1, 10, 40);
TextArea ta2 = new TextArea(nul1, 10, 40);
Main() {
super(“addTextListener Example”);
setLayout(new GridLayout(1, 2));
add(tal);
add(ta2);
// Add text listener for text areas
tai.addTextLi stener(thi s);
ta2.addTextLi stener(thi s);
pack();
show();
}
public void textValueChanged(TextEvent evt) {
Textcomponent src = (TextComponent)evt.getSourceO;
if (src =-= tai) {
ta2. setText(tal.getTextO) ;
} else {
tai. setText('ta2 .getTextO) ;
}
}
static public void mai n(St ri ng[J args) {
new Main();
}
}
getCaretPo$ition()
purpose Retrieves this text component’s text insert point.
syntax public int getCaretPosition()
description The caret position indicates where characters will be inserted as the user types.
See the class description for details on caret.
Rirri’RKs The zero-based index of the caret’s position. Text will be inserted just before
the character referred to by the index.
see also setCaretPosi tionQ.
TextComponent
getSelectedTextt)
jaxa.awt
EXAMPLE
This example creates a text area
for entering text and a label at
the bottom for displaying the
current caret position. Reposi-
tioning the caret using the
mouse also updates the label.
Sec Figure 352.
< getCaretPosition Example ВИЗЕ
There is some text. here.
Where Js the caret’7
carets 32
import java.awt.*;
import java.awt.event.*;
FIGURE 352: TextComponent's Caret Position.
class Main extends Frame {
TextArea ta =
new TextArea(nul1, 10, 40);
Label caret = new Label(“caret=0”);
MainQ {
super(“getCaretPosition Example”);
add(ta, BorderLayout.CENTER);
add(caret, BorderLayout.SOUTH);
// Add listeners for text area
ta.addKeyLi stener(new KeyEventHandl er());
ta.addMouseLi stener(new MouseEventHandl er());
packQ ;
show();
}
class KeyEventHandler extends KeyAdapter {
public void keyTyped(KeyEvent evt) {
caret. setText(“caret=”4-ta.getCaretPosi tionQ );
}
}
class MouseEventHandler extends MouseAdapter {
public void mousedicked(MouseEvent evt) {
caret.setText(“caret = ”+ta.getCaretPosi ti on());
}
}
static public void mai n(St ri ng [] args) {
new Mai n();
}
}
getSelectedTextf)
purpose Retrieves the selected text in (his text component.
syntax public synchronized String getSelectedText()
1432
get Selected le
1)1 SCRIP I l( )\
RETI R\S
This method retrieves the selected text in this text component. Each text com-
ponent has a selection that may be empty.
SEE ALSO
EXAMPI I.
A non-null string containing
the text in the selection. The
length of the result value may be
0.
select().
This example creates a frame
containing both kinds of text
components — the text field
and the text area — and a Print
button. See Figure 353. Click-
ing the Print button causes the
current selection of both text
components to be printed on
standard output.
^getS elected! ext Example BPJEJ
Print Selections
Heie's some selected text
FIGURE 353: Retrieving the Selected Text
from a TextComponent.
import java.awt.-';
import java.awt.event;
class Main extends Frame implements ActionListener {
TextField tf = new TextFieldO;
TextArea ta = new TextAreaO;
MainO {
super(“getSelectedText Example");
Button b = new ButtonC’Print Selections");
add(b, BorderLayout.NORTH);
addCta, BorderLayout.CENTER);
add(tf, BorderLayout.SOUTH);
// Add listener for button
b.addActi onLi stener(thi s);
pack():
show();
}
// Action listener for button
public void actionPerformed(ActionEvent evt) {
System. out. pri ntl n(“--text area----------;
System.out.println(ta.getSelectedText());
System. out. pri ntl n(“--text field---------”) ;
System.out.printlnftf.getSeiectedText());
static publir void main(StringГ1 args) {
new Ma i n();
Text Coni pone nl
ja\ u.au t
gel Select ion Finch )
getSelectionEnd()
p; RPOSi Retrieses the end position of this text component’s selection.
й\ъ\.\ public synchroni7ed int getSelectionEnd()
[)LSCRIPriO\
RETURNS
rhe selection end position can
he in lhe range 0 I о lhe length
of text in the text component.
I he selection's start position
musi be less than or equal lo
the selection's end position.
The zero-based index cd' the
selection’s end position. Note
get Select edE nd Example HIO E3
Hete’s some inure text
Here s some text
b\ lhe index is not in the
xu lecl ion.
I Hi I RE 354; Selecting tc» the End-ot-linc in a
TextComponent.
L X XMPl I
get Se1ect i onStart О » setSeiecti ontnd().
This example creates a frame containing both kinds of text components — (he
text field and the text area. See Figure 354. Гх pi ng C’lrl I; in one of these com-
ponents will extend lhe selection to the end-of-line, not including lhe newline
character.
inport java.awt.-;
import java.awt .event.;
class vai n extends Franc {
textField tf = new TextFieldO:
TextArea ta - new TextAreaO;
vain() {
super (“got So 1 oct edF nd F xa*ip 1 e”);
add(ta, BorderLayout.СЕХ1FR);
add(t f, Border:ayout.SOUTH);
// Add listeners for textField and textarea
KeyEventHandler listener new KeyFventHandl er();
ta.addKeyi i st oner(1i stener);
tf.addKeyLi stere гp i stener);
pack();
showC);
}
class KeyEventHand1 er extends KeyAdapter {
public void keyPressed(KeyFvent evt) {
if (evt.isControlDown() && evt.getKeyCodeO — Keylvent.VK_F) T
TextCorr.ponent tc = (TextCornponent )evt . getSourceO ;
String str - tc,getText();
int e = str.indexOf(‘\n’, tc.getSelcctionEnd()):
1434
gel SclectionSt
tc.setSelectionEnd(e < 0 ? str.lengthO : e) ;
}
}
}
static public void main(String[] args) {
new Mai n() ;
}
}
getSelectionStart()
purpose Retrieves the start position of this text component’s selection.
SYVI AX
public synchronized int getSel ecti onStartO
DESCRIPTION
REIURNS
SEE ALSO
EXAMPLE
The selection start posi-
tion can be in the range
0 to the length of text in
the text component.
The selection's end
position must be greater
than or equal to the
selection's start posi-
tion.
The /его-bascd index
of the selection’s start
position.
l^getSelectedStart Example ИНЕЗ
IlSelect to the start of the lineRffl 's some text I
.11 -O
Here's some more text.
FIGI RE 355: Selecting to the Beginning of the Line in
a TextComponent.
getSel ecti onEndO, setSelectionStartf).
This example creates a frame containing both kinds of text components — the
text field and the text area. Sec Figure 355. Typing Ctrl-A in one of these com-
ponents will extend the selection to the start-of-line.
import java.awt."';
import java.awt.event;
class Main extends Frame {
TextField tf = new TextFieldO:
TextArea ta = new TextAreaO;
MainO {
super("getSelectedStart Example'1);
addfta, BorderLayout.CENTER);
add(tf, BorderLayout.SOUTH);
// Add listeners for textfield and textarea
KeyEventHandler listener = new KeyEventHandler();
ta.addKeyL i stener(li stener);
java.awt
TextComponent
gelTcxtf)
tf.addKeyLi stener(1istener);
pack();
show();
}
A class KeyCventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
В if (evt.isControlDown() && evt.getKeyCodeO -- KeyEvent.VK_A) {
TextComponent tc = (TextComponent)evt.getSourceO;
C String str - tc.getTextO;
int s = str,lastlndexOf(‘\n’, tc.getSelectionStartO 1) + 1;
D
tc.setSelectionStart(s);
E }
}
F }
G static public void mai n(Stri ng[] args) {
new Main();
H }
}
I
J
getText()
plrpose Retrieves the text in this text component.
syntax public synchronized String getTextO
returns A non-null string containing the entire text in the text component.
see also setText().
example See setText().
isEditableQ
PURPOSE Retrieves this text component's current editable state.
SYMAX public boolean isEditableQ
RETURNS true if the text component is edit' able; fal se otherwise.
SEE ALSO setEditablet).
EXAMPLE This example creates a frame con- taining a text area and a text field. Typing Ctrl-T toggles the editable state of the text component. See Figure 356.
FIGI RE 356: Editable and Noneditable
TextComponents.
1436
import java.awt.*;
import java.awt.event;
class Main extends Frame {
TextField tf new TextFieldO;
TextArea ta = new TextAreaO;
Label status = new Label (“heritable”);
Main() {
super(“isEditable Example");
add(status, BorderLayout.NORTH);
add(ta, BorderLayout.CENTER);
add(tfT BorderLayout.SOUTH);
// Add listeners for textfield and textarea
KeyEventHandler listener = new KeytventHandlerO;
ta.addKeyListener(listener);
tf.addKeyListener(listener);
pack();
showO;
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
if (evt.isControlDown() && evt.getKeyCodeO == Keytvent.VK_T) {
TextComponent tc - (TextComponent)evt.getSourceO;
tc.setEditabled tc.isFditableO);
if (tc.i sEditableO) {
status.set Text("Fdi table");
} else {
status.setText(“Not Edi table");
}
}
}
static public void main(String[] args) {
new MainO;
}
paramStringO
Pl’RPOSh Generates a string representation of this text component’s state.
SYNTAX protected String paramStringO
DESCRIPTION The string representation of a text component consists of the string representa- tion of a Component, plus information stating whether it is editable and the text selected. A subclass of this class should override this method and return a concatenation of its stale with the results of super.paramStringO. This method is called by the toStringO method and is typically used for debug- ging.
TextComponent
processF.vent()
java.awt
REIT RNS A non-null string representing the text component's state.
OVERRIDES Component.paramStri ng().
SEE ALSO Component.toString(), java.lang.Object.toString().
EX AMPLE See Component.paramStringO-
processKventf)
Pl RPOSE Processes an event enabled for this text component.
SV MAX protected void processEvent(AWTEvent evt)
DEPRECATION This method extends Component.processEventO by adding support for TextEvent. This method can be overridden to handle new types of events for this text component. When a subclass overrides processEventO. it should call super.processEventO to perform the processing intended by its base class (such as dispatching events to the listeners).
PAR AM El ERS evt The event to be processed.
OVERRIDES Component.processEvent().
SEP ALSO AWTEvent, processTextEventО.
EX AMPLE See the Component class example.
processTextEvent()
PURPOSE Processes a text event enabled for this text component.
SYNTAX protected void processTextEvent(TextEvent evt)
DESCRIPTION Text events are tired when this text component’s text changes. See lhe class description and TextEvent for more details. This method processes text events for this text component by notifying the registered TextLi stener. This method is invoked only if text events have been enabled for this text compo- nent. This can happen either when a text listener is added to this text compo- nent or when Component. enableEventsO is called to enable text events. Typically, a text component controls how its text events are processed by add- ing or removing text listeners. It overrides processTextEventO only if it needs to do processing in addition to that performed by lhe registered listeners.
1438
reinove.Not
When a subclass does override processTextEvent O> it should call super.processTextEvent() to perform the processing intended by its base class (such as dispatching events to the listeners).
PARAMETERS evt fhe non-null text event.
SEE ALSO addTextListenerO , Component. enableEventsO . Component.disableEventsО, java.awt.event.TextEvent, java. awt. event.TextListener, processEventO , removeTextLi stenerO.
EXAMPI E See AWTEventMulti caster.textValueChangedО -
removeNotify()
PURPOSE: Destroys this text component’s peer.
SYVI-XX public void removeNotifyO
DESCRIPTION This method should never be called directly. It is normally called by the com- ponent's container.
OVERRIDES Component. removeNotifyO.
see: also Component.
EXAMPLE: See Component. setVi si bl e О.
removeTextListener()
PURPOSE Removes a listener from receiving this text component’s text events.
SYNTAX public void removeTextListener(TextListener listener)
DESCRIPTION Text events are fired when this text component's text is changed. See TextEvent for more details. After this method is called, the text listener listener will no longer receive text events from this text component. If listener is null, this method does nothing.
PARAMEIERS li stener The possibly nul 1 text listener to remove.
sei: also addlextLi stenerO, java.awt.event.TextEvent, j ava.awt.event.TextLi stener.
EX AMPLE See removeActionLi stenerO in Menuitem.di sableEventsQ.
TextComponent
select()
java.awl
select()
PURPOSE Sets the selection in this text component.
SYNTAX public synchronized void select(int selStart, int selEnd)
DESCRIPTION This method selects the text located between the positions selStart and sel End. inclusive. If a position is negative, the position is set to 0. If a position is greater than the length of text in the text component, the position is set to the length. If sel End < sel Start, sel End is set to sel Start.
PARAMETERS selEnd sei Start The zero-based end position of the text range. The zero-based start position of the text range.
SF.F. ALSO setSelectionEnd(), setSelectionStart().
example This example creates a text
area and a text field in a
frame. See Figure 357.
Pressing Return while in
the text field causes a
search for the string in the
text field.
FIGURE 357: Selecting Text in a TextComponent.
import java.awt.*;
import java.awt.event;
class Main extends Frame implements ActionListener {
TextField tf = new TextFieldO;
TextArea ta = new TextArea(10, 40);
MainO {
super(“select Example”);
add(ta, BorderLayout.CENTER);
add(tf, BorderLayout.SOUTH);
// Add listener for text field
tf.addAct i onLi stener(thi s);
pack();
show();
}
public void actionPerformed(ActionEvent evt) {
String str = tf.getTextO;
int s = ta. getTextO . i ndexOf (str, ta.getSelectionStartO);
if (s < 0 && ta.getSelectionStartO > 0) {
// Let's try from the beginning.
s = ta. getTextO . i ndexOf (str, 0);
}
1440
if (s >= 0) {
ta.select(s, s - str , lengthQ) ;
ta.request Focus();
static public void main(String[] args) {
new Main():
}
}
selectAlK)
Pl RPOSL
SYVLW
DESCRIP I IO\
SEE ALSO
EXAMPLE
Selects the text in this text component.
public synchronized void selectAHQ
This method selects the entire text
in the text component.
seiectО,
setSelectionEndO ,
setSeiecti onStart().
This example creates a frame con-
taining a menu bar and a text area.
The menu bar contains an Edit
menu with the item Select Aik
which causes the text area to
request the focus and select all of
its text. See Figure 358.
FIGI RE 35S: Selecting All of the Text in a
TextComponent.
import java.awt.w;
import java.awt.event.'':
class Main extends Frame implements ActionListener {
TextArea ta = new TextAreaO:
MainO {
supe r (“sei ectAl 1 Example’’):
MenuBar mb = new MenuBarO;
Menu menu = new Menu(“Edit");
menu.add(“Select All");
mb.add(menu);
setMenuBarГ mb);
addfta, BorderLayout.CENTER);
// Add listener for Edit menu
menu.addActionListenerfthis);
TextComponent
setCaretPosition()
java.awt
pack(); show(); } public void actionPerformed(ActionEvent evt) { if (“Select Al T\equal s(evt. getActionCommandO)) {
A ta.seiectAl1(); ta. requestFocusO;
В C } } static public void main(String[] args) {
D LI new Main(); } }
F G H 1 setCaretPosition() purpose Sets this text component's text insertion point.
J syntax public void setCaretPosition(int caret)
К description The caret position indicates where characters will be inserted as rhe user types.
L See the class description for details.
M N PARAMETERS caret The zero-based index of the caret’s position. Text will be inserted just before the character referred to by the index.
() sei: also getCaretPosi tionQ.
P example This example creates a text field. WnAll VPill ПГР<к tki*> к av thp
Q W 11^.11 у U U 111^» 1 * 111 । l\»t у * LI lx/ . . . IWheie is the caret now? caret is moved to the beginning ot J
R the text field. See Figure 359.
S U FIGURE 359: Settings Text Component’s Caret. import java.awt-*; import java.awt.event; class Main extends Frame {
V TextField tf - new TextFieldO;
W Main О { super(“setCaretPosition Example”);
X add(tf);
Y // Add key listener for text field
Z tf. addKeyl i stener(new KeyEventHandlerO); pack О; show(); J
1442
>ciHdituble(
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCodeO == KeyEvent.VK_ENTER) {
tf.setCaretPosi tion(0);
}
}
}
static public void main(String[] args) {
new Mai n();
}
}
setEditablel I
PLRPOSt. Sets this text component s editable state.
syntax public synchronized void setEditable(boolean editable)
PARAMETERS
editable If true, the text component becomes editable: otherwise, it becomes unedit-
ablc.
see: also i sEdi tabl e().
example This example creates a frame con-
taining a text area and a checkbox.
The checkbox sets the editable
state of the text area. See Figure
360.
import java.awt.1’';
import java, awt. event . ;
class Main extends Frame IIGLRE 360: Editable TextComponent.
implements ItemListener {
TextArea ta = new TextAreaO;
Checkbox cb =
new Checkbox(‘‘Edi tabl e” , null, true);
Main() {
super(“setEditable Example”);
add(ta, BorderLayout.CENTER);
add(cb, BorderLayout.SOUTH);
,// Add listener for checkbox
cb.addltemLi stener(this);
H^setEditable Example
.. ...........——— I ——1
This text is currently editable.
<|
P Editdbfe
packQ;
show():
TextComponent
setSelectionEndO
java.awt
public void itemStateChanged(ItemEvent evt) {
ta.setEdi tab le(cb. getStateO) ;
}
static public void main(String[] args) {
new Mai nO :
A 1
}
В
D setSelectionEnd()
E PURPOSE Sets the end position of this text component's selection.
F SYNTAX public synchronized void setSelectionEnd(int posn)
G DESCRIPTION Che end position of a text component's selection can be in the range 0 to the
H I length of text in the text component. The selection's start position must be less than or equal to the selection's end position. This method sets the selection's
end position to be posn and selects the text between getSelectionStartQ
J and posn.
К PARAMETERS
L M posn The noninclusive. zero-based index of the end position of this text compo- nent's selection. Note that the character referred to by the index is not in the selection.
N SEE ALSO getSelectionEndQ , selectO . selectAl 1 () , set Sei ectionStartQ.
О EXAMPLE See getSelectionEndQ.
p
setSelectionStart()
purpose Seis the start position of this text component’s selection.
syntax public synchronized void setSelectionStart(int start)
description Phe start position of a text component's selection can be in the range 0 to lhe
length of text in the text component. The selection's end position must be
greater than or equal to the selection's start position. This method sets the
selection's start position to be start and selects the text between start and
getSelectionEndQ.
PARAMETERS
start The zero-based index of the start position of this text component's selection.
SEE also getSel ecti onStartf) , selectO , sei ect All () , setSelectionEndO.
example See getSel ecti onStartQ.
1444
setTextf)
pi rposi Replaces ihe text of this text component.
S'txi.w public synchronized void setText (St ri ng text)
dlscripiiox This method replaces the entire text of the text component with the string
text.
PXRW1I h-.rs
text A string containing the text. A value of nul 1 is the same as
ski. also getTextO.
exampi i: This example creates
a frame containing two
text areas. Typing Ctrl-
T swaps the text in the
components. See Fig-
ure 361.
| setT ext E xample
This text used to be This text used to be
ill the nght text area in die let! text area
co тропе nt component
EIGl RE 361: Swapping Text.
import java.awt.'-;
import java.awt.event.*;
class Main extends Frame {
TextArea tai = new TextArea(nul1, 10, 40);
TextArea ta2 = new TextArea(nul1, 10, 40);
MainO {
super(“setText Example");
setLayout(new GridLayout(1, 2));
add(tal);
add(ta2);
// Add key listener for text areas
KeyEventHandler listener = new KeyEventHandler();
tai.addKeyLi stener(listener);
ta2.addKeyLi stener(listener);
pack();
showO ;
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
if (evt.isControlDown О && evt.getKeyCode() == KeyEvent.VK_Tj {
String str = tai. getTextO ;
tai setTpxt(ta 2.getTextО):
ta2.setText(strJ;
lextComponent java.awt
setTexK)
}
static public void mai n(St ri ng[] args) {
new Mai n();
}
}
Л
В
c
D
E
Г
G
II
I
J
К
L
M
N
G
P
Q
R
S
U
V
W
X
Y
Z
1446
I il V cl .U VV L /Ltl
TextComponentPeer
Syntax
public interface TextComponentPeer extends ComponentPeer
Description
The text component (see the TextComponent class) in the AWT uses the platform’s native
implementation of a text component. So that the AWT text component behaves the same on all
platforms, the text component is assigned a peer, whose task is to translate the behavior of the
platform’s native text component to the behavior of the AWT text component.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
j ava. awt counterparts.
See Component and Toolkit for additional information about component peers.
TextComponentPeer
getCaretPositionO
java.awt.peer
MEMBER SUMMARY
A
В
C
D
E
Peer Methods
getCaretPosi tion()
* getSelectionEndO
getSelectionStartО
getTextO
selectO
I setCaretPosition О
setEditablet)
setText О
Retrieves the text component's text insertion point.
Retrieves the selection4s end position.
Retrieves the selection's start position.
Retrieves the text in the text component.
Sets the selection in the text component.
Sets the text component's text insertion point.
Sets the text component's editable state.
Sets the text of the text component.
F
G
H
See Also
java.awt.Component, java.awt.TextComponent, java.awt.Toolkit.
j
getCaretPosition()
M
N
О
P
Q
R
S
U
w
X
Y
Z
rirpose Retrieves this text component's text insertion point.
symax public int getCaretPosi tionQ
reti’Rss The O-based index of the caret's position. Text will be inserted just before the
character referred to by the index.
sef also java.awt.IextComponent.geLCaretPosi t i on().
getSelectionEnd()
plrpose Retrieves the selection's end position.
syntax int getSelectionEndO
returns The О-based index of the selection's end position.
see also java.awt.TextComponent.getSelectionEndО.
getSelectionStart()
pirpose Retrieves the selection's start position.
syntax int getSelectionStart()
returns The О-based index of the selection's start position.
sei also java.awt.TextComponent.getSelectionStartО •
1448
getTe:
getTextf)
PURPOSE SYNTAX Retrieves the text in the text component. String getfextO
Rl-Л I RNS A non-nul 1 string containing the entire text in the text component.
SEE A [.SO java.awt.Textcomponent.getTextf).
select()
Pt: RPOSE Sets the selection in the text component.
SYNTAX void select(int selStart, int selEnd)
PARAMI: I ERs selEnd selStart The 0-based end position of lhe text range. The 0-based start position of the text range.
SEEALSO java.awt.TextComponent.seiect().
setCaretPosition()
PURPOSE Sets the text component’s text insertion point.
SYNTAX public void setCaretPosition(int caret)
PARAMETERS caret The 0-based index of lhe caret s position. Text will be inserted just before the character referred lo by the index.
SEE ALSO java.awt.TextComponent.setCaretPosi tion().
setEditable()
pi rpose Sets the text component’s editable state.
syntax void setEditable(boolean editable)
PARAMETERS
editable If true, the text component becomes editable; otherwise, it becomes unedit-
able.
see also java.awt .Textcomponent, setEdi tableO-
TextComponentPeer
sctText()
java.awt.peer
setText()
Л PURPOSE SYN'i AX PARAMETERS Sets the text of the text component, void setText(String text)
в text A string containing the text. A value of null is the same as
c SEE Al SO java.awt .TextComponent. setTextO-
D
E
F
G
H
1
J
К
L
M
N
О
P
Q
R
S
U
V
w
X
Y
z
1450
TextEvent
Syntax
public class TextEvent extends AWTEvent
Description
Text events are fired by text components (see
TextComponent) whenever the contents of (he
text component changes. The AWT has (wo text
components that fire text events: TextArea and
TextField. For more general information
about events, see AWTEvent.
Listening for Text Events
To listen for text events from a component, the
listener must implement the TextListener
interface. After that, the listener must be regis-
tered with the object. It becomes registered by
calling the object's addTextLi stenerO
method. As with most events, text events are
delivered to its listeners after the operation has
taken place.
TextComponent •
processEventO
TextListener О
UO
Text Event Flow
Figure 362 shows how text events typically FTGtRE362: Text Event Flow.
flow through the system. First, the event is fired
by a text component peer. This event is posted on the event queue (see EventQueue). When
the event makes its way to the front of the queue, it is given to the component via its dis-
TextEvent
java.awt. event
A
В
C
D
H
F
patchEventQ method. The main purpose of this method is to discard the event if the text
event type is not enabled or if there are no text event listeners. Otherwise, di spatchEventO
calls processEventO, which in turn calls different methods depending on the event ivpe.
Since this is an text event, processTextEventO is called. The main purpose of this method
is to notify the text event listeners.
A component can override processTextEventO to process text events before they are
delivered to its listeners. The overridden method should call super.processTextEventO to
ensure that events are dispatched to the component’s listeners.
MEMBER SUMMARY
Constructor TextEventO Constructs a Text Event instance.
| Text Event Id Constants J TFXT_FIRST TEXT.LAST TEXT. VALUE-CHANGED Constant specifying the first id in the range of text event ids. Constant specifying the last id in the range of text event ids. Event id indicating that a text event occurred.
Debugging Method paramStringO Generates a string representing Ihe text event's state.
See Also
jav.awt.AlftTTEvent, java.awt.AWTFventMulticaster.textValueChangedО,
java .awt.Component.di spatchEventO , java.awt.TextArea, java.awt .TextField»
TextLi stener.
Example
This example demonstrates how to get text events from a
component that fires them. The example creates a text area
and listens for text events from the text area. In response to
a text event, the specifics of the event are printed. See Fig-
ure 363.
T extE vent Ex...
This component
generates text events
FIGI Rk 363; TextEvent.
import java.awt.*;
import java.awt.event;
class Main extends Frame implements Text!istener {
Main() {
super("TextEvent Example1');
TextArea ta = new TextAreaO;
1452
paramStri
// listen for text events.
ta.addTextListenerfthi s);
add(BorderLayout.CENTER, ta);
pack();
show();
}
public void textValueChanged(TextEvent evt) {
System.out.println(evt);
}
public static void main(Strinq args[]) {
new MainO ;
J
}
paramStringO
PURPOSE Generales a string representing the text event's state.
SYNTAX public String paramStringO
DESCRIPTION The returned string contains the name of the text event. A subclass of this class should override this method and return a concatenation of its slate with the results of super. paramStringO. This method is called by the AWTEvent.toStringO method and is typically used for debugging.
REIT RN’S Л non-null string representing the text event’s state.
OVERRIDES java.awt .AWTEvent. paramStringO.
SEE ALSO java.awt.AWTEvent.toStringO, java.lang.Object.toString О.
EXAMPLE Seethe java.awt.AWTEvent class example.
TEXT FIRST
PURPOSE Constant specifying the first id in the range of text event ids.
SYNTAX public static final int TFXT-FIRST
DESC RIH ION All text event ids must be greater than or equal to TEXT-FIRST (value 900).
SEE ALSO TEXT .LAST.
EXAMPLE See java.awt.Component.processEventО.
java.awt.event
TextEvent
TEXT_LAST
TEXT_LAST
PL RPOSL Constant specifying the last id in the range of text event ids.
SYNTAX public static final int TEXT-LAST
A DESCRIPTION All text event ids must be less than or equal to TEXT„LAST (value 900)
В SE£E ALSO TEXT FIRST.
C D EXAMPLE See java.awt.Component.processEventO.
Г TEXT_VALLE_CHANGED
F -------- ----------------------------------------------------- --------
pr rpose: Event id indicating that a text event occurred.
H SYNTAX public static final int TEXT.VALUE_CHANGED
। description Text events are fired by text components (see Textcomponent) whenever the
contents of the text component change. All text events fired by the components
J TextArea and TextField have this id (value 900).
K she also TextEventO.
1 example See the java, awt .Component class example.
M
TextEventO
о-------------------------------------------------------------------------------------”
p pl rpose: Constructs a TextEvent instance.
p syntax public lextEvent(Object source, int id)
p description This constructor creates a new' text event with source as the object that fires
this event. At present, there is only one text event id. so i d must be set to
TEXT_VALUE_ CHANGED.
The source object should implement the various methods that support text
event listeners: addTextLi stenerO. removeTextListenerO, processEv-
entO, and processTextEventO. For an example of a component imple-
menting these methods, see the KeyEvent constructor example. After the text
event is created, the source object can distribute the text event by calling
AWTEventMul ti caster. textVal ueChanged О. If the event is not created by
source, the creator can deliver the event to rhe source component either by
posting the event to the event queue (see EventQueue. postEventO) or by
calling the source component’s Component .di spatchEventO method
directly.
1454
TextEx
PARAMH ERS
source id The non-null text component that is firing this text event. Must be TEXT.VALUE .CHANGED.
SEE ALSO java.awt .AWTEvent .getIDO, java.uti1.Eventobject.getSourceO, java.awt.AWTEventMulticaster.textValueChangedO, java.awt.Component.di spatchEvent О, TFXT_VALUE_CHANGED.
EXAMPLE See the java.awt .Component class example.
java.awt
TextField
C : * TextField
D -
E
F Syntax
c public class TextField extends TextComponent
H
I
J
К
L
Description
A text field is a text component that displays editable text.
The text field is similar to the text area component, except
that the text field holds only a single line of text.
Л text field is typically used to obtain textual input from
the user. Figure 364 shows a text area and a text field.
^TextField Ex.
...............
TextField
FIGI KF. 364: TextField.
The Echo Property
The text field can be set in a mode in which all characters typed into the text field are displayed
as a different character called the echo character. The text field still maintains the original
characters, but it disguises them as the echo character. The disguises can be removed b> setting
the echo character to 0.
Q
R
S
I)
V
w
X
Y
Preferred Number of Columns and Preferred Size
A text field can be created with a preferred number of columns used to calculate its preferred
width. The width calculation is based on the average size of a character, and the result is an
approximation. The average width of a character is a platform-dependent value. The preferred
number of columns can be changed at any lime using setColumnsO. When this happens, the
preferred si/e is changed as well.
The number of columns in a text field does not limit the number of characters that can be
entered. The text field automatically scrolls to the right as additional characters are appended
beyond its component si/e (regardless of the number of columns). The contents of the text
field can be scrolled and \ iewed using the left and right arrow keys.
A text field can be resized to be larger or smaller than its preferred number of columns.
1456
Events
A text field not only generates the events fired by a text component, but also fires an action
event when the Return key is pressed. The action command associated with the action event is
the text field's contents. See ActionEvent for details.
MEMBER SUMMARY
Constructor TextFi eldО Constructs a new TextField instance.
Echo Character Methods echoCharlsSetQ getEchoCharQ setEchoCharQ Determines if this text field's echo character has been set. Retrieves this text field's echo character. Sets this text field's echo character.
Layout Methods getColumnsO getMinimumSizeO getPreferredSizeO Retrieves the number of columns in this text field. Calculates the minimum dimensions of this text field. Calculates the preferred dimensions of this text field.
setColumns() Event Methods addActionLi stenerO processActi onEventO processEventO removeActionLi stenerO Sets the number of columns in this text field. Adds a listener to receive action events from this text field. Processes an action event enabled for this text field. Processes an event enabled for this text field. Removes a listener from receiving action events from this text field.
Peer Method addNotifyO Creates this text field’s peer.
Debugging Method paramStringO Generates a string representation of this text field's state.
Deprecated Methods minimumSi zeO preferredSizeO setEchoCharacterO Replaced by getMinimumSizeO. Replaced by getPreferredSi zeO. Replaced by setEchoCharQ-
See Also
TextArea.
java.awt
TextField
addActionl Jstener()
Example
This simple example creates a frame that has a text field. When you press Return while in the
text field, it prints the contents of the text field. Sec Figure 364 for a screen shot of the exam-
import java.awt, -';
import java.awt.event.*;
public class Main extends Frame implements ActionListener {
TextField tf - new TextFieldCTextField”) ;
MainO (
super(*‘TextField Example’’);
add(tf, Borderlayout.CENTER);
// Add listener for text field
tf.addActionListenerCthis);
pack();
show();
}
public void actionPerformedfActionEvent evt) {
System.out.println(tf.getTextО);
}
static public void mai n(Stri ng[] args) {
new Mai n();
}
}
addActionListenerf)
Pl'RPOSE Adds a listener for receiving this text component's action events.
SYNTAX public synchronized void addActionListener(ActionListener 1istener)
DFSCR1PTION Action events are fired when the Return key is pressed. See ActionEvent for more details. After this method is called, the action listener listener will receive action events fired by this text component. If listener is null, this method does nothing.
PARAMETERS li stener l he possibly nul 1 text listener to add.
SEEALSO java.awt.event.ActionEvent, java.awt.event.ActionListener, remove .ActionLi stenerO.
EXAMPI F See the class example.
1458
addNotify()
PURPOSE Creates the text field's peer.
SYNTAX public void addNotifyO
DESCRIPTION This method creates the text field's peer if it does not exist. The text field's peer is created by calling the Toolkit.createTextAreaO method. This method should nexer be called directly. It is normally called by the text field's parent.
OVERRIDES Component.addNoti fy().
SEE ALSO Component, Toolkit.
EXAMPLE See Component.setVi si ble().
echoCharlsSett)
Pl RPOSL
Determines if the text field's echo character has been set.
syntax public boolean echoCharlsSet()
returns true if the text field's echo character has been set; false otherwise.
see also getEchoCharQ , setEchoChar Q.
example This example creates a text field. Typ-
ing Ctrl-A toggles whether or not an
echo character is set for the text field.
See Figure 365.
import java.dwt.'';
import java.awt.event.*;
class Main extends Frame {
TextField tf = new TextField(40);
HGI RE 365:
Echoing TextField Contents.
MainQ {
super(“echoCharlsSet Example”);
add(tf, BorderLayout.NORTH);
tf.addKeyLi stener(new KeyEventHandl er());
pack();
showQ :
}
class KeyEventHandler extends KeyAdapter {
public void keyPressedCKeyEvent evt) {
int key = evt. getKeyCodeO ;
if (evt.isControlDownQ && key == KeyEvent.VK_A) {
if (tf.echoCharlsSetО) {
key = 0;
I ext Field
java.awt
gelColumn4)
} else {
key - ‘;
}
tf.setEchoChar((char)key);
}
}
A
В
C
D
E
F
G
H
I
J
К
L
static public void main(String[] args) {
new Mai n();
getColumnsf)
porposf Retrieves the preferred number of columns in this text field.
syntax public int getColumnsO
descripiion The preferred number of columns determines the text field s preferred width.
See the class description for details.
rkitrxs The number of columns used in this text field.
N
О
P
Q
R
S
SF-Лг ALSO EXAMPLE setColumnsO. This example cre- ates an automati- cally expanding
getColumns Example
|There is a lot of text here. I hope] |
text field. See Fig- ure 366. The text field’s number of FIGURE 366: An Automatically Expanding TextField.
columns is doubled of columns. when the number of characters entered equals the number
import java.awt.*;
import java.awt.event;
class Main extends Frame implements lextListener {
TextField tf = new TextField(10);
V
W
X
Y
Z
Main() {
super(“getColumns Example”);
add(tf, BorderLayout.NORTH);
// Add text listener fof text field
tf.addTextLi stener(thi s);
рас к О ;
show();
}
1460
getEchoCha
public void textValueChanged(TextEvent e) {
int cols = tf .getColumnsQ ;
if (tf.getTextO . lengthO == cols) {
tf.setColumns(cols+col s); // double
packO; // adjust Frame to accommodate new size
}
}
static public void main(String[J args) {
new Main();
}
}
getEchoChar()
purpose: Retrieves this text field's echo character.
SYNTAX public char getEchoCharO
DESCRJPFION This method retrieves the text f ield's echo character. The result is not meaning- ful unless echoCharlsSetO returns true.
RETI’RNS The text field's echo character.
see: ALSO echoCharlsSetO, setEchoChar().
EXAMPLE See setEcho€haracter().
getMinimumSize()
PURPOSE Calculates the minimum dimensions of this text field.
SYNTAX public Dimension getMinimumSizeO public Dimension getMinimumSize(int cols)
DESSC'RIPTION I'he minimum dimensions of a text field are based on the dimensions needed for displaying one row of cols characters. The size of a character depends on (he text field's current font. If the (ext field's font has variable-width charac- ters. then cols is based on the average size of a character and the result is an approximation. The average width of a character is a platform-dependent value. If col s is not specified, it defaults to the current preferred number of columns. If the text field's peer is not yet created, the resulting dimensions are (0, 0). On most platforms, the minimum and preferred dimensions are the same.
PARAMETERS cols A non-negative integer specifying the width in characters.
TextField
java.awt
getPreferredSize()
RETl’RNS A new non-nul 1 Dimension instance containing the minimum dimensions of the text field.
OVERRIDES Component.getMi ni mumSi ze().
EXAMPLE See lhe LayoutManager class example.
getPreferredSize()
PURPOSE Calculates the preferred dimensions of this text field.
SYNTAX public Dimension getPreferredSizeO public Dimension getPreferredSizefint cols)
DESCRIPTION The preferred dimensions of a text field are based on the dimensions needed for displaying one row of cols characters. The size of a character depends on the text field’s current font. If the text field's font has variable-width charac- ters, then col s is based on the average size of a character and the result is an approximation. The average width of a character is a platform dependent value. If cols is not specified, it defaults to the current preferred number of columns. If the text field's peer is not yet created, the resulting dimensions are (0, 0). On most platforms, the minimum and preferred dimensions are the same.
PARAMETERS cols A non-negative integer specifying the width in characters.
RE'I URNS A new non-null Dimension instance containing the preferred dimensions of the text field.
OVERRIDES Component .getPreferredSizeO.
EXAMPLE See the LayoutManager class example.
minimumSizeO оеш-апи
PURPOSE Replaced by getMinimumSizeO.
SYNTAX public Dimension minimumSizeO public Dimension minimumSizeOnt cols)
PARAMETERS cols A non-negative integer specifying the width in characters.
RETL’RNS A new non-null Dimension instance containing the minimum dimensions of the text field.
1462
pararnoui
OVERRIDES Component .minimumSizeO.
deprk a i ion Replace the usage of this deprecated method» as in
Dimension dim = textfield.minimumSizeO ; Dimension dim? = textfield.minimumSize(cols); with Dimension dim = textfield.getMinimumSizeO ; Dimension dim? - textfield.getMinimumSize(cols);
paramString()
PURPOSE Generates a siring representation of this text field's state.
SYNTAX protected String paramStringO
DESCRIPTION The string representation of a text field consists of the string representation of TextComponent and the echo character of this text field. A subclass of this class should override this method and return a concatenation of its state with the results of super.paramStringO- This method is called by the toStri ng О method and is typically used for debugging. A non-null string representing the text field s state.
OVERRIDES TextComponent .paramStringO.
SEE ALSO Component .paramStringO , Component. toStri ngO , j ava.1ang.Obj ect.toSt ri ng 0.
preferredSize() deprecated
PURPOSE Replaced by getPreferredSizeO.
SYNTAX public Dimension preferredSizeO public Dimension preferredSize(int cols)
PARAME'I ERS cols A non-negative integer specifying the width in characters.
RETl RNS A new non-null Dimension instance containing the preferred dimensions of the text field.
OVERRIDES Component.preferredSizeО.
DEPRECATION Replace the usage of this deprecated method, as in Dimension dim = textfield.preferredSize(); Dimension dim? = textfield.preferredSize(cols); with Dimension dim - textfield.getPreferredSizeO; Dimension dim? = textfield.getPreferredSizefcols);
TextField java.awt
processActionl: venl()
processActionEvent()
Pl RPOSL Processes an action event enabled for this text component.
SYNTAX protected void processActionEvent(ActionEvent evt)
DESCRIPTION /\ction events are fired when the user presses Return while in this text field. See the class description and ActionEvent for more details. This method pro- cesses action events for this text field by notifying registered ActionLis- tener. This method is invoked only if action events have been enabled for this text field. This can happen either when an action listener is added to this text field or when Component. enableEventsO is called to enable action events. Typically, a text field controls how its action events are processed by adding or removing action listeners. It overrides processActionEvent() only if it needs to do processing in addition to that performed by the registered listeners. When a subclass does override processActionEvent(). it should call super.processActionEventО to perform the processing intended by its base class (such as dispatching the listeners).
PARAMETERS evt The non-nul 1 action event.
SLL ALSO addActionListenerO » Component.enableFventsO , Component.di sableEvents(), j ava.awt.event.Acti onEvent, java.awt.event.ActionLi stener, processEventO » removeActi onLi stenerO.
EXAMPLE See AWTEventMulti caster. actionPerformedQ.
processEvent()
Pl RPOSE Processes an event enabled for this text component.
SYNTAX protected void processEventfAWTEvent evt)
DESCRIPTION This method extends TextComponent. processEventО by adding support for ActionEvent. It can be overridden to handle new types of events for this text field. When a subclass does override processEventO. it should call super.processEventO to perform the processing intended by its base class (such as dispatching events to the listeners).
PARAMETERS evt The event to be processed.
OVERRIDES TextComponent.processEventO-
SEE ALSO AWTEvent, processActionFvent().
EXAMPLE. See the Component class example.
1464
removeActi on Listen
remove ActionListener()
PURPOSE Removes a listener from receiving this text field's action events.
SYNTAX public synchronized void removeActionListener(ActionListener 1i stener)
DESCRIPTION Action events are fired when the user presses the Return key while in this text field. See ActionEvent and the class description for more details. After this method is called, the action listener listener will no longer receive action events from this text field. If 1 i stener is nul 1, this method does nothing.
PARAMETERS li stener The possibly null action listener to remove.
SEE ALSO addActionListener(), java.awt.event.ActionEvent, j ava.awt.event.Acti onLi stene r.
EXAMPLE See Menuitem.di sableEvent().
setColumns()
purpose Sets the number of columns in this text field.
syntax public void setColumns(int cols)
description I he preferred number of columns determines the text field’s preferred width
and does not limit the number of characters that can be entered in the text field.
See the class description for details.
PARAMETERS
col s The number of columns.
EXCEPTIONS
1I legalArgumentException
If col s < 0.
see also getCol umns ().
example See getColumnsO.
setEchoChar()
purpose Sets the text field’s echo character.
syntax public void setEchoChar(char ch)
java.awt
TextField
setEchoChar()
description This method sets the echo character of this text field to be the character ch. ch
can be any character and can be changed at any time. The value 0 is used to
clear the echo character. After the echo character is set to 0. the characters in
the text field will be visible and echoCharlsSetO will return true.
PAR A METERS
ch
SEE ALSO
EWMPI.F
The echo character. A value of 0 clears the echo character.
echoCharlsSetO , getEchoCharQ.
This example creates two text fields.
See Figure 367. In one text field, you
specify an echo character. In the
other, the echo character is used. If
you enter the same echo character
twice in a row, the echo character is
cleared.
setEchoCharactef Ex
| ???
^yoCtea^r:|~?
FIGI RF. 367: Changing the Echo
Character of a TextField.
import java.awt.*;
import java.awt.event.*;
class Main extends Frame {
TextField tf = new TextFieldO;
TextField tfEcho = new TextFieldO;
MainQ {
super(“setEchoChar Example”);
Panel p = new Panel();
p.setLayout(new Border! ayoutQ);
p.add(new Label("Echo Character:”), BorderLayout.WFST);
p.add(tfEcho, BorderLayout.CENTER);
// Add listener for echo char text field
tfEcho.addKeylistener(new KeyEventHandlerQ);
add(p, BorderLayout.SOUTH);
add(tf, BorderLayout.NORTH);
pack();
showO;
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
char key = evt.getKeyCharQ;
if (key == tf.getEchoCharQ) { // clear the echo char
key = 0;
t fEcho. setText(‘“‘) ;
} else {
tfEcho.setText(String.valueOf(key));
}
tf.setLchoChar(key);
tf. requestFocusO ;
1466
setEchoCharac
}
static public void mai n (Stri ng [] args) {
new Main();
}
}
setEchoCharacter() depreca ted
purpose: Replaced by setEchoCharQ.
SYNTAX public void setEchoCharacter(char ch)
PARA М1П ERS ch The echo character. Л value of 0 clears the echo character.
DEPRECA'I ION Replace the usage of this deprecated method, as in textfi eld.setEchoCharacter(ch); with textfield.setEchoChar(ch);
TextField() ._
PURPOSE: Creates a new TextField instance.
SYNTAX publ ic TextFieldO public TextField(int cols) public TextField(String text) public IextField(String text, int cols)
DESCRIPTION This constructor creates a new TextFi el d instance. If text is not specified or is null, it defaults to ‘Л cols specifies the preferred number of columns for the text field. See the class description for details. If cols is not specified, the default is chosen by the platform (usually wide enough to hold text if text has been specified). If both cols and text are specified, cols determines the preferred number of columns. If text does not fit within the width specified by col s. its Cail is not displayed and can be viewed using the right arrow key. The echo character is initially not set.
PARAMETERS col S A non-negative integer specifying the initial width in characters. See the class description for details.
text The string specifying the initial text for the text component. May be null.
see: ai so setColumns().
EX A MPL E See the class example.
java.awt.peer
TextFieldPeer
Л
в
c
Г)
e Syntax
P public interface TextFieldPeer extends TextComponentPeer
G ,
Description
H The text field component (see the TextField class) in the AWT uses the platform's native
1 implementation of a text field. So that the AWT text field behaves the same on all platforms,
the text field is assigned a peer, whose task is to translate the behavior of the platform's native
text field to the behavior of the AWT text field.
K AWT programmers normally do not directly use peer classes and interfaces. Instead, they
I deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with the peer classes and interfaces. Consequently, most peer documentation refers to
N java. awt counterparts.
o See Component and Tool ki t for additional information about component peers.
Q
R
S
IJ
V
w
X
< < f < J
Peer Methods
getMinimumSizeO Calculates the minimum dimensions of the text field.
getPreferredSizeO Calculates the preferred dimensions of the text field.
setEchoChar() Sets the text field's echo character.
Deprecated Methods
mi nimumSizeO Replaced by getMinimumSizeO.
preferredSizeO Replaced by getPreferredSi ze().
setEchoCharacterO i Replaced by setEchoChar().
Y
See Also
java.awt.Component, java.awt.TextField, java.awt.Toolkit.
1468
getMinimumS
getMinimumSize()
plrpose Calculates the minimum dimensions of the text field.
SYNTAX Dimension getMinimumSizefint cols)
parameters col s A non-negative integer specifying the width in characters.
RETI RNS The non-nul 1 minimum dimensions for the text field.
SEE Al50 java.awt.TextField.getMinimumSi ze().
getPreferredSize()
Pl RPOSE Calculates the preferred dimensions of the text field.
SYNTAX Dimension preferredSizefint cols)
PARAMETERS cols A non-negative integer specifying the width in characters.
RETI RNS l he non-nul 1 preferred dimensions for the text field.
SEE ALSO java.awt .TextFi eld. getPreferredSizeO.
minimumSize()
DEPRECATED
PURPOSE Replaced by getMinimumSizeО
SYNTAX Dimension minimumSize(int cols)
PARAMETERS cols A non-negative integer specifying the width in characters.
RETI RNS The non-null minimum dimensions for the text Held.
DEPRIX A HON Replace the usage of this deprecated method, as in Dimension min - peer.minimums!ze(cols); with Dimension min = peer.getMinimumS!ze(cols);.
TextFieldPeer
java.awt.peer
preferredSizef)
preferredSize()
DEPRECATED
A
В
c
D
e
F
G
PURPOSE Calculates the preferred dimensions of the text field.
SYNTAX Dimension preferredSize(int cols)
PARAMETERS
cols A non-negative integer specifying the width in characters.
RETURNS I’he non-nul 1 preferred dimensions for the text field.
DEPRECA'I ION Replace the usage of this deprecated method, as in Dimension pref = peer.preferredSizefcols); with Dimension pref - peer.getPreferredSizefcols);.
1 setEchoChar()
J purpose Sets the text field's echo character.
К svnia.x void setfchoCharfchar c)
I. PAR A METERS c The echo character. A \ alue of 0 clears the echo character.
M IN see also java.awt.1extFi eld.setEchoCharf).
() setEchoCharacter() deprecated
p
r n purpose Replaced by setEchoCharO.
V R S syntax void setEchoCharacter(char c) PARAMETERS c The echo character. A value of 0 clears the echo character. deprecation Replace the usage of this deprecated method, as in
U peer.setEchoCharacter(c);
V with peer.setEchoChar(c);
W
X
Y
Z
1470
I I ' ' к L « К 4 » • I „ X. ' V- I J I
TextListener
Syntax
public interface TextListener extends EventListener
Description
When an object (listener) wishes to receive text events from an object that fires them (the
source object), two things must be done:
1. The listener must implement the TextLi stener interface and the textVal ueChangedO
method it requires.
2. The listener must be registered with the source object by making a call to the source
object's addTextLi stenerO method.
For information about text events, see TextEvent.
In the AWT, the TextArea and TextField components fire text events.
MEMBER SUMMARY ’ ........... >
Text Event Callback Method
textVal ueChangedO Called when the contents of a text component changes.
TextListener
java.awt. event
See Also
java.awt.TextArea, java.awt.TextComponent, java.awt.TextFie1d,
java.util.EventListener, TextEvent.
A
В
F
G
H
1
J
К
L
M
N
()
P
Q
R
S
Example
Phis example implements a simple text
editor. For a simple example demonstrat-
ing text change events, see Figure 368.
The editor watches for any changes to
the text area. When a change is made, the
Save button is enabled. Also, the frame
removes itself from the text area's listener
list, since it is no longer interested in any
more text change events.
When the user clicks the Save button,
the file is saved and the Save button is dis-
abled. Also, the frame adds itself back
onto the text area's listener list, since it is
now interested in any changes lo the text
area.
For a simpler example, see TextEvent.
import java.awt.-';
import java.awt.event.-';
import java.io.*;
я TextListener Example ВЕЭЕЗ
// Simple Text Editor
class Main extends Frame impleme
String filename;
Button saveButton = new Butt
TextArea textArea = new Text
Main(S tring f11ename) {
super("TextListener Exan
±1_____________I
Save
FIGI RE 368: Simple Editor.
class Main extends Frame implements TextListener, ActionListener {
String filename;
Button saveButton = new Button("Save");
TextArea textArea = new TextAreaQ;
Main(String filename) {
super("TextListener Example");
this.fi1 ename = filename;
U
V
w
X
Y
Z
try {
chart] buffer = new char[1024];
int count = 0;
FileReader rd = new Fi1 eReader(fi1 ename);
// Read in the contents of the file
// and append them to the text area.
while ((count = rd.read(buffer, 0, 1024)) != -1) {
textArea.append(new String(buffer, 0, count));
}
rd.close();
} catch (Exception e) {
System.err.println("Could not open: " + filename);
System.exi t(1);
}
1472
П Listen for events.
textArea.addTextLi stener(this);
saveButton.addActionLi stener(t hi s) ;
saveButton.setEnabled(fal se);
// Layout components.
addCtextArea, BorderLayout.CENTER);
add(saveButton, BorderLayout.SOUTH);
setFont(new FontC'Monospaced", Font.PLAIN, 12));
pack();
show();
}
// Handler for text events.
public void textValueChanged(TextEvent evt) {
// No need to listen for more text change events
// so remove from listener list.
textArea.remove!extLi stener(thi s);
saveButton.setEnabled(true);
}
// Handler for action events.
public void actionPerformed(ActionEvent evt) {
// Listen for text change events again.
textArea.addTextl istener(this);
saveButton.setEnabled(false);
// Now save the changes back to the file.
try {
FileWriter wr = new FileWriter(fi1 ename);
String contents = textArea. getTextO;
wr.write(contents, 0, contents.length());
wr.close();
} catch (Exception e) {
System.err.print In(”Could not save: “ + filename);
}
}
public static void main(String argsU) {
if (args.length '= 1) {
System.err.println("Usage: java 4ain <filename>”);
System.exi t(l);
}
new Main(args[0]);
}
java.awt.cvent
lextListener
text Val ueChanged()
textVal ueChangedO
pcRBOsr. Called w hen the contents of a text component changes.
syntax public void textValueChanged(TextEvent evt)
Л description This method is called whenever the contents of the source text component
В changes.
C
D
E
F
PARAMET ERS
evt The non-null text event.
see also java.awt.TextComponent, TextEvent.
exampl i See lhe class example.
G
H
I
J
К
L
M
N
О
P
Q
R
S
U
V
X
Y
Z
1474
Toolkit
Syntax
public abstract class Toolkit
Description
This class is used to create platfonn-specific peers and to perform other global functions, such
as retrieving the screen resolution, creating a print job object for printing, and reading AWT-
specific properties.
Creating Peers
PanelPeer
TextAreaPeer
ButtonPeer
ButtonPeer
।
FIGI RE 369: A Component Hierarchy and Its Corresponding Peer Class Hierarchy.
A component, such as a button, in the AWT uses the platform’s native implementation of
a button. For example, on Solaris, the AWT button uses the Motif button widget, while in
Windows 95, the AWT button uses the button control. So that the AWT button component
behaves the same on all platforms, the button is assigned a peer (see Component), whose task
is to translate the behavior of the platform's native button to the behavior of the AWT’ button.
Each platform has its own complete set of peers to match each of the AWT components.
The purpose of the abstract class Toolkit is to deliver the correct set of peers that are appro-
priate for the current platform. For example, when an AWT’ button object needs a button peer,
it calls getDefaultToolkitО to retrieve an instance of this class and then uses that instance
to create a button peer.
There is only one instance of the Tool kit class in existence at any time. That instance is
created with the first call to getDefaul tTool ki t(). Each platform has an implementation of
this class. The awt. toolkit system property is used to determine the instance of the toolkit to
Toolkit
java.awt
create. The awt. tool ki t system property names the class to create (the class must, of course,
be a subclass of Toolkit).
Most of the peer creation methods in this class are not typically used directly by AWT pro-
grammers. since they are indirectly available through other classes.
A
В
C
D
ti
F
G
К
I
J
К
M
N
О
P
Q
R
S
u
V
w
X
Y
Z
SUMMARY _
Initialization Method
getDefaultToolki t() Retrieves the Toolkit instance to use when creating component peers.
Peer Methods
createButtonQ Creates a button peer.
createCanvas() Creates a canvas peer.
createCheckboxO Creates a checkbox peer.
createCheckboxMenultem() Creates a checkbox menu item peer.
createChoi ceO (Yeates a choice peer.
createComponentO Creates a lightweight peer for a component or a container.
createDi alog() Creates a dialog peer.
createFileDialogО Creates a file dialog peer
createFrameO Creates a frame peer.
createLabelО Creates a label peer.
createListO Creates a list peer.
createMenuf) Creates a menu peer.
1 createMenuBar() Creates a menu bar peer.
createMenuItemO Creates a menu item peer.
createPanel() Creates a panel peer.
createPopupMenuO Creates a popup menu peer.
createScrollbarO Creates a scrollbar peer.
createScrol 1 PaneO Creates a scrollpane peer.
i createTextAreaO Creates a text area peer.
createTextFi eld() Creates a text field peer.
createWindowO Creates a window peer.
Color Methods
getColorModel() Retrieves the color model for the screen.
1oadSys temColо rs О Loads current system colors into an array.
Event Methods
getMenuShortcutKeyMaskO Retrieves the event modifier mask used for menu short- cuts.
getSystemEventQueueQ Retrieves lhe event queue for this application or applet.
getSystemEventQueuelmpl() Retrieves the event queue for this application or applet.
1476
MEMBER SUMMARY
Font Methods getFontLi st() ; getFontPeerO getFontMetri csQ Retrieves a list of the names of all available AWT fonts. Creates the font peer for a font. < Retrieves the font metrics for a font.
Image Methods checklmageO createlmageO Retrieves the construction status of an image. Creates an image using image data supplied by an image producer.
getlmageQ preparelmageO Retrieves an image from a tile or URL. Triggers the loading of image data for an image.
; Print Method getPri ntJobO Screen Methods getScreenResolution() : getScreenSize() sync() Creates a new PrintJob instance. Retrieves the resolution of the screen. Retrieves the size of the screen. blushes any pending operations on active graphics con- texts.
System-wide Methods beepO getNati veContai nerQ getPropertyO getSystemCl i pboardO j Emits an audio “beep/* Retrieves the native container of a component. Retrieves a property from the awt .properties list. Retrieves the system clipboard.
Example
This example creates a frame and centers il on the
screen. See Figure 370. The frame also displays
the screen resolution and an estimate of the size of
the screen based on the screen size and resolution.
Toolkit Example
screen resolution = 96
screen width = 13.333333333333334"
screen height = 10.666666666666666
import java.awt.*;
- f FIG IKE 370: Centering a Frame on the
class Main extends Frame { *
MainO { Screen-
super(“Toolkit Fxample”);
Dimension d;
d = Tool kit.getDefaul tTool ki t() getScreenSizeO ;
setSize(225, 100);
setLocati on ((d .width-getBoundsO .width)/2 ,
(d. height-getBoundsO . height)/2) ;
showO;
Toolkit
java.awt
beep()
public void paintCGraphics g) {
FontMetrics fm = g.getFontMetrics() ;
int resol = Tool ki t.getDefaul tTool ki t() . getScreenResol ut ionQ ;
Dimension d = Toolkit.getDefaultToolkit().getScreenSizeO;
A Insets insets = getlnsetsO;
int x = insets.left;
В int у = insets.top + fm.getAscentO;
C g.drawString(“screen resolution = “+resol , x, y);
у += fm.getHeightO ;
D g.drawString(“screen width = “
+ ((double)d.width/resol) + “ x, y) ;
Г у += fm.getHeightO;
g.drawString(“screen height = “
F 4 ((double)d.height/resol) 4- “ x, y) ;
}
G
public static void main(String[] args) {
H new MainO ;
}
I }
К
L
M
N
()
P
Q
R
S
u
V
w
X
Y
Z
beep()
purpose Emits an audio “beep."
syntax public abstract void beepO
example This example creates a button that, when
pushed, emits an audio “beep.” See Figure
371.
FIGURE 371: Beeping Button.
import java.awt.*;
import java.awt.event. * ;
class Main extends Frame implements ActionListener {
MainO {
super(“Tool ki t. beepO Example”) ;
Button b = new Button(“Beep”);
add(b, BorderLayout.CENTER);
b.addActionListener(this) ;
packO ;
showO ;
}
public void actionPerformed(ActionEvent evt) {
Tool kit. getDefaul tTool ki t О . beepO ;
}
public static void main(String[] args) {
new MainO;
}
}
1478
check Im:
checklmage()
pc rpose: Retrieves the construction status of an image.
SYNTAX public abstract int checklmage(Image image, int width, int height, ImageObserver obs)
DESC Rl PHON See Component .checklmageO for a complete description of this method.
PARAMETERS height image obs If >- 0. specifies the height of the scaled version of the image to check. The non-null image to check. If non-null, specifies the image observer to be notified whenever the status changes.
wi dth If >= 0, specifies the width of the scaled version of the image to check.
REIT RNS The combination of status bits as denned by the ImageObserver interface.
SE:E ALSO Component. checklmageO.
EXAMPLE See Component .checklmageO.
createButton()
PURPOSE Creates a button peer.
SYNTAX protected abstract ButtonPeer createButtonfButton target)
DESCRIPTION This method is called by Button.addNotifyO as the peers for a component hierarchy are created. For a complete description of the behavior of the button peer, see the Button class.
PARAMETERS target The non-null AWT button requiring a button peer.
RETI'RNS A button peer for lhe AWT button target.
sei: also Button.
createCanvas()
Pl’RPOSE; Creates a canvas peer.
SYNTAX protected abstract CanvasPeer createCanvas(Canvas target)
I>E:SCR[Fyl ION This method is called by Canvas.addNotifyO as the peers for a component hierarchy are created. For a complete description of the behavior of lhe canvas peer, see the Canvas class.
Toolkit
createCheckbox()
java.awt
PARAMETERS
target The non-nul 1 AWT canvas requiring a canvas peen
returns A canvas peer for the AWT canvas target.
Л SEE ALSO Canvas.
в c createCheckbox()
D PERPOSE Creates a checkbox peer.
E SYNTAX protected abstract CheckboxPeer createCheckbox(Checkbox target)
E DESCRIPTION This method is called by Checkbox. addNoti fyO as ihe peers for a compo-
Ci nent hierarchy are created. For a complete description of ihe behavior of the
H checkbox peen see the Checkbox class.
1 PARAMETERS target The non-nul 1 AWT checkbox requiring a checkbox peer.
J RETURNS A checkbox peer for the AWT checkbox target.
К SEE Al.SO Checkbox.
L M N () createCheckboxMenuItemf)
Pl RPOSE Creates a checkbox menu item peen
p SYNTAX protected abstract CheckboxMenultemPeer
Q DIuSCRI PTION createCheckboxMenu!tem(CheckboxMenuItem target) This method is called by CheckboxMenuItem. addNotifyO as ihe peers fora
R component hierarchy are created. For a complete description of the behavior of
S the checkbox menu item peen see the CheckboxMenuItem class.
PARAMETERS target The non-null AWT checkbox menu item requiring a checkbox menu item
L< peer.
V REH RNS A checkbox menu item peer for the AWT checkbox menu item target.
w X SEE ALSO CheckboxMenuItem.
Y createChoice()
Z PI RPOSE Creates a choice peen
1480
createi.omponc
SYNTAX protected abstract ChoicePeer createChoicefChoice target)
DESCRIPTION This method is called by Choice.addNotifу() as the peers for a component hierarchy are created. For a complete description of the behavior of the choice peer, see the Choice class.
parameters target The non-nul 1 AWT choice requiring a choice peer.
RETURNS A choice peer for the AWT choice target.
SEE ALSO Choice.
createComponent()
PURPOSE Creates a peer for a lightweight component.
SYNIAX protected abstract LightweightPeer createComponentfComponent target)
DESCRIPTION This method is called by Component .addNotifyO as the peers for a compo- nent hierarchy arc created. A lightweight component is a component that does not have a corresponding peer in the window system. Instead, it has a peer rep- resented entirely in Java. For a complete description of the behavior of light- weight components, see the Component class.
PARAMETERS target l he non-null AWT component or container requiring a peer.
RETURNS Л lightweight peer for the AWT component.
SEE Al.SO Component.
createDialog()
PURPOSE Creates a dialog peer.
SYNTAX protected abstract DialogPeer createDialog(Dialog target)
DESCRIPTION This method is called by Dialog.addNotify() as the peers for a component hierarchy are created. For a complete description of the behavior of the dialog peer, see the Dialog class.
PARAME'J ERS target RETURNS The non-null AWT dialog requiring a dialog peer. A dialog peer for the AWT dialog target.
SEE ALSO Dialog.
Toolkit
create! ileDialog()
java.awt
createFileDialog()
Pl RPOSE Creates a file dialog peer.
SYNTAX protected abstract FileDialogPeer createFileDialogfFileDialog target)
DESCRIPTION This method is called by FileDialog.addNotifyO as the peers for a com- ponent hierarchy are created. For a complete description of the behavior of the file dialog peer, see the FileDialog class.
PARAMETERS target The non-nul 1 /\WT file dialog requiring a file dialog peer.
RETI RNS /X file dialog peer for the AWT file dialog target.
SEE, Ai S() FileDialog.
createFrame()
PERPOSE Creates a frame peer.
SYNIAX protected abstract FramePeer createFrame(Frame target)
DESCRIPTION This method is called by Frame.addNotify() as the peers for a component hierarchy are created. For a complete description of the behavior of lhe frame peer, see the Frame class.
PARAMETERS target The non-null AWT frame requiring a frame peer.
RETI RNS A frame peer for the AWT frame target.
SEE ALSO F rame.
createlmage()
Pl RPOSE Creates an image.
SYNIAX public abstract Image createlmage(ImageProducer producer) public abstract Image createlmage(byte[] imageData) public abstract Image createlmage(byte[] imageData, int offset, int count)
DESCRIPTION The first form of this method creates an image based on the image data gener- ated by the image producer producer. When the method returns, it does not contain any image information. The production of image information must be triggered by calling either preparelmageO or Graphics.drawImageO-
1482
create Lal
Since the image is not loaded before this method returns, the image may become invalid later (when an error is eventually encountered). See the Image class description for more information about the asynchronous loading of image data. The second and third forms of this method create an image using count num ber of bytes stored in an array i mageData, starting at index offset. If offset and count are not specified, the entire byte array is used. The data in Image- Data must be in a format supported by lhe toolkit. The currently supported for- mats include GIF and JPEG.
PARAMETERS count 1mageData offset producer The number of bytes to use. Fhe byte array containing the image. The index in imageData at which to start getting the image data. The non-null image producer.
RETURNS A reference to a new image, null may be returned if the producer is not valid.
SEE ALSO Image, java.awt,image.ImageProducer.
example: See Component.createlmage().
createLabel()
PURPOSE Creates a label peer.
SYNTAX protected abstract Label Peer createLabel(Label target)
DESCRIPTION This method is called by Label .addNotifyO as the peers for a component hierarchy are created. For a complete description of the behavior of the label peer, see the Label class.
PARAMETERS target The non-null AWT label requiring a label peer.
RETURNS A label peer for the AWT label target.
SEE At.SO L abel.
createList()
Pl.RPOSE Creates a list peer.
SYNTAX protected abstract ListPeer createList(List target)
Toolkit
java.awt
createMenu()
DESCRIPTION Phis method is called by Li st. addNoti fy О as the peers for a component hierarchy are created. For a complete description of the behavior of the list peer, see the Li st class.
PARAMETERS target The non-null AWT list requiring a list peer.
RETURNS A list peer for the AWT list target.
SEE ALSO List.
PURPOSE Creates a menu peer.
SYNIAX protected abstract MenuPeer createMenu(Menu target)
DESCRIPTION This method is called by Menu.addNotify() as the peers for a component hierarchy are created. For a complete description of the behavior of the menu peer, see the Menu class.
PARAMETERS target The non-null AWT menu requiring a menu peer.
RETURNS menu peer for the AWT menu target.
SEE ALSO Menu.
createMenuBar()
Pl RPOSE Creates a menu bar peer.
SYNlAX protected abstract MenuBarPeer createMenuBar(MenuBar target)
DESCRIPTION This method is called by MenuBar .addNoti fy() as the peers for a component hierarchy are created. For a complete description of the behavior of the menu bar peer, see the MenuBar class.
PARAMETERS target The non-null AWT menu bar requiring a menu bar peer.
RETURNS A menu bar peer for lhe AWT menu bar target.
SEE ALSO MenuBar.
1484
create Menu lie
PURPOSE Creates a menu item peer.
SYNTAX protected abstract MenuItemPeer createMenuItem(MenuItem target)
DESCRIPTION This method is called by Menuitem.addNotify() as the peers for a compo- nent hierarchy are created. For a complete description of lhe behavior of the menu item peer, see the Menu Item class.
PARAMI* I ERS target The non-null AWT menu item requiring a menu item peer.
RETURNS A menu item peer for the AWT menu item target.
sei: ALSO Menuitem.
PURPOSE Creates a panel peer.
SYNTAX protected abstract Panel Peer createPanel(Panel target)
DESCRIPTION This method is called by Panel .addNotifyO as the peers for a component hierarchy are created. For a complete description of the behavior of the panel peer, see the Panel class.
PARAMETERS target T he non-null AWT panel requiring a panel peer.
RETI RNS A panel peer for the AWT panel target.
SEI- Al SO Panel.
createPopupMenu()
PURPOSE Creates a popup menu peer.
SYNTAX protected abstract PopupMenuPeer createPopupMenu(PopupMenu target)
DESCRIPT ION- This method is called by PopupMenu .addNotifyO as the peers for a compo- nent hierarchy are created. For a complete description of the behavior of the popup menu peer, see the PopupMenu class.
PARAMETERS target The non-nul 1 AWT popup menu requiring a popup menu peer.
RETURNS A popup menu peer for the AWT' popup menu target.
SEI ALSO PopupMenu.
Toolkit
createScrollbarf)
java.awt
createScrollbar()
PURPOSE Creates a scrollbar peer.
SYNTAX protected abstract Scrol 1 barPeer createScrollbar(Scrollbar target)
DESCRIPTION This method is called by Scrol Ibar. addNotifyO as the peers for a compo- nent hierarchy are created. For a complete description of the behavior of the scrollbar peer, see the Scrol 1 bar class.
PARAMETERS target The non-nul 1 AWT scrollbar requiring a scrollbar peer.
RETURNS Л scrollbar peer for the AWT scroll bar target.
SEE ALSO Scrol Ibar.
createScrollPane()
Pt RPOSE Creates a scrollpane peer.
SYNTAX protected abstract Scrol1PanePeer createScrol1pane(Scrol1 Pane target)
DESCRIPTION This method is called by Scroll Pane.addNotifyO as the peers for a com- ponent hierarchy are created. For a complete description of the behavior of the scroll pane peer, see the Scroll Pane class.
PARAMETERS target The non-null AWT scroll pane requiring a scroll pane peer.
RETURNS A scroll pane peer for the AWT scroll pane target.
SEL /ALSO ScrollPane.
createTextArea()
purpose: Creates a text area peer.
SYNTAX protected abstract TextAreaPeer createtextArea(TextArea target)
DESCRIPTION This method is called by TextArea.addNotify() as the peers for a compo- nent hierarchy are created. For a complete description of the behaxior of the text area peer, see the TextArea class.
PARAMETERS target The non-nul 1 AWT text area requiring a text area peer.
I486
create lextHc
RETURNS Л text area peer for the AWT text area target.
SEE ALSO TextArea.
createTextField()
PURPOSE Creates a text field peer.
SYNTAX protected abstract TextFieldPeer createTextField(TextField target)
DESCRIPTION This method is called by TextField. addNotifyO as the peers for a compo- nent hierarchy are created. For a complete description of the behavior of the text field peen see the TextFi eld class.
PARAMETERS target The non-null AWT text field requiring a text field peer.
RETURNS A text field peer for the AWT text field target.
SEE ALSO TextField.
createWindow()
PURPOSE Creates a window peer.
SYNTAX protected abstract WindowPeer createWindowfWindow target)
DESCRIPTION This is called by Window.addNotifyO as the peers for a component hierar- chy are created. For a complete description of the behavior of the window peer, see the Wi ndow class.
PARAMETERS target The non-null AWT window requiring a window peer.
RETURNS A window peer for the AWT window target.
SEE ALSO Wi ndow.
getColorModel()
PURPOSE Retrieves the color model for the screen.
SYNTAX public abstract ColorModel getColorModel()
RETI RNS The non-null color model of the screen.
SEE ALSO ColorModel.
EXAMPLE See ColorModel for an example that displays the colors in the screen’s color table.
Toolkit gecDefaulflbolkiU) java.awt
getDefaultTooikit()
Pl RPOSE Retrieves the Tool ki t instance io use when creating component peers.
SYNIAX public static synchronized Toolkit getDefaultToolkit()
DESCRIPTION The first time this method is called. getDefaultToolkitО reads lhe awt. tool kit system property to determine which version of rhe Toolkit to create. The toolkit instance is created only once and cannot be replaced.
RETl’RNS The non-nul 1 toolkit instance.
EXCEPTIONS AWTError If the toolkit could nor be created.
EXAM PLE See lhe class example.
getFontList()
РГ RPOSE Retrieves a list of the names of all available AWT fonts.
SYNTAX public abstract StringLJ getFontList()
DESCRIPTION See Font's class description for list of currently supported fonts. T he returned list should not be modified.
RE II RNS A non-null list of all available AWT font names.
SEE ALSO Font.
EXAMPLE See the Font class.
getFontMetrics()
PLRtXJSE Retrieves the font metrics for a font.
SYNIAX public abstract FontMetrics getFontMetricsfFont font)
DESCRIPTION This method retrieves the font metrics for the font font.
PARAMEIERS font The non-nul 1 font.
RFIIRSS The non-null font metrics for font.
SEE ALSO FontMetri cs. Graphi cs.getFontMetri cs().
1488
getFontPeer()
PURPOSE Creates the font peer for a font.
SYNTAX protected abstract FontPeer getFontPeer(String fontName, int style)
DESCRIPTION This method creates the font peer for the font with the logical font name font- Name and the font style style.
PARAMETERS fontName style The non-null logical font name (e.g., "Serif’ or ‘'Monospaced”). Bits specifying the font's style. It is a mask constructed using Font.ITALIC Font.PLAIN, and Font.BOLD.
RETURNS The non-nul 1 font peer for the specified font.
SEE ALSO FontMetrics, Graphics.getFontMetrics().
getlmage()
PURPOSE Creates an image from a tile or URL.
SYNTAX public abstract Image getImage(String filename) public abstract Image getImage(URL url)
DESCRIPTION The two forms of (his method return a reference to an Image object. The pixels contained in the file filename or at the URL url are not immedi- ately loaded into the image. To start the loading of the pixel data, call Component.preparelmageO or Graphics.drawlmage(). Since the image is not loaded before this method returns, the image may become invalid later (when an error is eventually encountered). See the Image class description for more information about the asynchronous loading of image data.
PARAMETERS filename url The non-null string specifying the file that contains the image. The non-nul 1 URL specifying the location of the image.
RETURNS Л reference to the image that will eventually contain (he pixel data, null is relumed if fi 1 ename or url is invalid.
SEE ALSO Image, java.net.URL.
Toolkit
getlmage()
java.aw l
example This example demonstrates how
a URL can be derived from a
pathname and then be used to
load an image. See Figure 372.
I'he program creates a frame and
a canvas in which to displav the
image. The image is scaled to
the size of the canvas.
import java.awt.'-;
import java.net.'';
class Main extends Frame {
Main(String filename) {
super(“getlmage Example");
try {
// Retrieve the image.
URL url = new URL(“fi 1 e :///’’
I IGl Rl 372: Loading an linage I sing a URL.
System.getProperty(“user.dir")
+ “/" + fi1 ename);
Image urllmage = getToolkit().getlmage(url);
add(new ImageCanvas(url Image), BorderLayout.CENlf-R) ;
} catch (Exception e) {
e.pri ntStackTrace() ;
}
setSize(50, 100);
show();
}
static public void main(String[] args) {
if (args.length == 1) {
new Mai n(args[0]);
} else {
System.err.println(“usage: java Main <image file>”);
}
}
}
class ImageCanvas extends Component {
Image image;
ImageCanvas(Image image) {
this.image = image;
}
public void paint(Craphics g) {
update(g);
}
public void update(Graphics g) {
g.drawlmage(image, 0, 0, getSize().width, getSize().height, this):
}
}
1490
gei .vi en uo n one* u 1ivi <i
getMenuShortcutKeyMask()
Pl RPOSE Retrieves the event modifier mask to use for menu shortcuts.
SYNTAX public int getMenuShortcutKeyMaskO
DESCRIPTION This method defines the event modifier mask to use for menu shortcuts. The default value returned is InputEvent.CTRL_MASK. A toolkit should override this method if it uses another modifier for menu shortcuts.
REH RNS The event modifier mask for menu shortcuts.
SEE ALSO AWTEvent, java.awt.event.InputEvent, MenuShortcut.
getNativeContainer()
PURPOSE Retrieves the native container of a component.
SYNTAX protected static Container getNativeContainer(Component component)
DESCRIPTION T he immediate container of a component may not be a native component. The container might have a lightweight peer instead. This method allows a pro- gram to find the first container of the component component that has a native peer traversing up its container hierarchy.
PARAMETERS component fhe component whose native container to obtain.
REIT RNS SEE ALSO The native container that contains component. Container.
getPrintJob()
pirpose Creates a new Printjob instance.
symax public abstract Printjob getPrintJob(Frame frame, String title,
Properties props)
desc ription This method creates and returns a new PrintJob instance. Calling this method
causes a modal dialog to appear. The dialog displays lhe printer options from
which the user can choose. Until the user dismisses the dialog, this method
does not return.
The frame parameter is ignored.
The title parameter is printed on any header pages that the printer prints.
Toolkit
getPropertyf)
java.awt
If props is not null, it will be filled with the various printer options that the
user has chosen. Nnre: In Java 1.1.2, the props parameter is ignored.
PARAMETERS
frame The possibly null frame from which the print job was initiated.
props The possibly nul 1 properties associated with the print job.
В ti tl e The possibly nul 1 title of the print job.
C rftlrns A possibly nul 1 PrintJob instance.
D SEEALSO Pri nt lob.
E example See the Pri nt Job class example.
I
Ci getProperty()
tl purpose Retrieves a property from the awt. properti es list.
1 svstax public static String getProperty(String key» String defaultvalue)
J desc ription Visible strings used by the AWT are stored in the awt.properties property
К list in the lib subdirectory in which Java is installed (i.e., in the file $JAVA-
L HOME/lib/awt.properties). This method retrieves the value associated
M N with the property key. If key is not found in awt.properties, default- Val ue is returned. PARAMETERS
О defaultValueThe default value to return if key is not in the awt .properties list.
P key The name of the property to retrieve.
Q R reil rns The value associated with key in the awt.properties set; defaultValue if key is not found. seealso java.lang.System.getPropertyf) , java, uti 1. Properties.
S example This example displays the textual representation of a function key.
U void PrintFunctionKey(int fkey) { switch(fkey) {
V case VK_F1: System.out.Print(Toolkit.getProperty(“AWT.fl”, “Fl”));
w break; case VK_F2:
X System.out. PrintCToolki t .getProperty(”AWT.f2'1, “F2”)); break;
1492
getScreenResoluti
getScreenResolution()
Pl RPOSE Retrieves the resolution of the screen.
SYNTAX public abstract int getScreenResolution()
DESCRIPTION Dividing the screen size by the screen resolution should yield the physical size of the screen.
RETl RNS The resolution of the screen in dots-per-inch.
example: See the class example.
getScreenSize()
PURPOSE Retrieves the size of the screen.
SYNTAX public abstract Dimension getScreenSize()
RETURNS The non-nul 1 dimensions of the screen in pixels.
EXAMPLE See the class example.
getSystemClipboardf)
PURPOSE Retrieves the system clipboard.
SYNTAX public abstract Clipboard getSystemClipboardQ
DESCRIPTION The system clipboard allows data to be transferred between Java programs and native programs.
RETURNS The system clipboard.
see: ALSO java.awt.datatransfer.Clipboard.
EXAMPLE See the Cl i pboard class example.
getSystemEventQueue()
purpose: Retrieves the event queue of this application or applet.
SYNTAX public final EventQueue getSystemEventQueue()
DESCRIPTION Using the system event queue, you can add events to the queue to be processed later. (Contrast this with Component .di spatchEventO, which dispatches the event synchronously akjflp^jjon
java.awt
Toolkit
getSystemEventQueueImpl()
Depending on the toolkit implementation, applets running on the same virtual machine may not necessarily share the same system event queue. The system event queue can be obtained only if allowed to do so by the security manager in place.
RETURNS The non-nul 1 event queue for this application or applet.
EXCEPTIONS
Securi tyExcepti on
If not allowed to access the application or applet's system event queue.
SHE ALSO AWTEvent, EventQueue, getSystemEventQueuelmpl(), j ava.lang.Secu ri tyManager.checkAwtEventQueueAccess О -
EXAMPLE See the java.awt. peer .Acti veEvent class example and the AWTEvent class example.
getSystemEventQueuelmpH)
PURPOSE Retrieves the event queue of this application or applet.
SYNTAX protected abstract EventQueue getSystemEventQueuelmpl ()
DESCRIPTION A toolkit provides an implementation for this method, which is used by get- SystemEventQueueO. Depending on the toolkit implementation, applets running on the same virtual machine may not necessarily share the same event queue.
RETURNS The event queue for this application or applet.
SEE ALSO EventQueue, getSystemEventQueue().
loadSystemColorsf)
PURPOSE Retrieves the current system colors into an array.
SYNTAX protected void loadSystemColorsfintf] systemcolors)
DESCRIPTION This method loads the array systemcolors with the system colors. Each entry in the array represents a particular system color (the background color for scrollbars, the background color for the menu text, and so on). Each value in the array is the RGB value of the color.
PARAMETERS
systemcolors A preallocated array to store the system color values. It must have at least
SystemColor.NUM_COLORS elements.
SEE ALSO SystemColor.
1494
prepareJma
preparelmage()
PURPOSE Triggers the loading of image data for an image.
SYNTAX public abstract boolean preparelmageflmage image, int width, int height, ImageObserver observer)
DESCRIPTION This method starts the loading or production of image data associated with image image or a scaled version of image. If width and height are -1, no scaling of image is done. If width and height are non-negative, they specify that image should not only be loaded, but also scaled so that its width is width and its height is height. T'his method is typically used to preload image data for an image or a scaled version of an image so (hat Graphi cs. drawlmage0 can operate as quickly as possible.
PARAMETERS height image observer w i d th 1 or the scaled height of the returned image. The non-null image to load. The non-null image observer. <L or the scaled width of the returned image-
RETl RNS true if all of the image data for image is available: false otherwise.
SEE ALSO Component.checkimage 0 •
EXAMPLE See Component.checkimage().
sync()
PURPOSE Flushes any pending operations on active graphics contexts.
SYNTAX public abstract void sync()
DESCRIPTION This method is useful on platforms that batch painting calls to a graphics con- text. It currently is not used.
SEEALSO Graphics.
java. awt. datatransfer
Transferable
A
B Syntax
C public interface Transferable
D
Description
When an application wants to place data on a clipboard, it must first encapsulate the data in an
object that implements the Transferable interface. Similarly, when an application retrieves
G the contents of a clipboard, it is given a transferable object that it must use to retrieve the
encapsulated data.
A transferable object provides several features:
1 I. It can contain any type of data: an image, a string, a bean, and so on. Through the use of
J data flavors (sec DataFlavor), it allows an application to determine exactly what is
K encapsulated by the transferable object.
2. It can support the delivery of the encapsulated data in different ways. For example, if lhe
L transferable object contains a JPEG image, it may support the deliver}' of the image as an
M Image object, as a byte stream, or as an array of pixels. An application decides how it
wants the data delivered through the use of data flavors (see DataFl avor).
3. It does not necessarily have to contain the actual data, only a reference to that data. For
° example, an application may display a list of files containing images. When one of those
p image files is copied onto a clipboard, it does not have to provide the image pixels. When
some other application finally requests lhe data, the application reads the pixels from the
file and delivers them.
R Note: Transferable objects will play a role in drag-and-drop when it becomes available in a
s future release.
Supported Data Flavors
A transferable object must be able to supply a list of all data flavors that it supports, 'litis
allows an application to go through the list of data flavors looking for a data flavor that it can
v use to retrieve the encapsulated data. Alternatively, an application can simply try to retrieve
W the data with a data flavor and see if the transferable object w ill grant or reject the request.
X
Y
Z
1496
MEMBER SUMMARY
Data Method
getT ransferDataQ
Data Flavor Methods
getTransferDataFl avorsO
i sDataFlavorSupported О
Retrieves the data encapsulated in this transferable object.
Returns an array of data flavors that this transferable object
supports.
Determines whether this object supports a particular data
flavor.
See Also
Cl ipboard, DataFlavor.
Example
This example demonstrates how one could exchange images on a clipboard. Since the system
clipboard does not support images, the example uses a private clipboard. The example creates
an image paleae—a frame containing a number of images (see the “Copy" frame in Figure
373). Clicking one of the images causes that image to be highlighted and placed on the private
clipboard. The highlight is drawm only if the image is still in the clipboard; if the clipboard no
longer contains the image, the highlight is removed.
The other frame (the “Paste" frame in Figure 373) can copy the highlighted image shown
on the image palette. This is done by the user’s choosing the Copy menu item from the Edit
menu. The copied image is displayed in the frame’s display area.
The Edit menu also contains a Clear Clipboard command, which simply sets an empty
string in the clipboard. T his is used to test that the current image in the image palette loses its
highlight.
Paste
FIGLRE 373: Copy and Paste Using Transferable.
Transferable
java.awLdalatransfer
import java.awt.*;
import java.awt.datatransfer.;
import java.awt.event. *;
import java.io.*;
class Vain extends Frame implements Actionlistener {
static Clipboard mainClipboard - new Clipboard("Main Clipboard");
Image currentTmage;
Main() {
super("Transferable Example”);
MenuBar mb - new MenuBarO;
Menu m = new MenuC'Edi t”) ;
m.add("Paste”);
m. addC’Clear Clipboard"):
m.addActionLi stener(thi s);
mb.add(m);
setMenuBar(mb);
setSize(100, 150);
showO;
}
public static void main(String[] args) {
new Main();
Frame f = new Frame("Image Palette”);
f.add(new ImagePalette(), BorderLayout.CENTER);
f,pack();
f. showO ;
}
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommandO.equals(’Paste”)) {
// Get the image in the clipboard.
Transferable t =- mainClipboard.getContents(this) ;
try {
if (t !-= null) {
Currentimage = (Image)t.getTransferData(
ImageSelection.imageFlavor);
repaint();
}
} catch (lOException e) {
} catch (UnsupportedFlavorException e) {
}
} else {
// Clear Clipboard
mainClipboard.setContents(nul1, nul1);
}
repai nt();
}
public void paint(Graphics g) {
if (currentimage '= null) {
g.drawlmage(currentlmage, getlnsetsO.left, getlnsetsO.top, this);
}
// All containers must call super.paintO in case
1498
// it contains lightweight components,
super.pai nt(g):
}
}
class ImagePalette extends Component implements ClipboardOwner {
// If >= 0, points the currently selected image.
int curlmage • 1;
// This field holds all the images.
Image imagesfl = new ImageГ4];
// This field holds the bounds for each image.
Rectangle rects[] = new Rectangle[4];
ImagePaletteO {
MediaTracker tracker new MediaTracker(this);
// Use a media tracker because we need to know the
// dimensions of the images immediately.
for (int i=0; i<images.length; i++) {
images[i] getToolki t () .getlirage(,,duke,,+i-t-" .gi f") ;
tracker.addlmage(images[i]r 0);
}
try {
// Wait for images to load,
tracker.waitForAllО;
} catch (Exception e) {
e.printStackTraceO ;
}
// Determine the location of each image.
int x * 0;
int h = 0;
for (int i=0; i<images.length; i++) {
rectsfi] - new Rectangle(x, 0,
images[i1.getWidth(nu11), images Li].getHeight(null
x += rects[ij.width;
h =- Math.max(h, rects[i].height);
}
addMouselistener(new MouseEventHandlerQ);
setSize(x, h);
}
public void paint(Graphics g) {
for (int i=0; i<images.length; i++) {
g.drawlmage(images[i], rects[i],x, rectsLi]-y, this);
if (i == curlmage) {
// Draw border around current image.
g.drawRect(rects[i].xf rects(i].у,
rects[i].width, rects[i].height);
}
1
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(vouseEvent evt) {
for (int i-0; i<rects.length; i++) {
// Find out if an image has been clicked.
Transferable
java.awt.datatransfer
A
В
C
D
E
E
G
H
I
J
К
L
if (rects[i].contains(evt.getXC), evt.getYO)) {
// Place image into clipboard.
Mai n.mai nClipboard.setContentsC
new ImageSe1ection(images[i]), ImagePalette.this);
curlmage - i;
repaintО;
break;
}
}
}
}
public void lostOwnership(Clipboard clipboard, Transferable contents) {
// Remove border around current image.
curlmage = -1;
repai nt О;
}
}
class Imageselection implements Transferable {
// Initialize supported flavors.
public static DataFlavor imageFlavor;
private Image data;
public ImageSelection(Image data) {
this.data = data;
}
public synchronized DataFlavor[j getTransferDataFlavorsQ {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(imageFlavor);
}
public synchronized Object getTransferDataCDataFlavor flavor)
throws UnsupportedFlavorException, lOException {
if (flavor.equals(imageF)avor)) {
return (Object)data;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
static {
try {
imageFlavor = new DataFlavor(
Class.forName("java.awt.Image") , "lava Image”);
imageFlavor.setHumanPresentableName(”A Java Image Object");
} catch (Exception e) {
}
}
DataFlavor flavors[] = {imageFlavor};
}
1500
gel Tran sferDi
getlYansferDataO
per pose Retrieves the data encapsulated in this transferable object.
syntax public Object getTransferData(DataFlavor flavor) throws
UnsupportedFlavorException, lOException
description This method retrieves the transferable object's encapsulated data in the data
flavor flavor.
PARAMETERS
flavor The non-nul 1 data flavor.
re-terns Л possibly nul 1 object in the data flavor fl avor.
EXCEPTIONS
UnsupportedF1avorException
If flavor is neither DataFlavor. stri ngFlavor nor DataFlavor .plai n-
TextFlavor.
lOException If the data is no longer available.
st-т also DataFlavor.getRepresentationClass().
example Sec the class example for a class that implements this method. I he following
example retrieves and prints the contents of the clipboard in the string data fla-
vor. The System.exitO method calls are necessary in this code to terminate
the program. This is because retrieving a reference to the system clipboard pre-
vents the process from terminating.
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
class Main {
public static void mai n(String [] args) {
Clipboard clipboard =
Toolkit.getDefaultToolkit().getSystemClipboardО;
Transferable t - clipboard.getContents(nul1);
if (t -= null) {
System.out.println(“The clipboard is empty”);
System.exit(0);
}
try {
String s = (String)t.getTransferData(DataFlavor.stringFlavor);
System. out.printl n------------------------”) ;
System.out .println(s);
System.out.println(“-~ ---------------------”);
} catch (lOException e) {
System.out.println(
“The data is no longer available in the string flavor”);
} catch (UnsupportedFlavorException e) {
System.out.pri ntln(
Transferable j a v a. a wt .dat at r an sfe r
getTransferDaraFlavorst)
“The data is not available in the string flavor");
}
System.exit(0);
1
}
getTransferDataFlavors()
PL RPC >SE SYNTAX Returns an array of data flavors that this transferable object supports, publi c DataFlavor[1 getTransferDataFlavorsО
DESCRIPTION The data flavors in the returned array should be ordered in such a way that the more descriptive data flavors come first. For example» suppose a transferable object contains some rich text and allows the text to be delivered in the same rich text format or converted to plain text. The rich text data flavor should come before the plain text data flavor.
RED'RNS A non-nul 1 array of data flavors.
EXAMPLE See the class example.
PURPOSE Determines whether this object supports a particular data flavor.
SYNTAX public boolean isDataFlavorSupported(Datallavor flavor)
DESCRIPTION This method determines whether flavor is one of the supported data flavors. The transferable object should use DataFlavor,equalsO to determine equality.
PARAMETERS flavor The non-null desired flavor for the data.
REILRNS true if the data flavor is supported: false otherwise.
LX \MPI F. See the class example.
1502
J ' " " — ' ’ -..
UnsupportedFlavorException
< f1 fnxr t ho: p-u'kages r. sh^wn s»4’ :av<s lane. Kx',ppt ion fox -Grplf»»- listin'?
Syntax
public class UnsupportedFlavorException extends Exception
Description
This exception can be thrown when trying to retrieve data from a Transferable object. If the
transferable object (see Transferable) cannot return the data in the desired flavor (see
DataFlavor), the transferable object must throw this exception.
The Exception Message
fhe exception’s message property contains the flavor's human presentable name (see
DataFl avor. getHumanPresentabl eNameO).
Constructor UnsupportedFlavorExceptionO < "" sr ' Constructs an UnsupportedFlavorException instance.
See Also
Clipboard, DataFlavor, Transferable.
Example
This example retrieves the clipboard contents as an illegal flavor called “chocolate.” This
causes Transferable.getTransferDataQ to throw the UnsupportedFlavorException.
For an example demonstrating how a transferable object throws this exception, see the
Transferable class example.
U nsupportedFla vor Exception
L'nsupported FlavorException ()
java.awt.datatransfer
A
В
C
D
E
F
G
H
J
J
К
L
M
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event;
import java.io.*;
class Main extends Frame {
// UnsupportedFlavorException Example
public static void main(St ri ng[] args) {
// Retrieve handle to clipboard and contents.
Clipboard clipboard «.
Toolki t .getDefaul tToolkit() .getSystemClipboardQ ;
Transferable t = clipboard.getContentsCnul1);
if (t == nul1) {
// The clipboard is empty
System.exi t(0);
}
try {
t.getTransferData(new DataFlavor("chocolate”, "chocolate"));
} catch (UnsupportedFlavorException e) {
System.out.println(°This transferable object does not
+’’support the "+e.getMessageO +” data flavor.’’);
} catch (lOException e) {
e.printStackTraceO;
System.out.printin("The transferable data is "
+’’no longer available.’’);
}
}
}
N
()
UnsupportedFlavorException()
Q purpose Constructs an UnsupportedFlavorException instance.
syntax public UnsupportedFlavorException(DataFlavor flavor)
DESCRIPTION
PARAMETERS
flavor
EXAMPLE
W
X
This exception is generated by transferable objects when a request is made for
an unsupported data flavor. The flavor parameter should be the one that was
requested.
The non-null unsupported data flavor
See the Transferable class example.
Y
Z
1504
VetoableChangeListener
Syntax
public interface VetoableChangeListener extends EventListener
Description
F1GFRE 374: Constrained Property Event Flow.
When a constrained property in a bean (see Bean) is about to change, the bean will fire a prop-
erty change event to notify listeners of the requested change. Any listener can veto the
requested change, thereby cancelling the change. See Figure 374. To listen for these events, an
VetoableChangel Jstcne г
java.beans
Л
в
с:
D
E
F
G
H
I
J
К
L
M
N
()
P
Q
R
S
T
U
object must define the method in this interface and then call the bean's addVetoabl eChange-
Li stenerO method.
Vetoing Events
When a vetoable change listener receives the change property event, it can decide to veto the
change request. It does this by throwing PropertyVetoException. Should this occur, the
bean should not change the property value and should inform all vetoable change listeners that
had received and not vetoed the event that the value was not changed. See Figure 374. See
VetoableChangeSupport.fi reVetoabl eChangeO for more details about this process.
Extra Events
When a listener is removed from a bean's listener list, it should be prepared to receive a few
more property change events. Whether it will receive the extra events depends on how the
bean distributes events. In particular, a bean has the option of using a cop\ of the listener list
while delivering events. If the listener is removed while an e\ent is being delivered, it is
removed from the main list but not from the copy. Since the listener is still in the copied list, it
may receive the event.
MEMBER SUMMARY
Callback Method
vetoableChangeO Called whenever a bean's constrained property is about change.
\
w
X
Y
7
See Also
java.uti1.EventLi stener, PropertyChangetvent, PropertyChangeLi stener,
PropertyVetoException, VetoableChangeSupport.
Example
This example demonstrates both an object that fires property change events (because a con-
strained propen} is about to change) and one that listens for those events.
This example implements an in\isible bean that has one constrained properly: “price."
When the bean is created, it also creates a thread that constantly changes its price. When the
price is about to change, lhe bean fires a property change event to notify its vetoable change
listeners. The bean uses VetoableChangeSupport to implement the list of veioable change
listeners.
Fhe Mai n object creates the bean and then listens for property change events. Whenever
an event occurs. Main prints out the new price. However, if lhe new price exceeds $2.50, Main
vetoes the change request.
1506
Bean.java
import java.awt.*;
import java.beans.*;
class Main implements VetoableChangeListener {
MainO {
Bean bean = nul1;
try {
// Create the bean.
bean - (Bean)Beans.instantiate(Main.class.getClassl oader(),
} catch (Exception e) {
e.printStackTraceO;
}
bean.addVetoableChangeLi stener(thi s);
}
// Print the new price. If too high, veto it.
public void vetoableChange(PropertyChangeFvent evt)
throws PropertyVetoException {
float newPrice - ((Float)evt.getNewValueO) .f loatValueO ;
System.out. pri nt(evt, getPropertyNameO + " + newPrice);
// Don't let the price go up to more than $2.50
if (newPrice > 2.50f) {
System.out.println(" VETO");
throw(new PropertyVetoFxceptionC'Too Much!”, evt));
} else {
System.out.print1n();
}
}
public static void main(String argsTl) {
new Main() :
}
}
public class Bean implements Runnable {
float price = 1.49f;
// Constructor
public BeanO {
(new Thread(this)) .startO ;
// The price is a constrained property,
public float getPriceO {
return price;
}
public void setPrice(float newPrice) {
try {
vceLi steners.fi reVetoableChangeC’pri ce”,
new Float(price), new Float(newPrice));
price - newPrice;
} catch (PropertyVetoException e) {
// Don’t change the price
PropertyChangeEvent pee e .getPropertyChangeEventO;
System.out.print("Some listener didn't like the new price
VetoableChangeListener java.beans
vetoableChangef)
* ((Float)pce.getNewValue()) .f loatValueO);
System.out.println(" ” e.getMessageQ) ;
}
}
// Create the listener list.
Л VetoableChangeSupport vceListeners =
new VetoableChangeSupport(this);
В
// The listener list wrapper methods.
C public synchronized void addVetoableChangeListener(
VetoableChangeListener 1) {
D vceListeners.addVetoableChangeListener(l);
}
E public synchronized void removeVetoableChangeListener(
VetoableChangeListener 1) {
F vceListeners.removeVetoableChangeLi stener(l) ;
}
G
public void run О {
H try {
while (true) {
I // Change price up or down by ,50.
setPrice(Math.max(1.0f, price + . 5f - (float)Math.random())) ;
J
Thread.sleep(500);
К }
} catch (Exception e) {
L e.printStackTraceO;
}
M }
}
N
0 Output
price; 2.1139786
p price: 1.9831498
price: 2.2478595
q price: 2.6623638
VETO price: 2.2478595
p Some listener didn't like the new price 2.6623638 - Too Much!
price: 2.4985642
s price: 2.3612332
T
и vetoableChange()
V
PURPOSE
w
SYNTAX
X
Y DESCRIPTION
Z
Called whenever a bean's constrained property is about change.
void vetoableChange(PropertyChange£vent evt) throws
PropertyVetoExcepti on
This method is called when the source bean tires a property change event just
before a constrained property is about to be changed. See PropertyChange-
Event for details.
1508
v с ц J<wi cv. । icii i
If the listener wants to veto the property change request, it should throw
PropertyVetoException. See the class description for more details.
This method may be called a few more times even after the listener is removed
from the bean's listener list. See the class description for details.
PAR A MEI ERS
evt
A non-null properly change event.
EXCEPTIONS
PropertyVetoException
If a change is being vetoed by a listener.
java.beans
VetoableChangeSupport
A
В
<• Syntax
D public class VetoableChangeSupport implements Serializable
i:
Description
Any bean that has constrained properties (see Beans) must be able to deliver vetoable property
G change events (see PropertyChangeEvent). This involves maintaining a list of vetoable
H change event listeners and delivering events to those listeners. This class can be used by a bean
to maintain the listener list and to deliver the events.
1 There are two ways a bean can use this class. Hirst, the bean can extend this class. This is
j not typical, however, since it prevents the bean from inheriting other useful classes such as
Component. The second, and typical way, is for the bean to create an instance of this class and
provide wrapper methods for addVetoableChangeListener() and removeVeto-
1- abl eChangeLi stener(). These bean methods should simply call the methods in this class
that have the same names.
Extra Events
О After a listener is removed from the listener list, the listener might still receive more vetoahle
property change events. This is due to the way fi reVetoableChangeO is implemented. In
1 particular, it makes a copy of the listener list just before it delivers a new event. If a listener is
Q removed while an event is being delivered, the listener is removed from the main listener list
R but not from the copy. Since the listener is still in the copied list, it may receive the event. The
removed listener may also receive an extra vetoable properly change event if the event was
s vetoed by some other listener.
Vetoed Events
As a bean is delivering a vetoable property change event to all of the vetoable change listeners,
a listener may decide to veto the event. It does so by throwing PropertyVetoException.
Should this occur, the bean should stop lhe delivery of the event to the remaining listeners. It
should then inform all of the change listeners who had received and not vetoed the event that
the value was not changed. See fi reVetoabl eChange () for details on exactly how it imple-
ments this reversion process.
1510
add VetoablcChange Listen
MEMBER SUMMARY
Constructor VetoableChangeSupportО Constructs a new VetoableChangeSupport instance.
Listener Methods addVetoableChangeLi stenerO Adds a listener for receiving vetoable property change events.
removeVetoableChangeLi stenerO Stops a listener from receiving vetoable property change events.
Event Method fi reVetoableChange О Delivers a vetoable property change event to the lis-
teners. ; _J
See Also
java.i о.Seri alizable, PropertyChangeSupport, VetoableChangeLi stener.
Example
See the Vetoabl eChangeLi stener class example.
addVetoableChangeListener()
PURPOSE Adds a listener for receiving vetoable property change events.
SYNTAX public synchronized void addVetoableChangeListener(VetoableChangeListener 1i stener)
DESCRIM ION This method adds listener to the listener list. If listener is null, the method call is ignored. The method does not check if listener has already been added, so a listener can be added to the list more than once.
PARAMETERS 1i stener SEEALSO A possibly null vetoable change event listener. removeVetoableChangeLi stenerO.
EXAMPI .E See the Vetoabl eChangeLi stener class example.
VetoableChangeSupport java.beans
fireVetoableChanget)
fireVetoableChange()
pi’rposl Delivers a vetoable property change event to the listeners.
syntax public void fireVetoableChange(String propertyName, Object
oldValue, Object newValue) throws PropertyVetoException
description The oldValue parameter is the current value of the constrained property. The
newValue parameter is the requested new value of the constrained property.
This method creates a new property change event and delivers it to all listen-
ers. If a listener throws PropertyVetoException. this method will stop
delivering the event and then undo the changes. In particular, it creates another
property change event in which its old value is newValue and the new value is
oldValue. It then delivers this new event to the entire list of listeners. (A more
efficient policy might be to deliver only to the listeners that received the
vetoed event.) During this process, all PropertyVetoExceptions are
ignored. After all listeners have been notified of the vetoed exent, this method
throws the vetoed event.
This method first checks if oldVal ue and newVal ue are equal. If they are. the
method call is ignored. The two values are equal if
oldValue != null && oldValue.equals(newValue).
If they are not equal, a new properly change event is created with the values
propertyName. oldValue. and newValue. The event's source is the one that
was used when this class was created. This new event is delivered to each lis-
tener.
The parameter propertyName can be null, which indicates that this is a mul-
tichange event (see PropertyChangeEvent for details). In this case, old-
Val ue and newVal ue will also be nul 1.
After a listener is removed from the listener list, it might still receive more
vetoable properly change events. See the class description for more details.
PARAMETERS
newValue The possibly nul 1 requested new value of the property.
oldValue The possibly null old value of the property.
propertyNameA possibly null property name.
example See the VetoableChangeLi stener class example.
1512
remove VetoableChangcListcr
remove VetoableChangeListenerO
Pl'RPOSI* Slops a listener from receiving vetoable property change events.
SYNTAX public synchronized void removeVetoableChangeListener(VetoableChangeLi stener 1i stener)
DESCRIPTION This method removes 1 istener from the listener list. If 1 istener is null or not in the listener list, the method call is ignored. The removed listener should be prepared to receive a few more vetoable prop- erty change events. See the class description for more details.
PARAMETERS listener A possibly null vetoable change event listener.
SEE Al SO addVetoableChangeLi stener().
EXAMPLE' See the Vetoabl eChangeLi stener class example.
Vetoa bleC ha ngeSup port()
PURPOSE: Constructs a new VetoableChangeSupport instance.
SYNTAX public VetoableChangeSupport(Object source)
DESCRIPTION This method creates a new vetoable change support object and records source as the object that will be firing vetoable property change events. The source object will always be included in every new event that is fired by fi reVeto- abl eChangeO. The source object cannot be changed.
PARAMETERS source The non-nul 1 bean that will be generating vetoable property change events.
SEE: Al.SO fi reVetoabl eChangeO.
EXAMPLE- See the Vetoabl eChangeLi stener class example.
java.beans
Visibility
(visibility ~
Л
B Syntax
C public interface Visibility
D
Description
This interface can be implemented by beans that can be run on servers that may or may not
have a display or w indow system. For example, a timer bean could read its settings from a con-
q figuration file if a window system was unavailable. Otherwise, it would display a graphical
user interface for setting the timing variables,
H This interface is not meant for the typical bean. Hence, to avoid confusing bean users, the
1 get PropertyName and set Proper tyName method signature patterns are not used for lhe
j methods in this interface.
К UseGUI Flag
1 Л bean that implements this interface should maintain a useCUI flag, which determines
whether the bean can display a graphical user interface (GUI). The methods in this interface
M query and set this tlag. The Hag should be initialized to false.
О MEMBER SUMMARY
p 1 GUI Methods
Q avoidingGu i() Determines if the bean can display a GU I.
dontUseGui() Instructs the bean not to display a GUL
R needsGui() Determines if the bean must display a GUI.
S okTollseGui Q Instructs the bean that it can display a GUI.
W This example implements a bean that can display a window containing a message if a GUI is
available. If a GUI is not available, the bean prints to standard out. To run the bean with a GUI,
invoke the command
Y
java Main yes
1514
To run the bean without a GL'L invoke the command
java Main no
Main.java
import java.beans.*;
class Main {
public static void main(String[] args) {
Bean bean - null;
if (args.length != 1) {
System,out.printlnC'Usage: java Main [yeslno]’’);
System.exi t(l);
}
// Should the bean use a gui?
boolean useGui args[0] .equals("yes’') ;
Beans.setGuiAvailable(useGui);
try {
// Create the bean.
bean - (Bean)Beans.instantiate(Main.class.getflassLoadei
} catch (Exception e) {
e.pri ntStackT race();
System.err. println(”Fai led to create bean.1’);
System.exit(l);
}
if (Beans.isGuiAvai1able()) {
bean.okTollseGui ();
} else {
bean.dontUseGui();
}
}
}
Bean.java
import java.beans.-;
public class Bean implements Runnable, Visibility {
boolean dontUseGui = true;
public Bean() {
(new Thread(this)) . startO ;
}
public boolean needsGui() {
return false;
}
public void dontUseGui() {
dontUseGui - true;
}
public void okToUseGuiO {
dontUseGui - false;
}
public boolean avoidingGui() {
return dontUseGui;
Visibility
java.beans
}
MessageFrame frame;
public void run О {
while (true) {
try {
if (Math. randomO > .9944) {
if (’avoidingGui() && (frame -= null ||
!frame.isShowing())) {
frame - new MessageFrameC JACKPOT’’!”);
} else {
System.out.println(''JACKPOT! ! ’ ”) ;
}
}
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}
MessageFrame.java
import java.awt.*;
import java.awt.event.*;
public class MessageFrame extends Frame implements Actionlistene
MessageFrame(String msg) {
super("Message");
// Create the components.
Button b new ButtonC’OK") ;
label 1 = new Label(msg, Label.CENTER) {
// This adds some space around the text,
public Dimension getPreferredSizeO {
Dimension d - super.getPreferredSizeO;
return new Dimension(d.width+40T d.height+40);
}
};
// Listen for events.
b.addActionLi stener(this);
addWindowLi stener(new WindowEventHandlerO);
// layout components.
add(l, BorderLayout.NORTH);
add(b, BorderLayout.SOUTH);
рас к О;
showO;
}
public void actionPerformed(ActionEvent evt) {
dispose();
}
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
di sposeO;
}
}
1516
d WIUIJI£4
avoidingGuif)
PURPOSE Determines if the bean can display a GUL
SYNTAX boolean avoidingGui()
REIT rns true if the bean cannot display a GUI: fal se otherwise.
EXAMPLE See the class example.
dontUseGuiO
PURPOSE Instructs the bean not to display a GUL
SYNTAX void dontUseGuiO
DESCRIPTION This method sets the useGUI flag to false. When the flag is false, the bean cannot create a GUL
EXAMPI 1- See the class example.
needsGui()
PURPOSE Determines if the bean must display a GUL
SYNTAX boolean needsGui()
DESCRIPTION This method should be implemented to return true if the bean must display a GUL If the bean does not have a GUI or does not have to display a GUI, this method should return false.
RETURNS true if the bean must display a GUI; false otherwise.
EXAMPI E See the class example.
okToUseGuiO
PURPOSE Instructs the bean that it can display a GUL
SYNTAX void okToUseGuiO
DESCRIPT ION This method sets the useGui Hag to true. When the flag is true, the bean is allowed to create and present a GUI if it wants to.
EXAMPLE See the class example.
java.awt
Window
Syntax
public class Window extends Container
Description
A window is a lop lex el window that has no tnie. menu bar in bordei к could be i sed to
implement a popup w mdow.
The И a ruing Message Property
l he warning message is a siring that is displaced in a
non secure window. и is not displaced in secure win-
dows. A nonsecure window is a windoxx ihat has a
securilx manager insta’led and tor which ending
Securi tyvanager.check Iopleve 1wi now()
xields false lhe warning message is displaced
somewheic m the windwx and cannot he hidden or
disgu.sed In the application. This pr.nenb an uPPi. Urttivsted Applet Window
cation lioin disguising t. window to look like a crili ---;-----———---------------
cal w indow. such as a login w indow. in order to sie.il
I , . '-A . 1 на Kt .nj; \ \oii-s<4 tin-U iiuloxo
informal ion. liguic o/> shows ;> nonsecure window
on die \\ mdows p|jiiorm.
l he default wanting message suing is ictriexcd from the awt.appletwarrinq ^xsicr'
property See the P^ope^t ies class u>i Rk re details ahoul чукчи piopeilies
1518
Coordinates, Sizes, and Insets
The insets for a window are normally (0. 0. 0, 0) because a window has no title, menu ban or
border. However, if the window has a warning message that is displayed, the insets can be non
zero.
The Peer Hierarchy
The peers for most AWT components require that both the component s parent and its peer
exist. The window component (and its subclasses) is the exception. The window's peer can be
created even if it does not have a parent. This means that the other components need to have a
window at the root of their ancestor chain before their peers can be created.
The Toolkit Property
A toolkit is a factory that creates AWT components such as buttons, scrollbars, and windows.
The default toolkit that AWT uses supplies components that use the platform's native window-
ing toolkit. For example, when running an AWT application on Windows 95, the default tool-
kit creates wrappers around Windows controls, while on Motif, the default toolkit creates
WTappers around Motif widgets.
Events
A window fires all of the events fired by the Container class. It also fires window events. A
window event occurs when the window is closed/opened or iconified/deiconified or when it
gains/loses focus. See WindowEvent for more details. See AWTEvent for details on events and
how to filter and handle them.
MEMBER SUMMARY
Constructor WindowO Constructs a new Wi ndow instance.
Event Methods addWindowLi stenerQ processEventO processWi ndowEventО removeWi ndowLi stenerQ Focus Method ‘ getFocusOwnerQ Property Methods getLocaleQ getToolki tQ getWarni ngSt ri ngQ Adds a listener for receiving events fired by this w indow. 1 Processes an event enabled for this window. Processes a window event enabled for this wundow. Removes a listener from receiving events fired by this window. Retrieves the component in this window that has the focus. Retrieves this window’s locale. Retrieves this Windows’s toolkit. Retrieves this W indows’s warning message.
Continued
Window
ja\ a.awt
MEMBER SUMMARY J
Visibility Methods show (.) toBackO toFront() Makes this window visible. Moves this window behind all other windows. Moves this window in front of all other windows.
Peer Methods addNoti fy() di sposeQ Creates this window’s peer hierarchy Destroys this window's peer hierarchy
Layout Method packQ Resizes this window lo its preferred size.
A
В
c
D
i:
F
G
H
I
J
К
L
M
N
()
P
Q
R
S
I
u
V
Example
This example displays char-
acters represented bv a range
of Unicode values on a
mouse-sensitive canvas.
Rolling the mouse over a
character displays the char-
acter's Unicode value on the
status bar above the cam as.
You can display a differ-
ent range of Unicode values
by entering a 32-bit hexadec-
imal number in the text field
FIGI RE 376: Window for Rendering I ’nieode Characters.
that is supplied and then
pressing Return. Otherwise, lhe next block of Unicode characters will be displaced (the >ize ot
a block is the number of visible rows of characters).
w
X
Y
When you click a character, the character is displayed in a popup window. The popup win-
dow is visible only while the mouse is pressed. See Figure 376.
Note: In Java 1.1.2. the window must listen for mouse up events in order to dispose of
itself. This is because the component that received the mouse pressed event docs not leceive
the mouse up event because of the newly created popup w indow. This w ill be fixed in a later
release.
import java.awt.-';
import java.awt.event.-;
class Main extends Frame implements ActnonListener {
TextField inputTf = new TextFieldO;
Label statusBar = new LabelLabel.CENTER);
1520
CharDisplay charDisplay = new CharDisplay(statusBar);
MainO {
// Set up listeners.
inputlf.addActionListener(this);
// Initialize status bar.
statusBar.setForeground(Col or.white):
statusBar.setBackground(Col or.black);
// Layout components.
add(statusBar, BorderLayout.NORTH);
add(charDisplay, BorderLayout.CENTFR);
add(inputTf, BorderLayout.SOUTH);
setSize(400, 400);
show();
}
char oldCode = (char)-l;
public void actionPerformed(ActionEvent evt) {
// Change starting code.
char code = (char)Integer.parselnt(inputTf .getTextO, 16);
if (code oldCode) {
code = charDi splay. nextPageO ;
} else {
charDisplay.setStartCode(code);
}
i nputTf. setText (In teger. toHexSt ring (code) .toUpperCaseO) ;
oldCode = code;
}
public static void mai n(5t ri ng[] args) {
new Main();
}
}
class CharDisplay extends Canvas {
char startcode;
Label statusBar;
int charW;
int charH;
int charsPerLine ~ 32;
Font font = new Font(“Monospaced", Font.PLAIN, 14);
FontMetrics fontM;
CharDisplay(Label statusBar) {
this.statusBar - statusBar;
// Set up font information.
setFont(font);
fontM - getFontMetrics(font);
charW = fontM.getMaxAdvanceC);
charH fontM .getHeightO ;
// Listen for mouse events.
addMouseListener(new MouseEventHandler());
addMouseMotionListener(new MouseMotionEventHandler());
}
Window
java.awt
// Sets the starting code.
void setStartCode(char startCode) {
this-startCode = startCode;
repai nt();
}
char nextPageQ {
startCode +- charsPerLine * size().height/charH;
repai ntО;
return startCode;
}
public void paint(Graphics g) {
int s - startCode;
int у = 0;
int lines sizeO,height/fontM,getHeight();
charf] buf - new char[l];
Rectangle clip - g.getClipBoundsO ;
// The following could also be used to retrieve the clipping area.
// Rectangle clip = g.getClipO;
// Crow the clipping area to include surrounding characters.
if (clip null) {
cl ip.x -= charW;
clip.width +- 2 * charW;
cl ip.у -- charH;
clip.height +- 2 '• charH;
}
for (int i=0; i<lines; i++) {
// Fill one line with character.
for (int j=0; j<charsPerLine; j++) {
buf[0] = (char)s++;
// Don’t paint the character if not in the clipping area.
if (clip =- null l| clip.contains(j*charW, y)) {
g.drawChars(buf, 0, 1, j*charW, y+fontM.getAscentQ);
}
}
у i= charH;
}
}
class MouseFventHandler extends MouseAdapter {
Window window;
public void mousePressed(Mousetvent evt) {
char code = (char) (evt. getXQ/charW
+ evt.getY()/charH * charsPerLine
* startCode);
Component c - CharDisplay.this;
while (!(c instanceof Frame)) {
с = c.getParent();
}
// Display the window
Point pt =- getLocationOnScreenO;
pt.translate(evt.getX() , evt.getYQ) ;
1522
window = new LargeChar(code, (Frame)c, pt);
}
public void mouseReleased(MouseEvent evt) {
window, di sposeO;
}
}
class MouseMotionEventHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
int code = evt.getXO/charW
> evt.getY()/charH * charsPerLine
* startCode;
statusBar.setText(Integer.toHexStri ng(code).toUpperC
}
}
}
class LargeChar extends Window {
FontMetrics fontM;
char ch;
LargeChar(char ch, Frame frame, Point pt) {
super(frame);
this.ch - ch;
Font font = new Font(“Monospaced”, Font.BOLD, 7?);
fontM = getFontMetrics(font);
setFont(font);
// Listen for mouse events.
addMouseLi stener(new MouseEventHandler());
// Set bounds and show.
setSize(fontM.charWidth(ch)*2, fontM.getHeight()+2);
setLocation(pt.x-size().width/2, pt.у size().height/2);
show() ;
}
public void paint(Graphics g) {
g.drawString(““+ch, 1, fontM.getAscentO+l) ;
g.drawRect(0, 0, size().width-1, sizeO. height-1);
}
class MouseEventHandler extends MouseAdapter {
public void mouseReleased(MouseEvent evt) {
di sposeO;
1
Window
java.awt
addNotifyf)
addNotifyO
purpose Creates this window's peer hierarchy.
SYMAX public void addNotifyO
A DESCRIPTION This method creates this window's peer hierarchy, if necessary. The window 's
В peer is created by calling the Toolki t .createWindowO method. This
C method should be called before the window's minimum or preferred size is calculated. I’he methods pack О and showO automatically call
D addNoti fy().
E* OVERRIDES Container.addNoti fyО.
F SI-Л ALSO Component.addNoti fу О.
(1 H EXAMPLE See Component.setVi si ble().
i add Wi ndo wListener()
J purpose: Adds a listener to receive window events fired by this window.
К SYNTAX public synchronized void addWindowListener(WindowListener
L 1i stener)
M DESCRIPTION See WindowEvent and the class description for more details on window
\ events. After this method is called, the window listener li stener will receive window events tired by this window. If listener is null, this method does
() nothing.
P PARAMEI ERS
Q 1i stener The possibly nul 1 window listener to add.
R Sid: ALSO java.awt.event.WindowEvent, java.awt.event.Windowt istener, removeWi ndowLi stenerO.
S T EXAMPI 1 See the Wi ndowEvent class example.
pi rpose Destroys this window's peer hierarchy.
public void disposeQ
description This window's peer hierarchy is destroyed, if it exists, thereby freeing any
resources used by the peers. The state of the window hierarchy is left intact
and can be reused. The peer hierarchy can be restored by calling
addNotifyO.
example See the class example.
1524
<»ctbociisOwi
getFocus()wner()
pi rposl Retrieves the component in this window that has the focus.
syntax public Component getFocusOwner()
description If this window is active, then one of the components within this window has
the focus.
reti rns The component with the focus; null if no component in this window has the
focus.
seealso Component.requestFocusO, Component.transferFocus(),
java.awt.event.FocusEvent.
example This example creates a window that has various
buttons and text fields. Use the Tab or Shift-Tab
keys to change the focus among components.
The program prints, every 5 sec, the component
that has the focus. If lhe window' is not selected,
null is printed as the focus owner. See Figure
377.
import java.awt.";
< Window...
West | Center | East |
FIGURE 377: Determining
the Focus Owner.
class Main extends Frame implements Runnable {
MainO {
super (“Window.getFocusOwnerО Example”);
add(new TextFieldO, BorderLayout. NORTH) ;
addfnew Button(“West”), Rordprl ayout .WEST) ;
add(new Button(“Center”), BorderLayout.CENTER);
add(new Button(“East”), BorderLayout.EAST);
add(new TextFieldO, BorderLayout. SOUTH) ;
pack();
show();
(new Thread(this)).start();
}
public void run() {
while (true) {
try {
System. out. pri ntl n(“’focus owner = “ + getFocusOwner());
Thread.sieep(5000);
} catch (InterruptedException e) {
}
}
static public void main(Stringf] args) {
new Mai n();
Window
jax a.awt
gctLocale()
getLocale()
pi rposi: Retrieves this window's locale.
SYNTAX public Locale getLocaleO
A RETURNS This window's locale if it has been set; otherwise, the .laxa runtime's default
В locale.
C OVERRIDES Component .getLocaleO.
I) SEE Al SO Component.setLocaleО, java.util.Locale.getDefau110•
E EXAMPI F See Component.getName().
G getToolkit()
н
purpose Retrieves this window 's toolkit.
I
syntax public Toolkit getToolkitO
J
description This method calls Tool ki t. getDefaul tTool ki t ()and returns the result. It a
К window implements its own toolkit, it should oxerride this method to return its
L own toolkit.
M
This window's toolkit.
N OVERRIDES Component.getToolki t().
() SEE A I SO Toolki t.getDefaultToolki tО
p EXAMPLE See Tool ki t.
Q
R getWarningString()
S Г purpose: Retrieves this window's warning message.
LI SYNTAX public final String Untnisted Java Applet Window
V getWarni ngStri ng О
RETURNS The warning message. A return
xahic of null means the window .•••. < Untested window
X is a secure window; —
FIGURE 378: Window.getWarni ngStri ngQ .
Y EXAMPLE This example implements an
у applet that creates a window.
With most browsers, the security manager forces a warning message to be dis
played on any external window that an applet creates. In this example, the
1526
external window simply displays the warning message in its center See Figure
378. Notice that the window's insets are used to calculate the center of the win-
dow's paintable area. The insets of a window are normally all zero, since a
window does not have any window decorations such as a title or border, l he
only exception is when the window* displays a warning message.
import java.awt.*;
import java.awt.event
import java.applet;
public class Main extends Applet {
MyWindow w;
public void init() {
// Find the applet’s frame.
Component f = getParentO;
while (f ! = null && 1 (f instanceof Frame)) {
f = f.getParentО;
}
w = new MyWindow((Frame)f);
w.setBounds(0, 0, 200, 200);
w.show();
}
public void startQ {
w.show();
}
public void stopO {
w.setVisible(false);
}
public void destroyO {
if (w != null) {
w.di spose();
w - nul1;
}
}
}
class MyWindow extends Window {
MyWindow(Frame frame) {
super(frame);
this.addMouseListener(new MouseEventHandlerO);
}
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetricsO ;
String s = getWarningStringO;
int w = getSi zeO-width - getlnsetsO . left - getlnsetsO . right;
int h - getSize().height getlnsetsO . top - getlnsetsO .bottom;
if (s 1- nul1) {
g.drawString(s, (w-fm.stringWidth(s))/2,
(h-fm.getHeightO)/2 + fm.getAscentO);
}
}
Window java.awt
pack()
class MouseEventHandler extends MouseAdapter {
public void mousePressedfMouseEvent evt) {
setVi sible(false);
}
}
}
Input Here is the HTML necessary to start the applet:
:applet code-Main widths100 height-100>
/applet>
pack()
Pl RPOSE Resizes this window to its preferred size.
SYNTAX public void pack()
DESCRIPTION This method resizes this window to its preferred size. It calls lhe addNoti fy0 method before the window's preferred size is calculated. This is important to note because the preferred size of some components is valid only if the compo- nent's peer exists.
SEE Al SO Contai ner .getPreferredSizeO.
EX XMPLE See showQ.
postEvent() DEPKKCATED
PURPOSE Replaced by Component.dispatchEvent().
SYNTAX public boolean postEvent(Event evt)
PARAMETERS evt lhe non-null event.
RETTRNS fal se if the event should be passed up co lhe component’s parent; true other- wise.
OVERRIDES Component.postEvent О.
DEPRECATION See Component postEvent О for how lo replace deprecated usage of this method.
1528
piOCCSSlSVi
processEventO
Pl RPOst Processes an event enabled for this window.
S'! VI A\ protected void processlvent(AWTFvent evt) This method extends Container.processEvent() by adding support for WindowEvent. When a subclass overrides processEventO. it should call super.processEventO to perform the processing intended by its base class I such as dispatching the t ypes of events to its listeners L
PAR AMI.I I RS
evt The event to be processed.
overrides Container, processEventO.
se-:i. Л1 so AWIEvent, processWindowLventО.
EXAMPI E See the Component class example.
processWindowEventf)
Pl RPOSF Processes a window event enabled for this window.
SY VI AX protected void processWindowFvent(IWindowFvent evt)
DESC 'RIH ION See WindowEvent and the class description for more details on window events. This method processes window events for this window by calling any registered WindowListener. This method is invoked only if window e\enls have been enabled for this window. This can happen either when a window lis- tener is added to this window or if window events are enabled explicitly via Component,enableEvents 0 • Topically, a program controls how window- events for a choice are processed by adding or removing window listeners. It overrides processWindow- Event() only if it needs to do processing in addition to that performed by the registered listeners. When a subclass does override processWindowEvent(). it should cull super.processWindowEventO to perform the processing intended by its base class (such as dispatching its listeners).
PAR V.ME IERS evt The non-null window event to be processed.
O\ ERRIDES Contai ner.processl vent О •
SEI. Al SO java.awt.event.Wi ndowEvent, java.awt.event.WindowLi stener, processEvent().
EXAMPI E See AWTEventMu11 i caster.wi ndowActi vated().
java.awt
Window
removewindow Listened)
remove WindowListener()
PURPOSE Removes a listener from receiving window events from this window.
SYXTAX public synchronized void removeWindowlistener(WindowListener 1i stener)
DESCRIPTION See WindowEvent and the class description for more details on window events. After this method is called, the window listener listener will no longer receive window events from this window. If listener is null, (his method does nothing.
PAR A METT RS 1i stener The possibly null window listener to remove.
SEE XLSC) addWindowlistenerO, java.awt.event.WindowEvent, java.awt.event.Wi ndowLi stener.
exampi.e: See removeActionListenerO in Menuitem.disableEventsQ-
show()
purpose Makes this window visible.
SYNTAX public void showQ
1
j
)
)
)
description This method calls lhe addNotifyO method, validates the window's layout
and then makes the window visible. The window does not necessarily appear
in front of all other windows: the exact behavior is platform-dependent, lb
force the window- to be displayed in front of all other windows, call the
toFrontO method. If the w indow is already visible, the window is brought to
the front.
overrides Component. showQ.
see also Component.setVi si ble(). Hide
EXAMPLE This example creates a window that has a button that, when pressed, hides the window’. The window reap- FIGURE 379:
pears within 5 sec. See Figure 379. Window Visibility.
import java.awt.
import java.awt.event.*;
class MainWindow extends Window implements Runnable. ActionListener {
MainWindow(Frame parent) {
super(parent);
Button b = new ButtonQHide”) ;
b.addActionlistener(this);
add(b, BorderLayout.CENTER);
setSize(100, 50);
1530
1оВ;кк
showQ ;
(new Th read(this)).start О:
}
// Hides window when button is pressed
public void actionPerformed(ActionEvent evt) {
setVi s i ble(false);
}
public void run() {
while (true) {
try {
show();
Ihread.sleep(5000);
} catch (InterruptedException e) {};
I
}
}
class Main {
static public void main(StringLJ args) {
new Mainwindow(new FrameO);
}
}
toBackf)
pi rposi: Moves the window' behind ail other windows.
SYNTAX public void toBack()
DESCRIPTION The window is moved behind all windows in the system, regardless of whether they arc ?XWT windows. The position of the window with respect to other win- dows is not necessarily maintained: the exact behavior is platform-dependent, bor example, if the window was behind some windows, hidden, and then is shown again, it may not reappear behind the same window's.
SEE -\| SO toFrontO.
EX.AM PI 1 See toFrontO.
toFrontf)
Pi Rposi' Moves the window in front of all other windows.
public void toFrontO
Of SCRIJH |<)\
The window is moved in front of all other windows in the system, regardless
of whether they are AWT windows.
Window
java.awl
Window! )
i xampi.I: This example creates a window that has a button that
sends lhe window to lhe back. The window returns to Back
the front within 5 see. See Figure 380.
import java.awt. "'; I KЛ Rl 3S0:
import java.awt.event; Window. toFrontO .
class MainWindow extends Window implements Runnable,
ActionListener {
MainWindow(Frame parent) {
super(parent);
Button b = new But ton(“Back”);
b.addActionListener(this) ;
add(b, BorderLayout.CENTER);
setSize(100, 50);
showO ;
(new Thread(this)).start();
}
// Hides window when button is pressed
public void actionPerformed(ActionEvent evt) {
toBackO ;
public void run() {
while (true) {
try {
toFrontO ;
Th read.sieep(5000);
} catch (InterruptedException e) {};
class Main {
static public void main(String[J args) {
new MainWindow(new FrameO);
}
Window()
j ----------------------------------------------------
V' Pl Rpost Constructs a new Window instance.
1 S'» M AX public Window(Frame parent)
v l)FS( RIPI ION This constructor creates a new invisible, modeless Window instance that has
\ the parent parent. The new window has a border layout manager.
PAR WIFIT.RS
parent The non-null owner of the window.
1532
Windox
I.XC'I PI IONS
Ill egal ArgumentExcept!on
It parent is nul 1.
see ai so BorderLayout, java.1ang.Il 1 egalArgumentException, show().
E\ XX1PI E
This example demonstrates
how to create a popup win-
dow. Clicking the frame cre-
ates a window at the point of
the click. Releasing the
mouse button disposes of the
window. See Figure 381.
Notice that a mouse listener
must be installed for the
popup window in addition to
the mouse listener for the
[^Window Example ВИЕ1
main frame. This is because
the popup created is modal
and blocks all other user input
until it disappears.
FIGURE 3K1: A Popup Window.
import java.awt.*;
import java.awt.event;
class Main extends Frame {
PopupWindow pm = null;
Main() {
super(“Window Example”);
// Install listener
this.addMouseLi stener(new MouseEventHandler());
setSize(100, 100);
show();
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
Rectangle r = getBoundsO;
int x = evt.getX();
int у = evt.getYO ;
// Create popup at position of mouse
pm = new PopupWindow(Main.this);
pm.setBounds(r.x + x, r.y + y, 100, 50);
pm. showO ;
}
public void mouseReleased(MouseEvent evt) {
if (pm •= null) {
// get rid of peer
pm. di sposeO ;
java.awt
Window
Window()
pm null;
}
}
}
static public void main(Stri ng[] args) {
4 new Mai n();
}
В }
(’ class PopupWindow extends Window {
PopupWindow(Frame f) {
D super(f);
set Background(Color.yellow);
li
// Listener to remove popup when mouse button released.
F // Need listener within popup menu because popup menu is modal,
this.addMouseListener(new MouseEventHandler());
G }
H public void paint(Craphics g) {
FontMetrics fm g.getFontMetrics();
I String s = “Popup Window”;
j q.drawString(s, (getSize().width fm.stringWidth(s))/2,
(getSizeO .height- fm.getHeight())/2 + fm.getAscent l
К }
L class MousetventHandler extends MouseAdapter {
public void mouseReleased(MouseEvent evt) {
M // get rid of peer
disposeQ ;
N }
}
О }
P
Q
R
S
T
L
V
в
X
V
Z
1534
Window Adapter
Syntax
public abstract class WindowAdapter implements WindowListener
Description
The win&m adapter is a window listener in which all callback methods are empty implemen-
tations, The window adapter makes it more convenient for an object to listen for window
events. In particular, by using the window adapter, you can implement only those callback
methods in which you are interested. Without the window adapter, you must implement all
callback methods, even if the method is empty.
To use a window adapter, you create a subclass of WindowAdapter and override the
desired callback methods. You then create an instance of the window adapter subclass and use
it to call the window's addWi ndowLi stenerO method. The window adapter subclass is typi-
cally an inner class.
MEMBER SUMMARY
Window Event Callback Methods
wi ndowActi vatedO Called after a window is activated.
. windowClosedf) Cal led after a window is closed.
windowClosingO Called when a window is about to close.
wi ndowDeact i vated О Called after a window is deactivated.
. windowDeiconifiedО Called after a window is deiconified.
windowlconi fiedO Called after a window is iconified.
wi ndowOpenedO Called after a window has been shown for the first time.
See Also
java.awt.AWTEventMulticaster, java.awt.Window.addWindowListenerO,
java.uti1.EventListener, WindowEvent, WindowListener.
Example
See the WindowEvent class example.
Window Adapter
java.awi.e vent
window ActivatedO
windowActivatedO
X Pl RPOSE SYNTAX DESCRIPTION Called after a window is activated. public void windowActivated(WindowEvent evt) This method is called after a window is activated. A window can be activated
by the user or by calling Component. requestFocusO on the window. At
present, there is no method call for determining a window's current, actixated state. If this information is needed, you must override windowActi vated()
PARAMETERS and wi ndowDeacti vatedO and maintain the state yourself. This method, by default, has an empty implementation.
.1 evt The non-null window event.
t EXAMPLE See the Wi ndowEvent class example.
PURPOSE
Л M ) Э * S I SYNTAX DESCRIPTION
J PARAMETERS
v' evt
Я EXAMPLE
i
J windowClosed()
<
Called after a window is closed.
public void windowClosed(WindowEvent e)
This method is called after Window.disposeO has been called on the win-
dow. /\fter a window's di sposeO method is called, the window7 is considered
closed. This is the only way to close a window. When a window7 is closed, it is
simply hidden and its peer are destroyed. This means that it is possible to call
showO on the window again.
This method is not called when the user requests that the window be closed
(using a platform-specific gesture); rather, windowCl osingO is called. It is
the application that must call Window.di sposeO on the window in order for
the window to be closed and the windowClosedO method to be called.
This method, by default has an empty implementation.
The non-null window event.
See the Wi ndowEvent class example.
К
windowClosingO
purpose Called when a window7 is about to close.
syntax public void windowClosing(WindowEvent e)
1536
window Deacti vat
DESCRIPTION This method is called when the user has requested that the window be closed (see windowClosedO tor more details about closed windows). The applica- tion must call the window's disposeQ method in order for the close opera- tion to be completed. If disposeQ is not called, the user's close request is ignored. If the window is closed by calling disposeQ, this method is not called; only the wi ndowClosedQ method is called. The main purpose of this method is Co let the application check if any data needs to be saved and then ask the user whether to save lhe data. This method, by default, has an empty implementation.
PARAMEI ERS evt The non-null window event.
EXAMPLE See lhe Wi ndowEvent class example.
windowDeactivated()
PURPOSE Called after a window is deactivated.
SYNTAX public void windowDeactivated(WindowEvent e)
DESCRIPTION This method is called after a window is deactivated. A window is deactivated when the user moves the focus to another window or if Component. request- FocusQ is called on another window. At present, there is no method call for determining a window's current, activated state. If this information is needed, you must override windowActivatedQ and wi ndowDeacti vatedQ and maintain the state yourself. This method, by default, has an empty implementation.
PARAMETERS evt l he non-nul 1 window event.
EXAMPLE See the Wi ndowEvent class example.
w i ndo w Deicon ifiedO
PURPOSE Called after a window is deiconifled.
SYNTAX public void windowDeiconifiedfWindowEvent e)
DESCRIPTION This method is called after a window has been deiconifled. At present, there is no method call that can deiconify a window; only the user can do this. Also, there is no method call for determining a window’s current, iconified state. If
Wi ndowAdapter java.awt.event
windowlconifiedO
this information is needed, you must override windowlconifiedO and win- dowDei coni tied () and maintain the state yourself. This method, by default, has an empty implementation.
PARAMI TERS evt The non-nul 1 window event.
EXAMPLE See the Wi ndowEvent class example.
window IconifiedO
PURPOSE Called after a window is iconified.
SYNTAX public void windowlconifiedfWindowEvent e)
DESCRIPTION This method is called after a window is iconified. At present, there is no method call that can iconify a window; only the user can do this. Also, there is no method call for determining a window's current, iconified state. If this information is needed, you must override windowIconifiedO and window- Dei conified() and maintain the state yourself. This method, by default, has an empty implementation.
PARAMETERS evt The non-null window event.
EXAMPLE See the Wi ndowEvent class example.
windowOpenedf)
РГ RPOSE Called after a window has been shown for the first lime.
SYNTAX public void windowOpened(WindowEvent e)
DESCRIPTION This method is called after a window is shown for the first time. When this event is processed, calling Component.isShowing() on the source compo- nent returns true. This method, by default, has an empty implementation.
PARAMETERS evt The non-nul 1 window event.
EXAMPLE. Sec the WindowEvent class example.
1538
J СI V 11 , cl V v L . V V t III
WindowEvent
Syntax
public class WindowEvent extends ComponentEvent
Description
Window events are fired by a window (see Window) whenever the window is opened/closed,
activated/deactivated, or iconified/deiconified. For more general information about events, see
AWTEvent.
Listening for Window Events
To listen for window events from a window, (he listener must implement the Wi ndowLi stener
interface. Next, it must be registered with the window. It becomes registered by calling the
window's addWi ndowLi stenerO method.
An alternative, and possibly more convenient, way of receiving window' events is to use a
window adapter. See WindowAdapter for more details.
As with most events, window events are delivered to the window's listeners after the oper-
ation has taken place.
The Iconified Property
A window* is iconified if the window has been reduced to a small icon on the system's desktop.
At present, there is no method call for determining a window's current, iconified state. If this
information is needed, you must listen for all changes to a window’s iconified state and manu-
ally maintain the stale.
WindowEvent
java, aw i. event
The Activated Property
A w indow is activated if it or some child component it contains has the focus. At present, thcie
is no method call for determining a window's current, activated state. II this information is
needed, vou must listen for all changes to a window's activated state and manuallv maintain
the state.
Window Event Flow
Figure 382 shows how window events typicallv
flow through the system. First, the event is fired b\ a
component peer in response to some user gesture.
This event is posted on the event queue (see Event -
Queue). When the event makes its wax to the front
of the queue, it is given to the component via its
di spatchEvent О method. The main purpose ol
this method is to discard the event if there are no
window event listeners. Otherwise, di spatch-
EventO calls processEventO. which in turn calls
different methods depending on the event type.
Since this is a window event, processwindow
Event О is called. The main purpose of this method
is io notifv the window listeners of the event.
A component can override processwindow
Event О to process window events before lhev are
delivered to the component's listeners. 'I'he overrid-
den method should call super.processwindow-
Event О to ensure that events are dispatched to the
component’s listeners.
kinaowPeer WindowEvent
System
Event I —1
Queue I
•i
dispatchEventO
I
Window processEvent()
I I
^processwi ndowEvent() ,
I “ "
/'S
Wi ndowL i s t ene r r> v. 7
I !(! Rl',382: Window Event Flow.
MEMBER SUMMARY
Const motor
Wi ndowE vent()
Constructs a new Window^ vent instance.
Window Method
getWindowO
Retrieves the window that fired this event.
Window Event Id ( (instants
WINDOW ACTIVATED
WINDOW CLOSED
WINDOW-CLOSING
WINDOW-DEACTIVATED
WINDOW.DLTCONIFTFD
Event id indicating that a window was activated.
Ел ent id indicating that a window was closed.
Event id indicating that a window is about to close.
Елен! id indicating that a window was deactivated.
Ел ent id indicating that a window was deiconified.
1540
I MEMBER SUMMARY
WINDOW-FIRST
WINDOW_ICONIFIED
WINDOW-LAST
| WINDOW-OPENED
Debugging Method
paramStri ngO
Constant specif}ing the first id in lhe range of window event
ids.
Event id indicating that a window was iconified.
Constant specifying the last id in the range of window event ids.
Event id indicating that a window has been shown for the first
lime.
Generates a string representing the window event's stale.
See Also
java.awt.AWTEvent, java.awt.Component.di spatchEvent(),
java.awt.Component.processEventO, java.awt.Window, WindowAdapter,
Wi ndowLi stener.
Example
This example implements a fra me
manager that can control and dis-
play the current properly state of
all AWT frames. The left frame in
Figure 383 shows all existing
AWT frames, of which there are
Fl Gt RE 383: Frame Manager.
four. The left part of the item is the
title of the frame, while the right
part of the item shows the frame's current property state. The + indicates that the frame is
deiconified: the - indicates that it is iconified: and the * indicates that it is activated. The
absence of a symbol indicates the frame is hidden.
The two frames on the right represent two visible AWT frames. FrameO is hidden and
Frame3 is iconified. so they do not appear on the screen.
Clicking the New button on the frame manager creates a new hidden frame. Clicking the
Show/Hide button shows the selected frame (if the frame is hidden) or hides the selected frame
(if the frame is showing). Double-clicking an item in the list does the same thing. Clicking the
Close button disposes of the selected frame.
Although the AWT can inform vou when the iconified or activated states of a frame
changes, it docs not allow you to quer\ these states on a frame. Consequent!}, this example
creates a subclass of the frame that listens to window events on the frame. In this way the
frame can maintain an accurate picture of its current state that can then be used by the frame
manager.
WindowEvent
awt.event
Notice that My Frame also listens to the component events that are fired whence
frame becomes hidden or shown. VyFrame uses these events to inform the frame man2
update its display.
import java.awt.-';
import java.awt.event.
import java.util.’;
class vain extends Frame implements Actionlistener {
FrameManager frameManager = now TrameManagerC);
vain() {
super("Wi ndowEvent Example");
Button b;
Panel p - new Panel(new GridLayout(0, 1));
// Populate the control panel.
p.add(b = new But ton("New"));
b.addActionl i stener(t h i s) ;
p.add(b - new ButTon("Show/Hide")):
b.addActionL istener(th is);
p.add(b - now Button("Close"));
b.addActionl istener(this);
add(p, Borderlayout.FAST);
add(franevanager, BorderLayout.CENTER);
frameManager.addActionLi stener(thi s);
setSize(?00, 100);
show();
// Button act ions.
public void actionPerforrred(Actiontvent evt) {
if (evt.getActionCommandO.equalst"New")) {
new MyFrame(frameManager);
return;
}
MyFrame f - fгате^ападег.getTrameO;
if (f — null) {
return;
}
if (evt.getActionCommandO.equals("Show/Hi de")
I evt. get SourceO == f ranevanager) •[
if (f. isShowing()) {
f.setVi sible(false);
} else {
f. showO;
}
frameManager.update(f);
} else if (evt.getActionCommand().equalsC'Close")) {
franevanager.close(f);
f.d i sposeO ;
}
}
public static void ma^nCString arqs[ ]) {
new Mai n();
1542
class MyFrame extends Frame implements WindowListener {
FrameManager frameManager;
static int count; // for naming the frames.
boolean iconified;
boolean activated;
MyFrame(FrameManager wl) {
supe r(" Frame"* (count+ 0);
frameManager - wl;
// Add this frame to the window list.
frameManager.add(this);
// Listen for events.
addWindowListenerCthis);
addComponentListener(new ComponentEventHandlerO);
add(new Label (getTitleO , L abel .CFNTER) , BorderLayoi
setSize(100, 50);
}
// Window Events
public void windowOpened(WindowEvent evt) {
System.out.printin("WINDOW-OPENED");
public void windowClosing(WindowEvent evt) {
di sposeC);
1
public void windowClosed(WindowEvent evt) {
frameManager.close((MyFrame)evt.getSourceO);
public void windowlconified(WindowEvent evt) {
iconified true;
frameManager.update(this);
}
public void windowDeiconified(WindowEvent evt) {
iconified = false;
f rameManager.update(thi s);
}
public void windowActivated(WindowEvent evt) {
activated = true;
frameManager.update(thi s);
}
public void windowDeactivated(WindowEvent evt) {
activated = false;
frameManager.update(this);
}
// Component Events
class CorrponentEventHandler extends ComponentAdapter {
public void componentShown(ComponentEvent evt) {
frameManager.update((MyFrame)evt.getSourceO);
}
public void componentHidden(ComponentEvent evt) {
frameManager. update((MyF rame)evt.getSourceO) ;
}
WindowEvent
java.awt.event
}
class FrameManager extends List {
// This holds a list of frames. The order of the frames
// in this vector corresponds to the order of the frames
// in the list component.
Vector frames - new VectorO;
FrameManager() {
setFont(new FontC'Monospaced", Font.PLAIN, 12));
}
// Returns the currently selected frame or null if there
// is no selected item.
MyFrame getFrame() {
int ix - getSelectedlndexQ ;
if (ix >- 0) {
return (MyFrame)frames.elementAt(ix);
}
return nul1;
}
void add(MyFrame f) {
add(f .getTi tleO);
frames.addElement(f);
update(f);
}
void close(MyFrame f) {
int ix = frames.indexOf(f);
if (ix >- 0) {
f rames•removeFlementAt(i x);
remove(ix);
}
}
void update(Myhrame f) {
int ix = frames.indexOf(f);
if (ix >- 0) {
String s = f.getTitleO * " ";
if (f-isShowingQ) {
if (f.iconified) {
s += ’ ’;
} else {
s += ’+’;
}
if (f.activated) {
s += ’*’;
} else {
s += ' ’;
}
}
replaceltem(s, ix);
}
}
1544
getWi ndm
getWindow()
purpose: Retrieves the window that fired this event.
SYNTAX public Window getWindowO
DESCRIPTION This method returns the component that fired the component event. This is the same object returned by Eventobject.getSourceO.
RETURNS The non-null window that tired this event.
SEE ALSO j ava.awt.Wi ndow, j ava.util.EventObj ect.getSou rce О.
EXAMPLE. See the class example.
paramStringO
purpose: Generates a string representing the window event's state.
syntax public String paramStringO
description The returned string contains the name of the window’ event. A subclass of this
class should override this method and return a concatenation of the window
event s state with the results of super. paramStringO. This method is called
by lhe AWTEvent .toStringO method and is typically used for debugging.
returns Л non-nul 1 string representing the window event’s state.
overrides java.awt.AWIEvent.paramStri ng().
see: also java, awt .AWTEvent .toStri ngO , java. lang .Object .toStringO.
exampi e Seethe java.awt .AWTEvent class example.
WINDOW, ACTIVATED _________________________
purpose E:vent id indicating that a window was activated.
syntax public static final int WINDOW_ACTIVATED
description An event with this id (value 205) is fired by a window when it is activated. A
window can be activated by the user or by calling Component. requestFo-
cusO on the window. At present, there is no method call for determining a
window's current, activated state. If this information is needed, you must listen
for WINDOW__ACTIVATED and WINDOW-DEACTIVATED events and maintain the
state yourself.
see also java.awt.Component.requestFocusO, WINDOW-DEACTIVATED.
example- See the class example.
java.awt.event
WindowEvent
W1N?WW_C1.()SED
WINDOW CLOSED
H RPOSE Event id indicating that a window was closed.
SYNTAX public static final int WINDOW-CLOSED
DESCRIPTION An event with this id (value 202) is fired by a window after Window.dis- pose Q has been called on the window. After a window 's di sposeO method is called, the window is considered closed. This is the only way lo close a win- dow. When a window is closed, it is simply hidden and its peers are destroyed. This means that it is possible to call showO on the window again. This event is not fired when the user requests that lhe window be closed (using a platform-specific gesture): rather, a WINDOW. CLOSING event is fired. It is the application that must call Window.di sposeO on the window in order for the window to be closed and lhe WINDOW-CLOSED event to be fired.
SEE ALSO WINDOW-CLOSING.
E.XAMPl I See the class example.
WINDOW_C LOSING
PERPOSE Event id indicating that a window is about to close.
SYNTAX public static final int WINDOW-CLOSING
DESCRIPTION An event with this id (value 201) is fired by a window when the user has requested that the window be closed (see WINDOW-CLOSED for more details about closed windows). The application must call the window's disposeQ method in order for the close operation to be completed. If di sposeO is not called, the user's close request is ignored. If the window is closed by calling di sposeO, this event is not fired: only the WINDOW CLOSED event is fired. l he main purpose for the WINDOW-CLOSING event is to let the application check if any data needs to be saved and then ask the user whether to sa\e the data.
SEE. Al.SO java.awt .Window,di sposeO , WINDOW-CLOSED.
EXAMPLE-: See the class example.
1546
VV 1NWW_MtlAC I I
WINDOW-DEACTIVATED
PURPOSE Hvent id indicating that a window was deactivated.
SYNTAX public static final int WINDOW. DEACTIVATED
DESCRIPTION An event with this id (value 206) is fired by a window when it is deactivated. A window is deactivated when the user moves the focus to another window or if Component. requestFocusO is called on another window. At present, there is no method call for determining a window’s current, activated state. If this information is needed, you must listen for WINDOW-ACTIVATED and WINDOW-DEACTIVATED events and maintain the stale yourself.
SEP, Al,SO java.awt.Component.requestFocusO, WINDOW_ACHVATED.
ЕХЧМР1.Г See the class example.
WINDOW DEICONIFIED
Pl -RPOSI Event id indicating that a window was deiconified.
SYNTAX public static final int WINDOW DFICON1FTED
DESCRIPTION An event with this id (value 204) is fired by a window when it is deiconified. At present, there is no method call that will deiconify a window; only a user can do this. Also, there is no method call for determining a window's current, iconified state. If this information is needed, you must listen for WINDOW-ICONIFIED and WINDOW_DEICONIFIED events and maintain the state yourself.
SEE. ALSO WINDOW—ICONIFIFD.
EXAMPI 1; See the class example.
WINDOW-FIRST
PURPOSE Constant specifying the first id in the range of w indow event ids.
SYNTAX public static final int WINDOW_FIRSI
DISCRIPTION All window event ids must be greater than or equal to WINDOW-FIRST (value 200).
SEE ALSO WINDOW LAST.
EXAMPLE See java.awt.Component,processEventО.
WindowEvent
java.awt.event
WINDOW JCONIHED
WINDOW-1CONIHED
PURPOSE Event id indicating that a window was iconified.
SYNTAX public static final int WINDOW_ICONIFIED
DESCRIPTION An event with this id (value 203) is tired by a window when it is iconified. At present, there is no method call that will iconify a window; only a user can do this. Also, there is no method call for determining a window's current, iconi- fied slate. If this information is needed, you must listen for WINDOW_ICONIFIED and WINDOW.DEICONIFIED events and maintain the state yourself.
SHE Al SO WINDOW..,DEICONTFTFD,
example: See the class example.
WINDOW_LAST
purpose: Constant specifying the last id in the range of window event ids.
syntax public static final int WINDOW-LAST
DESCRIPTION All window event ids must be less than or equal to WINDOW-LAST (value 206).
SEE ALSO WINDOW-FIRST.
EXAMPLE See java.awt .Component. processEventO.
WINDOW-OPENED
PUR Pl )SE: Event id indicating that a window has been shown for the first time.
SYNTAX public static final int WINDOW-OPENED
DESCRIPTION An event with this id (value 200) is fired by a window when it is shown for the first time. When this event is processed, calling Component. i sShowi ng() on the source component returns true.
EXAMPI E See the class example.
WindowEventO
PURPOSE Constructs a Wi ndowEvent instance.
SYNIAX public WindowEvent(Window source, int id)
1548
DESCRIPTION This constructor creates a new window event instance with source as the win- dow that fires this event. After lhe window event is created, the source window can distribute the event to its listeners by calling the window event-related methods in AWTEventMul- ticaster. If the event is not created by source, the creator can deliver the event to the source component either by posting the event to the event queue (see EventQueue. post Event О) or by calling lhe source component's Com- ponent .di spatchEventO method directly.
PARAMETERS
source id The non-null window that is firing this window event. One of the window event ids.
SEE ALSO java.awt.AWTEvent.getXDО, java.uti1.tventObject. getSourceO.
java.awt.event
WindowListener
Syntax
public interface WindowListener extends EventListener
Description
When an object (listener) wishes to receive window events from a window (the source win-
dow), two things must be done:
1. The listener must implement the Wi ndowLi stener interface and all of the interface’s
required methods.
2. The listener must be registered with the source window. It becomes registered by making
a call to the source window's addWindowListener().
For information about window' events, see WindowEvent. For more information about win-
dows, see Wi ndow.
1550
winaowAcuvai*
MEMBER SUMMARY
Window Event Callback Methods wi ndowActi vatedО Called after a window is activated. wi ndowC 1osed О Called after a window is closed. windowClosing() Called when a window is about to be closed. wi ndowDeacti vated() Called after a window is deactivated. windowDeiconified() Called after a window is deiconified. wind owl coni fied() Called after a window is iconified. wi ndowOpenedO Called after a window has been shown for the first time.
See Also
java.awt.Window.addWi ndowLi stenerO T java.uti1.EventLi stener,
Wi ndowAdapter, Wi ndowEvent.
Example
See the WindowEvent class example.
window Acti vated()
purpose Called after a window is activated.
SYN'l AX public void windowActivated(WindowFvent evt)
IM-SCR llyJ ION This method is called after a window is activated. A window can be activated by the user or by calling Component. requestFocusO on the window. At present, there is no method call for determining a window's current, activated state. If this information is needed, you must implement wi ndowActi vatedO and windowDeactivatedO to maintain lhe state.
PARAMCfERS evt The non-null window event.
EXAMPLE See the Wi ndowEvent class example.
windowClosedO
purpose Called after a window is closed.
syntax public void windowClosed(WindowEvent evt)
WindowListener
java.awt.event
windowClosingO
DLSCRI PTION This method is called after Window.di sposeO has been called on the win- dow. After a window's disposeO method has been called, the window is considered closed. This is the only way to close a w indow. When a window is closed, it is simply hidden and its peers are destroyed. This means that it is possible to call showO on the window again. This method is not called when the user requests that the window be closed (using a platform-specific gesture): rather. windowClosingO is called. It is the application that must call Window.disposeO on the window in order for the window to be closed and the wi ndowCl osedO method to be called.
PARAMETERS
evt I’he non-null window event.
example See the Wi ndowEvent class example.
windowClosingO
PURPOSE Called when a window is about to be closed.
SV M AX public void windowClosing(WindowEvent evt)
DESCRIPTION This method is called when the user has requested that the window be closed (see windowClosedO for more details about closed windows). The applica tion must call the window’s disposeO method in order for the close opera- tion to be completed. If disposeO is not called, the user's close request is ignored. If the window is closed by calling disposeO. this method is not called; only the wi ndowCl ose() method is called. The main purpose of this method is to let the application check if any data needs to be saved and then ask the user whether to save the data.
PARAMETERS evt The non-nul 1 window event.
EXAMPLE See the WindowEvent class example.
windowDeactivatedO
PURPOSE Called after a window is deactivated.
SYNTAX public void windowDeactivated(WindowEvent evt)
DESCRIPTION This method is called after a window is deactivated. /\ window is deactivated w hen the user moves the focus to another w indow or Component.request-
1552
WiriUOWMC Infill J 1
Focus() is called on another window. At present, there is no method call for
determining a window’s current, activated state. If this information is needed,
you must implement windowActivatedQ and windowDeactivateО to
maintain the state.
PARAMETERS
evt The non-null window event.
example See the Wi ndowEvent class example.
windo wDeicon ified()
pcrposi- Called after a window is deiconifled.
syntax public void windowDeiconified(WindowEvent evt)
description This method is called after a window' has been deiconifled. At present, there is
no method call that will deiconify a window; only a user can do this. Also,
there is no method call for determining a window's current, iconified state. If
this information is needed, you must implement windowIconifiedO and
windowDei coni fiedO to maintain the state.
PARAMETERS
evt The non-null window event.
example See the Wi ndowEvent class example.
windowIconifiedO
PURPOSE Called after a window is iconified.
SYNTAX public void windowlconified(W1ndowEvent evt)
DESCRIPTION This method is called after a window is iconified. At present, there is no method call that will iconify a window; only a user can do this. Also, there is no method call for determining a window's current, iconified state. If this information is needed, you must implement windowIconifiedO and win- dowDei conifiedO to maintain the state.
PARA MET'ERS evt The non-null window event.
EXAM Pl л: See the Wi ndowEvent class example.
WindowListener
wi ndowOpenedO
java.awLexent
windowOpen ed()
Pl RPOSL Called after a window has been shown for the first lime.
SYXT/XX public void windowOpened(WindowEvent evt)
IK SCRIP 11<).\ This method is called after a window is shown for lhe first lime. When this event is processed, calling Component. i sShowingO on the source compo- nent returns true.
PARAMI"! LRS evt The non-nul 1 window event.
F XAMPI F See the Wi ndowEvent class example.
1554
WindowPeer
Syntax
public interface WindowPeer extends ContainerPeer
Description
The window component (see the Window class) in lhe AWT uses the platform's native indple-
mentation of a window. So that the AWT window behaves the same on all platforms, the win-
dow is assigned a/wr, whose task is to translate the behavior of the platform’s native window
to the behavior of the AWT window.
AWT programmers normally do not directly use peer classes and interfaces. Instead, they
deal with AWT components in the java.awt package. These in turn automatically manage
their peers. Only someone who is porting the AWT to another platform should be concerned
with lhe peer classes and interfaces. Consequently, most peer documentation refers to
java.awt counterparts.
See Component and Tool kit for additional information about component peers.
MEMBER SUMMARY
। Peer Methods
I toBackO Moves the window behind all other windows.
I toFrontO Moves the window in front of all other windows.
I_______________________________________________________________
See Also
java.awt.Component, java.awt.Toolkit, java.awt.Window.
Windowpeer
java.awt.pcer
loBackf)
toBackf)
PIRPOSL Moves the window behind all other windows.
SYM'AX void toBackQ
SEL ALSO java . awt. Wi ndow. toBackQ.
toFrontO
PE RPOSE Moves the window in front of all other w indov
SYM’AX void toFrontO
SHK ALSO j ava.awt.Wi ndow.toFront().
1556
lllVIV/k
20 plane.
See lines; o\als; points; polygons; rectangles; Shape
30 outline.
Graphi cs.draw3DRectQ;695
painting filled rectangle u ith,
Graphics,fi113DRectQ;714
SystemColor;1382
controlDkShadow;1394
controlHigh1ight;1394
controlLtHighlight;1394
control Shadow;1394
control Text: 1395
A
a.
AWTEventMulticaster: 133
ABORT,
ImageObserver: 834
abort status,
images,
TmageConsumer.IMAGEABORTED; 816
ImageObserver.ABORT: 834
MediaTracker.ABORTED:1020
ABORTED.
MediaTracker;1020
abortGrabbing(),
PixelGrabber; 1170
aborting.
pixel delivery'.
PixelGrabber. abortGrabbingO; 1170
accessor methods,
properties,
PropertyDescriptor.getReadMethodQ:
1238
PropertyDescri ptor .getWri teMethodQ;
1240
signature,
IndexedPropertyDescriptor:856
PropertyDescriptor; 1231
actionO,
Component, replaced by ActionListener; 317
action commands.
See action events
ACTION-EVENT.
Event, replaced by
ActionEvent.ACTION-PERFORMED; 551
ACTION-EVENT_MASK,
AWT Event:120
action events.
See Aho AWTEvent
ActionEvent;31
buttons.
Button:189
Button. addActionLi stenerO; 189
Button. getActionCommandQ; 194
Button.processActi onEventО; 196
Button. removeActionLi stenerO; 197
Button. setActionCommandO; 197
callback methods.
Actionl istener. actionPerformedQ; 43
components that fire.
See Button; Li st; Menuitem; TextFi eld
Table, AWT Event; 115
dispatching. AWTEventMulti caster.action-
PerformedQ: 133
event id.
ActionEvent.ACTION-FIRST; 34
ActionEvent.ACTION-LAST; 35
Acti onEvent.ACTION-PERFORMED; 35
firing, notification. ActionLi stener. action-
PerformedQ: 43
flow-. Figure, ActionEvent; 32
handling.
ActionLi stener, actionPerformedQ; 43
behavior description, ActionLi stener; 41
listeners. ActionLi stener: 41
INDEX
action events t continued)
lists,
Li st .addActionLi stenerQ: OSO
Li st. processAct! onEventQ; 1002
List.removeActionli stenerQ: 1005
mask for. AWTEvent.ACTTON„EVENT_MASK: 120
menu items,
Menuitem.addAct ionLi stenerQ; 1091
Menuitem. getAct ionCommandQ; 1096
Menuitem.processActionEventQ: 1098
Menuitem.removeActionLi stenerQ;1099
Menuitem. setActionCommandQ: 1100
modifier kc>s, ActionEvent .getModifiersQ;
37
retrieving command name,
Acti onEvent.getActionCommandO:37
state. ActionEvent .paramStringQ: 38
term definition.
ActionEvent:31
AWTFvent; 110
text fields.
TextField.addActionLi stenerQ: 1458
TextField.processActionEvent();1464
TextField. removeActionl i stenerQ: 1465
ACTION_FIRST.
ActionEvent: 34
action keys,
key codes.
KeyEvent: 927, 938
Table. KeyEvent; 927
testing for, KeyEvent. i sActionKeyO; 941
ACTION-LAST,
Acti onEvent;35
ACTION_PERFORMED,
ActionEvent;35
ActionEvent; 31
ACTION-FIRST: 34
ACT10N_l AST; 35
ACTION-PERFORMED; 35
ActionEventО:35
AL I.MASK; 36
CTRL-MASK: 36
getActionCommandQ; 37
getModi fi ersQ;37
MFTA-MASK; 38
paramStri ngQ; 38
SHTFT_MASK: 39
ActionEventO,
ActionEvent; 35
ActionListener; 41
act ionPerformedQ: 43
actionPerformedO.
Acti onLi stener; 41
AWTEventMulticaster; 133
activated.
term definition. Wi ndowEvent: 1539
active events.
ActiveEvent:44
term definiiion. ActiveEvent; 44
active state.
ot applet,
testing.
Applet. i sActiveQ; 87
Appletstub, i sActiveQ; UH
activeCaption.
SystemColor; 1389
acti veCaptionBorder.
SystemColor: 1190
activeCaptionText.
SystemColor:1392
ActiveEvent;44
dispatchQ; 45
adapters,
ComponentAdapter:396
ContainerAdapter;458
event, term definition. AWTEvent; 111
FocusAdapter: 628
KeyAdapter: 919
MouseAdapter:1121
MouseMotionAdapter;1149
Wi ndowAdapter; 1535
addQ,
AWTEventMul ti cast er: 134
(hoi ce;254
ChoicePeer: 266
Component:119
Contai ner; 431
List; 988
Li stPeer; 1011
Menu;1044
MenuBar;1057
Rectangle;1292
addActionListener().
Button;192
list; 989
Menuitem;1091
TextField; 1458
1558
addAdjustmentLi stenerO, Adjustable:56 Scrollbar: 1326 addComponen t Li s tene r (). Component: 320 addConsumerQ, Fi1teredlmageSource:615 ImageProducer: 843 MemorylmageSource:1032 addContai ner Li stenerO, Container; 432 addFocusLi stenerO, Component:321 addHelpMenuO, MenuBarPeer:1068 addimageО, Med iaTracker; 1021 addlmpl (). Contai ner: 432 Sc roll Pane: 1349 addinternal(), AWTEventMulticaster; 135 addMouseMotionLi stenerO, Component;322 addNoti fyO, Button;193 Canvas:205 Checkbox;224 CheckboxMenuItem;242 Choice: 255 Component: 322 Contai ner: 433 Di alog:512 Fil eDi alog;605 F rame: 670 Label:957 List; 991 Menu;1045 MenuBar; 1058 MenuItem;1092 Panel: 1164 PopupMenu:1196 Sc rol Ibar: 1327 Scroll Pane: 1349
additemО, ChoicePeer, replaced by addQ ; 266 ListPeer, replaced h\ add(); 1011 Choice:255 List: 989 MenuPeer: 1110 addltemListenerО, Checkbox:224 CheckboxMenuItem;241 Choice: 255 ItemSelectab1e:917 List: 990 addKeyLi stenerO, Component;321 addLayoutComponentО, BorderLayout:179 CardLayout;211 FlowLayout; 621 Gri dBaglayout;761 Gri dl ayout: 783 LayoutManager;969 1ayoutManager2;979 addMenuQ, MenuBarPeer; 1068 addMouseLi stener(), Component;321 lextArea; 1408 TextField;1459 Window;1524 addPointО* Polygon;1187 addPropertyChangeLi stenerO. Customi zer; 498 PropertyChangeSupport;1227 PropertyFditor;1255 PropertyEditorSupport;1272 addSeparatorO, Menu;1046 MenuPeer; 1110 addTextLi stenerO, TextComponent: 1430 addVetoableChangeLi stener О, VetoableChangeSupport; 1511 addWi ndowLi stenerO, Window:1524 Adjustabl e: 47 addAdjustmentLi stenerO: 56 getBlocklncrement():57 getMaximumQ: 57 getMinimumO; 57 getOri entationO: 57 getUni tlncrementO; 58 getValue():58
A
INDEX
Adjustable ^ofuimiedf
getVi si bl eAmountO: 58
HORIZONTAL:59
removeAdjustmentLi stenerO;59
setBlocklncrementO: 59
setMaximumO - 60
setMinimumО; 60
setUnitlncrement(); 60
setVal ueO: 61
setVisibleAmountO: 61
VERTICAL;61
adjustable components.
Adjustab1e:47
block increment.
Ad justable.getBlоскIncrement(): 57
Adjustable.setBlocklncrementO; 59
or icntatioii.
Adjustable. getOri entationO; 57
Adjustable.HORIZONTAL; 59
Adjustable.VERTICAL: 61
i)pe, term definition. AdjustmentEvent: 62
unit increment
Adjustab! e. get Un i tine rement О: 58
Adjustable. setUni tlncrementO: 60
\ allies.
Adjustable.getMaximumO; 57
Adjustable. getMi nimumO: 57
Adjustable.getValue(): 58
Adj ustable.getVi s i bl eAmount О; 58
Adjustable.setMaximumO; 60
Adjustable.setMi nimumO; 60
Adjustable.setValue(): 61
Adjustable.setVi sibleAmount O; 61
range, term definition. Adjustable: 47
term definition. Adjustable: 47
adjustable value,
range, term definition. Scrol Ibar: 1321
term definition. Scroll bar; 1321
AdjustForGravityO,
GridBagLayout: 764
ADJUSTMENT_EVENT_MASK.
AWTEvent; 120
adjustment events,
Adjustable;48
AdjustmentEvent:62
callback methods. AdjustmentLi s-
tener.adjustmentValueChangedO:73
change notification. Adjustment-
Fvent.ADJUSTMFNT.VAt UF_CHANGFD; 66
components that fire. Table. AWTFvent; 115
dispatching. AWTEventMulti caster.adjust-
mentVal ueChangedO: 135
event id,
AdjustmentEvent.ADJUSTMENT „FIRST; 65
AdjustmentEvent.ADJUSTMENT-LAST: 65
flow. Figure. AdjustmentEvent: 63
listener.
Adjustable.addAdjustmentLi stenerO:
56
Adjustable,removeAdjustment
ListenerO: 59
Sc rol Ibar: 1326
ScrolIbar.addAdjustmentListenerO:
1326
listeners.
Adjustment! istener; 70
Scrol1 bar.removeAdjustment-
Li stenerO: 1332
mask for. AWTFvent .ADJUSTMENT EVENT. MASK;
120
retrieving object that fired, getAdjustable(): 67
scroll bars.
Scrollbar.processAdjustmentEventO:
1331
Scrol Ibar.processEventO: BT?
scrollbars. Scrol Ibar; 1322
state, Ad justment! vent. paramStringO: 68
types.
Adjustment Event.getAdjustmentTypeO;
68
AdjustmentEvent.TRACK; 69
AdjustmentEvent. UNI T .DECREMENT; 69
AdjustmentEvent.UNIT-INCREMENT; 69
BLOCK .DECREMENT; 67
BLOCK-INCREMENT; 67
value.
Adjustment Event. getValueO; 68
property, term definition. AdjustmentEvent:
62
ADJUSTMENT-FIRST,
Adjustment!vent:65
ADJUSTMENT-LAST,
AdjustmentEvent; 65
ADJUSTMENT_VALUE_CHANCED,
AdjustmentEvent; 66
1560
AdjustmentEvent:62
AD JUSTMENT-FIRST; 65
ADJUSTMENT_LASI: 65
ADJUSTMENT VALUE-CHANGED:66
AdjustmentEvent О; 66
BLOCK-DECREMENT; 67
BLOCK-INCREMENT: 67
getAdjustable0: 67
getAd justmentTypeO: 68
getValueO; 68
paramStri ng();68
TRACK;69
UNIT_DECRFMENT; 69
UMT-INCREMFNT; 69
AdjustmentEventО,
AdjustmentEvent; 66
AdjustmentListener:70
adjustmentValueChangedO: 73
adjustmentVal ueChangedO,
Adjustment! i stener; 73
AWTEventMul ti caster: 135
algorithms,
encryption. .LAR support for. Applet: 76
message digest, term definition. Applet: 76
scaling,
AreaAveragingScaleFilter;101
Image, SCALE ARFA_AVERAGING specification
of: 808
Image.SCALF-REPLICATF speculation of; 809
ReplicateScaleFilter; 1304
specification of.
Image.SCALE-DFFAULT: 809
Image.SCALF-FAST: 809
Image.SCALE-SMOOTH: 810
Milnes used by.
Repli cateScaleFiIter.sreeols[1;
1307
Rep IicateScaleFi1 ter.srerows[1;
1308
alignment,
based layout. LayoutManager?; 972
bottom. Component. BOTTOM-ALIGNMENT: 323
center. Component .CENTER-ALIGNMENT: 323
components. Flow! ayout: 618
flow layout,
FlowLayout.CENTER: 621
I low!ayout.getAlignment(J; 622
FlowLayout.setAlignmentO: 626
labels.
Label;955
Label. CENTER: 957
1abel. getAlignmentO; 957
Label. LEFT; 958
Label. RIGHT; 959
Label. setAlignment0: 959
label Peer. setAl ignment (); 963
left.
Component,LEFT-ALIGNMENT: 356
FlowLayout.LEFT: 624
point.
Container;422
term definition, LayoutManager?; 972
property,
Contai ner: 422
term definition.
Component;303
LayoutManager?:972
right.
Component.RIGHT. ALIGNMENT; 382
FlowLayout.RIGH7; 626
setting. LayoutManager?; 973
top. Component. TOP_Al IGNMENT: 390
ч.
BorderLayout.getLayoutAlignmentXO*.
181
CardLayout.getLayoutAli gnmentXO:21
Component.getLayoutAlignmentXO; 336
Contai ner. getLayoutAl i gnmentXO; 435
Gri dBagLayout. get Layout Al ignmentXO
767
LayoutManager?.getl ayoutAlign-
mentXO: 979
y,
BorderLayout.getLayoutAl ignmentYO;
18!
CardLayout.getLayoutAlignmentYO; 21
Component .get Layout Al i gnmentY(); 336
Contai ner. getLayoutAl ignmentYO: 43(
GridBagLayout.getLayoutAlignmentYO
767
LayoutManager?.getl ayoutAlign-
mentYO: 980
ALLBITS,
ImageObserver;834
alTowsMultipi eSeiections О,
Li st, replaced by i sMu 11 i pl eMode О; 991
alpha component,
bit mask, Di rectColorModel . getAlpha(); 5:
A
INDEX
alpha component (eoiniiwed)
pixels.
ColorModel . getAlphaO- 299
Di rectColorModel.getAlpha();531
IndexColorVodel.getAlphaO:848
IndexColorModel . getAl phasO: 849
Alt key,
InputEvent.AlT_MASK; 8 74
testing, InputEvent. i sAl tDownO: 878
ALTJ4ASK,
Fvent. replaced by Input I vent .Al T_MASK: 551
Acti onEvent; 36
InputEvent: 874
ancestor,
container, testing. Container, i sAncestorOf():
442
anchor,
gridbag.
type. GridBagConst raint s.Cl Ml R: 741
type. GridBagConstrai nts. FAST; 744
type. GridBagConstraints.NORTH: 753
type. Gri dBagConst rai nt s .NORTHEAST: 753
type. Gri dBagConstrai nt s.NORTHWl ST; 75 1
type. Gri dBagConstrai nts . SOUTH; 756
type. GridBagConstraints .SOUTHEAST; 756
type. GridBagConstraints.SOUTHWEST: 756
type. GridBagConstraints.WEST; 758
as giidbag constraint, term definition.
GridBagConstraints:738
GridBagConstraints.anchor; 741
anchor,
GridBagConstraints: 741
animation,
See Ahn Medial racker
setting frame mode. MemorylmageSou rce. set
AnimatedO; Ю35
appendО,
TextArea:1408
appending,
strings to text areas. TextArea.append(): 1408
appendTextC).
TextArea. replaced by appendО: 1409
Appl et; 74
dest roy():83
getAppletContext():Ri
getAppletlnfoO: 83
getAudioClipO: 84
getCodeBaseO; 8I
getDocumentBaseO; 85
getImageO: 85
getLocaleO; 85
getParameter():86
getParameterlnfoO; 86
i ni tO ; 87
isActi ve(): 87
playO;
resizeО: 89
setStubO: 90
showStatus():90
startO; 90
stop():91
applets).
See AK<> compoik'iMs: panels: I RLs. WWW
accessible. Appl etContext. getAppletsО: 94
active state.
testing.
Appl et.i sAct i ve().87
AppletStub. isActiveO: 100
Applet:74
archive^ Applet; 76
bounds.
Applet. resi zeO; 89
AppletStub.appletResize0: 98
code base I 'Rl,.
Appl et. getCodeBaseO: 84
Арр 1etStub.getCodeBaseO; 99
context.
See Aho containers
Applet.getAppletContext():83
Applet.showStatusО;90
AppletContext: 9?
AppletStub.getAppletContext():99
as environment for an applet. AppletContext
92
companion with applet stub. AppletStub: 98
term definition. Applet: 74
creating. Applet: 75
destroy ing. Applet .destroyO: 83
document base I’RL.
Applet.getDocumentBaseO:85
AppletStub.getDocumentBaseO; 99
HTML lag. Applet; 77
information. Applet.getApplet IntoO: 83
initializing. Applet .initO: 87
locale. Applet.getLocaleO: 85
parameter value.
Appl et.getParameterO: 86
Appl etStub. getPararret er 0: 100
1562
parameters.
Applet;77
Applet .getParameterlnfoO: 86
reference to. Appl etContext .getAppl et(): 94
serializing. Applet: 75
starting. Applet, st art(); 90
states, Appl et: 75
stub.
Applet .setStubQ: 90
AppletStub:98
term defimtion. Applet: 74
viewer. as applet context. 1:1цнге. AppletContext:
92
AppletContext;92
getApplet();94
getAppletsО;94
getAudioCl ipO: 95
getImageО:96
showDocurent(); 96
showStatusO: 97
appletResizeO,
Applet St uh: 9x
applets,
AppletContext.getApplets(); 94
displaying, Applet. showStatus(): 90
AppletStub;98
appletResize();98
getAppletContextQ: 99
getCodeBaseO; 99
getDocumentBaseO: 99
getParameterO: 100
i sActivef): 100
arc,
elliptical, Graphics . drawArcO; 697
filled, painting. Graphics, fi 1 lArcO: 715
archives.
applet. Appl et: 76
a real s),
averaging scale filter class,
AreaAveragingScalel ilter; 101
clipping,
Graphics.cl ipRectO; 690
Graphics.getClipO: 724
Graphics.getCl ipBoundsQ; 725
Graphics .setС 1 ipQ: 728
term definition. Graph i cs; 687
display, component, term definition,
GridBagLayout;759
on drawing surface, Grap hi cs . copyAreaO; 691
rectangle, testing for. Rectangle. isEmptyQ;
1297
text.
event types fired by. Table. AWTtvent: 115
term definition. TextArea: 1405
TextArea:1405
TextAreaPeer: 1423
AreaAveragingScaleFilter:101
AreaAveragingScaleFi IterQ; 104
setHintsO; 104
setPixel sO: 104
AreaAveragingScaleFi1 ter О ♦
AreaAveragingScaleFi Iter; 104
arg,
Fvent. replaced by event-specific fields and met
ods:55l
ArrangeGridO,
Gri dBagLayout: ?64
arrays,
byte.
ГontMetri cs.bytesWi dth();658
painting as characters.
Graphi cs .drawBytesQ; 699
character.
FontMetrics .charividthО; 659
Graphics.drawCharsО; 699
width, determining. Fontsetri cs. chars-
WidthQ: 659
indexed property type, term definition,
TndexedPropertyDescriptor; 854
ascent,
lont,
FontMetrics.getAscentO: 661
FontMetrics.getMaxAscent(); 664
term definition. FontMetrics. 653
a11ributeNamesО.
FeatureDescriptor: 595
attributes,
hean descriptor. Table-. 155
bean indexed property descriptois. Table.
TndexedPropertyDescri ptor:855
feature descriptor.
default values. Table. FeatureDescriptor:
591
extension, FeatureDescriptor; 592
FeatureDescriptor.att ribut eNames();
595
term definition. FeatureDescriptor: 591
л
INDEX
attributes (com in urd)
features,
FeatureDescriptor.setHidden0: 599
FeatureDescri ptor,setValue():600
testing expert,
EeatureDescriptor. isExpertO; 598
testing hidden,
FeatureDescri ptor. i sHiddenO; 598
audio clips,
AudioClip; 106
playing.
Applet.play();89
AudioC 1 ip. loop(): 106
AudioClip.play();106
retriev ing.
Applet. getAudioCIi p; 84
Appletcontext.AudioClip;
stopping, AudioCi ip. stop(); 107
term definition. AudioCi ip; 106
AudioCi ip;106
loopO; 106
playO; 106
stopO; 107
avoidingGui().
Vi si bi 1i ty;1517
AWT (Abstract Window Toolkith
components, event types tired by. Table. AW I Event:
115
errors. AWTError; 108
events.
AWTEvent; 1 10
AWTEvent .getIDO: 123
AWTEvent.id; 123
maximum value for reserved AWT id**.
AWTEvent.RESERVED ID_MAX;I26
term definition, AWTEvent: 110
exceptions, AWTException; 153
AWTError;108
AWTErrorO; 109
AWTErrorO,
AWTError: 109
AWTEvent; 110
ACTION.EVENT-MASK; 120
AD1US1MFNT„EVENT_MASK; 120
AWTEventO: 120
COMPONENT_EVENT_MASK: 121
consumeO; 122
consumed:122
CONTAINER-EVENT MASK; 122
FOCUS EVFNT *ASK;123
getIDO: 123
id: 123
isConsumed(); 123
ITEM_EVEN1.MASK; 1 ?4
KEY^EVENTJMSK; 124
MOUSE_FVENT_MASK: 124
MOUSt_MOTION_l VENT-MASK; 125
paramStringO; 125
Ri SFRVED_ID.,MAX; 1 ?6
TEXT .1 VENT-MASK: 126
toStri ng О; 126
WINDOW..FVENT MASK; 126
AWTEventO.
AWTEvent:120
AWTEventMulticaster: 128
a: 133
act ionPerf ormedO; 133
add():134
addinternal():135
adjustmentVal ueChangedO; 13:
AW1 FventMul ti casterO; 136
b; 136
componentAdded();136
componentHidden();137
componentMovedO - 138
componentRemoved0: 138
componentResized(); 1 ^8
componentShown О; 139
focusGained(): 139
focusLostO: 140
i temStateChangedO: 140
keyPressedf);141
keyReleasedO: 141
keyTypedO; 142
mouseCli ckedO; 142
mouseDraggedO: 143
mouseEnteredO: 143
mouseExi tedO: 144
mouseMovedOi 144
mousePressedO; 144
mouseReleasedO: 14S
removeО:145
removelnternal(): 146
save():147
savelnternal():148
t extVal ueChangedO: 148
windowActivatedО:149
wi ndowClosedO; 149
1564
windowClosingO; 150
wi ndowDeacti vatedO: 150
windowDei coni f iedO: 151
windowIconifiedO: 151
windowOpenedO; f 51
AWTEventMul ti casterQ,
AWTEventMulticaster; 136
AWTException:153
AWTExceptionO; 153
AWTException О,
AWTException; 153
в
ь,
AWTEventMu1ticaster; 136
background,
color.
Component .getBackgroundO; 336
Component.setBackgroundO:383
ComponentPeer.setBackgroundO; 418
Graphics; 686
baseline,
fonts, term definition, FontMetrics; 653
BeanDescriptor:154
BeanDescriptorО;157
getBeanClassO; 159
getCustomizerClass(): 160
BeanDescriptor(),
BeanDescriptor; 157
Beaninfo;161
getAdditionalBeanlnfoO; 163
getBeanDescriptor();163
getDefaultEventIndex(); 164
getDefaultPropertylndex();164
getEventSetDescri ptorsO; 165
getlconO; 165
getMethodDescriptorsO; 165
getPropertyDescri ptorsO; 166
ICON „COLOR-16x16; 166
ICON_COLOR_32x32;167
ICON M0N0_16x16;167
ICON_MONO_32x32; 167
beans,
hean-info,
BeanDescriptor; 154
Beaninfo; 161
Beaninfo.getAdditionalBeaninfoО; 163
Beaninfo. getEventSetDesc ri ptorsO; 165
Beaninfo.getlconO; 165
Bea n Inf o. getMethodDescri ptorsO: If
Bean Info .getPropertyDescri ptorsO:
Introspector.getBeanlnfoO: 900
Introspector.getBeanlnfoSearch-
Path();901
Introspector.setBeanlnfoSearch-
Path();901
introspector use. Introspector: 890
retrieving, Simp]eBeaninfo.getAdditior
alBeanInfo():1369
SimpleBeanlnfo; f365
SimpleBeanlnfo.getEventSet-
Descri ptorsO; 1371
SimpleBeanlnfo. getlconO: 1371
SimpleBeanlnfo.getMethodDescri p
torsO; 1372
S imp]eBeaninfo.getProperty-
Descri ptorsO: 1372
BeanDescriptor: 154
Beaninfo; 161
Beans; 168
casting, into superclass.
Beans.getlnstanceOfO;171
class, as bean descriptor attribute. Tabic: 155
Class object.
BeanDescriptor. getBeanClassO; 159
BeanDescriptor.getCustomizerClasst
160
creating. Beans . i nstant i ate(): 172
Customizer; 486
default.
Beaninfo.getDefauItEvent Index О;16^
Beaninfo.getDefaultPropertylndex():
164
event set. term definition, Beans; 168
property, term definition. Beans: 168
SimpleBeanlnfo.getDefaultProperty-
lndex О ; 1371
descriptor,
attributes, Table: 155
BeanDescriptor; 154
Beanlnfo.getBeanDescriptorO;163
introspector use. Beaninfo: 161
SimpleBeanlnfo.getBeanDescri ptorО:
1370
term definition. BeanDescriptor; 154
в
ixdex
beans (continued)
editing.
EventSetDesc ri ptor;577
properties. Customizer: 486
properly editor relationship to bean editor.
PropertyEditorSupport:1267
PropertyEditor:1248
PropertyEdi tor.getCustomEditorQ: 1256
PropertyEdi torSupport.qetCustom-
EditorO; 1275
editor, environment interaction. Beans: 168
environment, term definition. Beans: 168
EventSetDesc r i ptor: 576
exceptions. Int rospectionl xcept i on: 887
feature descriptors.
Feat ureDescriptor; 591
introspector construction of. Introspector:
890
SimpleBeanlnfo:1365
FeatureDesc riptor: 591
home page. See http://splush.javasofi.com/beans/
icon. Simpl eBeanl nfo.get IconQ: 1371
icon type field.
Beaninfo.ICON.COI0R_16xl6:166
Beaninfo.ICON COLOR_32x32: 167
IndexedPropertyDescri ptor;854
get 1ndexedPropertyType():861
getIndexedReadMethod(): 861
getlndexedWri teMethod 0: 865
initializing.
properly values.
PropertyEdi tor.get!avalniriali za
t ionStri ng(): 1256
PropertyEdi torSupport.getJava
InitializationString():1278
IntrospectionException;887
Introspector: 89(1
JavaSoft URL.
See http://splash.javasoft.com/beans/
loading images relative to.
SimpleBeanlnfo. loadlmaqeO: 1372
MethodDescriptor; 1116
monochrome image icon type field.
Beaninfo.ICON_MONO_16xl6: 167
Beaninfo.ICON MONO_32x32; 167
package.
BeanDescriptor: 154
Beaninfo; 161
Beans:168
Customi zer: 486
EventSetDescriptor: 576
F eatureDescr i ptor: 591
IndexedPropertyDescriptor:854
IntrospectionException;887
Introspector;890
MethodDescri ptor: 1116
ParameterDescriptor:1166
PropertyChangeEvent:1215
PropertyChangeListener:1223
PropertyChangeSupport: 1225
PropertyDescriptor: 1229
PropertyEditor; 1248
Propertyl ditorManager: 126?
PropertyEditorSupport;1267
PropertyVetoException:1286
SimpleBeanlnfo:1365
VetoableChanqeListener:1505
VetoableChangeSupport:1510
Visibility;1514
ParameterDescriptor; 1166
properties.
Beaninfo.getDefault PropertylndexO:
164
BeanInfo.getPropertyDescri ptors(): 16(
IndexedPropertyDescri ptor.get-
IndexedPropertylypeC): 861
IndexedPropertyDescri ptor.get -
IndexedReadMethodf):861
PropertyChangeEvent:1215
PropertyChangeListener; 1223
PropertyChangeSupport:1225
PropertyDescri ptor: 1229
PropertyEditor; 1248
PropertyEditorManager:1262
PropertyEditorSupport:1267
PropertyVetoException: 1286
SimpleBeanlnfo.getDefaultEvent-
Index();1370
SimpleBeanlnfo.getDefaultPropertyIn
dex():1371
SimpleBeaninfo.getProperty-
Descri ptors():1372
PropertyChangeEvent: 1215
PropertyChangeListener: 1223
PropertyChangeSupport:1225
PropertyDescri ptor; 1229
PropertyEdi tor: 1248
PropertyEditorManager:1262
1566
PropertyEdi torSupport;1267
PropertyVetoException;1286
properties. IndexedPropertyDescri ptor,get-
IndexedWri teMethodO; 865
setting. Customi zer. setobject (); 499
SimpleBeanlnfo: 1365
subclass, testing tor. Beans. i sInstanceOf (); 173
URL for. http://splash.javasoft.eotn/beinis/
VetoableChangeListener; 1505
VetoableChangeSupport:1510
Visibility:1514
WWW home page.
See http://splash.javasott.coni/beans/
Beans; 168
getlnstanceOfO: 171
instantiateO; 172
i sDesignTimeO; 173
isCuiAvai lableO; 173
i slnstanceOf();173
setDesignfineO:174
setGui Avai 1 ableQ; 174
beep O,
Too 1 ki t; 1478
beginValidateO,
Contai nerPee r: 469
black,
Color.black; 282
black.
Color: 282
block,
decrement. BLOCK-DECRFMF\T; 67
increment.
adjustable components, teim definition.
Adjustable: 48
Adjustable .get В lockinc rementO: 57
Adjustable.setBlocklncrement(); 59
BLOCK-INCREMENT; 67
BLOCK-DECREMENT,
AdjustmentEvent: 67
BLOCK-INCREMENT,
AdjustmentEvent: 67
blue,
Color; 283
blue component,
bit mask. Di recrColorModel . getBl ueMaskO;
532
Col or.Ы ue: 283
pixels.
ColorModel .getBlueO: 30(1
Di rectColorModel .getBlueO: 531
IndexColorModel .getBlueO; 849
IndexColorModel.getBluesf):849
retrieving. Col or. getBlueO; 287
BOLD,
Font; 642
border,
color,
SystemColor.activeCaptionBorder;1390
window. SystemColor,windowBorder; 1404
window, SystemColor.inactiveCaption-
Border: 1396
border layout,
See A/iN containt*rl ч I
alignment.
BorderLayout .getl ayoutAlignmentXO:
181
BorderLayout .getl ayoutAlignmentYO:
181
components.
BorderLayout. addLayoutComponentО; 17*
container,
Borderlayout.1ayoutContainer();184
gap.
BorderLayout. getHgapO; 182
BorderLayout. getVgapO; 183
BorderLayout .setHgapO; 187
BorderLayout. setVgapO; 187
invalidating. BorderLayout.invalidate-
LayoutO; 184
layout manager, BorderLayout; 176
location,
BorderLayout;176
Borderl ayout.CENTER:180
BorderLayout.EAST; 181
BorderLayout.NORTH;185
BorderLayout.SOUTH; 187
BorderLayout .WEST; 188
BorderLayout:176
addLayoutComponent0: 179
BorderLayoutO: 180
CENTER;180
EAST: 181
getHgapO: 182
getLayoutAl ignmentXO; 181
getLayoutAl ignmentYO; 181
getVgapO; 183
i nval idateLayoutO; 184
layoutContainerO; 184
в
INDEX
BorderLayout (еипГтиаЬ
maxi muml ayoutSi zeO*. 184
minimumLayoutSizeO; 185
NORTH; 185
preferredLayoutSizeO; 186
removeLayoutComponent(): 186
setHgapO: 187
setVgapO; 187
SOUTH; 187
toStringO; 188
WEST; 188
Border Layout О,
Border!ayout;I8o
BOTH,
GridBagConstraints; 743
bottom,
alignment, Component.BOTTOM_ALIGNMENT; 323
value. Insets. bottom; 884
bottom.
Insets;884
BOTTOM-ALIGNMENT,
Component; 323
bound properties,
PropertyDescri ptor.setBoundО;1246
term definition. PropertyChangeEvent: 1215
testing. PropertyDescriptor.isBoundO: 1242
bounding box,
polygon.
calculating. Polygon.getBoundsO; 1188
Polygon.bounds; I 187
term definition. Polygon: 1184
bounds,
applet.
Applet.resize(); 89
AppletStub.appletResize():98
component.
Component.getBoundsO; 337
Polygon.getBoundsO; 1188
Shape, get BoundsO: 1364
gridbag, adjusting component.
GridBagLayout.Adj ustForGravityO: 764
rectangles. Rec tangle. getBoundsO; 1294
setting. Componentpeer. setBounds0: 419
term definition. Component; 304
bounds,
Polygon;1187
bounds().
Component, replaced by getBoundsO; 323
bounds-relative,
term definition. Mouse! vent: 1132
brighterQ-
Color; 283
buffer,
pixel.
Pi xelGrabber .getHeightO; 1171
PixelGrabber.getPixels():1171
PixelGrabber,getWidth():1172
Button:189
addActionLi stenerO; 192
addNotifyO; 191
Button(); 193
getActionCommandO: 194
getLabe1():195
paramSt ri ng();195
processActionEventO: 196
processEventO: 196
removeActionListenerО;197
setActionCommandO: 197
setLabel():198
Button(),
Button;193
button(s).
action events.
Button.addActionListenerO: 192
Button. get Act ionCommandO: 194
Button.processActionEventО:19f
Button.removeActionLi stenerO:
Button. setActionCommandO; 197
class Button: 189
events.
Button.processEvent():196
types. Tahk\ AWTEvent: 115
labels.
Button.getLabelО:195
Button.setLabelО: 198
ButtonPeer.setLabelO;201
mouse. Mousetvent: 1129
peers,
ButtonPeer:200
creating, Button. addNotifyO: 193
Toolkit. createButtonO; 1479
slate. Button.paramString(); 195
term definition. Button; 189
BUTTON1_MASK,
InputEvent;875
BUTT0N2_MASK,
InputEvent:875
1568
BUTT0N3J4ASK,
InputEvent:875
ButtonPeer;200
setLabelQ: 201
byte arrays,
painting, as characters,
Graphics.drawBytesQ:699
width. FontMetrics. bytesWidthQ; 658
bytesWidthQ,
FontMetrics: 658
c
calculating,
hash code.
colors. Col or. hashCodeO; 292
Font. hashCodeO: 648
Point.hashCodeO; 1181
Rectangle. hashCodeO: 1295
layout. Gri dBagLayout .GetLayoutlnfoQ; 768
si/e,
BorderLayout . maximumLayoutSi zeO: 184
BorderLayout.minimumLayoutSizeО: 185
BorderLayout.preferred!ayoutSi ze():
186
CardLayout.maximum!ayoutSizeО;217
Cardl ayout.mi nimumLayoutSizeO; 217
Card! ayout.preferredLayoutSizeO: 218
Component .getMi nimumSi zeQ; 342
Component.getPreferredSizeO; 345
Component Peer.getMinimumSi zeO: 415
Container.getMaximumSize0: 440
Contai ner. getvi nimumSizeQ; 440
Flow! ayout .mi nimumLayoutSi zeQ: 625
FlowLayout. preferredLayoutSizeQ: 625
GridBagLayout.maximumLayoutSizeQ; 776
Gri dBagL ayout.mi nimumLayoutSi zeQ;7 77
Gri dBagLayout.preferredLayoutSi zeQ:
777
GridLayout .minimumLayoutSizeO: 787
! ayoutManager.preferredLayoutSi zeQ:
970
LayoutManager2.maximumLayoutSize():
981
Li st .getMi ni mumSizeQ; 994
Li st.getPreferredSi zeО;995
Li stPeer.getMinimumSizeO: 1013
TextArea. getMinimumSi zeO: 1411
TextAreaPeer.getMi nimumSi zeQ; 1424
7extAreaPeer.getPreferredSi ze():1424
Text Field. getMi nimumSi zeQ; 1461
TextFi eld.getPreferredSi zeQ: 1462
Text I i el dPeer. getMinimumSi zeQ:1469
callback methods,
action events.
ActionLi stener. actionPerformedQ: 43
adjustment events. Adjustment-
Listener, adjustmen tValueChanged О: 7
clipboard.
Cli pboardOwner. lostOwnershipO: 277
Stri ngSel ection. lostOwnershipO; 137
component events.
ComponentAdapter.componentHi ddenQ;
399
ComponentAdapter.componentMovedО; 3
CorponentAdapter.componentResizedQ
399
ComponentAdapter.componentShownQ; 4
Component! istener. componentHiddenQ
409
ComponentLi stener.componentMovedО:
409
Component!, i stener. component-
Res i zedQ; 410
ComponentLi stener.componentShownQ;
410
Component Peer. handleFventQ: 416
container events.
ContainerAdapter.componentAddedO; 4
ContainerAdapter.componentRemovedО
459
Container! istener.componentAddedO:
467
Contai nerLi stener.Component-
Removed О; 467
focus events.
FocusAdapter.focusGainedQ: 630
FocusAdapter.focusLostO; 630
FocusListener.focusGainedQ: 638
FocusLi stener. focusLostO; 638
item events.
ItemLi stener. i teirStateChangedQ; 913
key events,
KeyAdapter. keyPressedO: 924
KeyAdapter. keyReleasedO: 924
KeyAdapter. keyTypedO: 924
KeyListener.keyPressedO; 953
KeyListener. keyReleasedO; 953
Keyl i stener. keyTypedO; 954
INDEX
callback methods (continued!
listener, as event sei component.
EventSetDescri ptor: 576
mouse events,
MouseAdapter.mouseC1i eked011123
MouseAdapter .mouseEnt eredO: 1123
MouseAdapter .mousetxi tedO; 1124
MouseAdapter.mousePressedO: 11 24
MouseAdapter .mouseRel easedQ: 1128
Mouse! istener.moused ickedO: 1147
MouseLi stener.mouseEnteredО: 1147
MouseLi stener.mouseExi tedO; 1148
MouseLi stener .mousePressedO; 1148
MouseL i stener.mouseReleasedO; 1148
MouseMot i onAdapte r.mou seDragged():
1153
MouseMoti onAdapter .mouseMovedO: 1153
MouseMoti onL istener.mouseDraggedO:
1156
MouseMotionListener.mouseMovedO: 1157
propertv change events.
PropertyChange! i s-
tener. propertyChanqeO; 1224
VetoableChangel i stener.vetoable-
Change();1508
text events.
TextLi stener. t extValueChangedO: 1471
window, events.
Wi ndowAdapter .wi ndowActi vated(); 1536
Wi ndowAdapter .wi ndowClosedO: 1536
WindowAdapter.windowClosingO: 1536
W i ndowAdapter.wi ndowDeacti vated();
1537
Wi ndowAdapter.wi ndowDei con i f iedO:
1537
Wi ndowAdapter.wi ndowlconifiedO:1538
Wi ndowAdapter. wi ndowOpenedO; 15 38
Wi ndowLi stener.wi ndowActivated0: 1551
Window! istener.windowClosedO: 1551
Wi ndowListener.wi ndowClosi ng 0:1552
Wi ndowLi stener.wi ndowDeacti vatedO;
1552
Window! istener.windowDeiconifiedO;
1553
WindowLi stener.windowlconifiedO; 1553
Wi ndowLi stener, wi ndowOpenedO; 1554
canFiIterlndexColorModel,
RGBImageFilter: 1311
canvas*
components.
Canvas;20?
Canvas.pai nt О; 206
term definition: 202
event types fired by. Table, AWT! vent: 115
peers.
CanvasPeer: 207
creating. Canvas. addNot i fy O: 205
Tool ki t. c reateButtonO: 1479
Canvas;202
addNotifyO: 205
paint(): 206
CanvasPeer:207
card layout*
CardLayout:208
horizontal gnp.
CardLayout. getHgapO; ? 13
CardLayout. setHgapO; 219
lay ing out components,
ardl ayout. 1 ayout Con tai nerO; 216
stale. CardLayout . inval idatel ayoutО; .^16
\ ertical gap.
CardLayout .getVgapO; 215
CardLayout. setVgapO; 219
v-alignmcnt.
CardLayout.getLayoutAl ignmentXO; 21
v alignment.
CardLayout.getLayoutAlignmentYO; 2!
CardLayout;208
addLayoutComponent0:211
CardLayout О;211
fi rst():212
getHgapO: 213
getLayoutAlignmentXO; ?I?
getl ayoutAl ignmentYO; 212
getVgapO; 215
invalidateLayout():216
last();216
layoutContai nerO; 216
maximumLayoutSizeO: 217
minimumLayoutSizeO: 217
nextO: 217
preferred! ayoutSi zeO: 218
previ ous():218
removeLayoutComponentO:219
setHgapO: 219
setVgapO: 219
1570
show(): 220
toStri ngO: 220
CardLayoutО.
CardLayout;211
cascading,
menus, term definition, l^enu; 1040
casting,
beans, into .superclass, Beans. getlnstanceOfO:
171
cells,
locution, GridBagt ayout. JocationO; 773
maximum gridbag number,
GridBagLayout.MAXGRIDSIZE;776
center.
alignment.
BorderLayout-CENTER:180
Component.CENTER-ALIGNMENT: 323
FlowLayout .CENTER; 62]
GridBagConstraints.CENTER; 743
Label. CENTER;957
CENTER,
BorderLayout; 180
F1owLayout: 621
GridBagConstraints; 743
Label;957
CENTER-ALIGNMENT,
Component: 323
change,
notification. Adjustment-
Event . ADJUSTMENT. VALUE-CHANGED; 66
CHAR_UNDEFINED,
KeyFvent; 933
characters.
Sec Aho fonts; keyboard; strings: text
array width,
FontMetri cs.charsWidthО; 659
FontMetrics.charWidth(): 659
key,
KeyEvent.CHAR-UNDFFINED: 933
KeyEvent .get KeyCharO: 935
KeyEvent. setKeyCharQ: 949
painting,
Graphics.drawBytesО; 699
Graphics.drawChars(): 699
text area replacement.
TextArea. replaceRangeO; 1416
TextAreaPeer. replaceRangeO; 1426
charsWidthO<
FontMetri cs: 659
charWidthO,
FontMetrics:659
check state.
term definition. CheckboxMenuItem: 239
checkAllO.
MediaTracker: 1021
checkbox,
components.
Checkbox; 221
term definition. Checkbox: 221
current.
CheckboxGroup.getSelectedCheckboxO:
237
selected, term definition: 233
events.
Checkbox.processEventO: 228
Checkbox.processItemFventO; 228
types, Tu/j/c. AWTEvent: 115
group,
Checkbox .getCheckboxGroupO; 225
Checkbox.setCheckboxGroupO: 229
CheckboxGroup;233
CheckboxPeer.setStateО;250
choice components compared with: 233
term definition, Checkbox; 221
label,
Checkbox.getLabel(); 226
Checkbox.setLabel(); 230
CheckboxPeer.setLabelO; 250
menu item.
CheckboxMenuItem; 239
CheckboxMenuItem.getSelected-
ObjectsO; 242
CheckboxMenuItem.getStateO: 243
CheckboxMenuItem.paramString(): 243
CheckboxMenuItem.processEventО; 243
CheckboxMenuItem.processitemEventО;
244
CheckboxMenuItem.setStateO; 245
CheckboxMenuItemPeer: 247
CheckboxMenuItemPeer.setStateO: 248
event types tired by Table. AWTEvent: 115
peers, creating,
CheckboxMenuItem. addNoti fу 0:242
Toolkit.createCheckboxMenuItemО;I4X(
peers,
CheckboxPeer: 249
creating. Checkbox. addNotifyO: 224
Toolki t. createCheckboxO; 1480
INDEX
checkbox (cun finncd)
state.
Checkbox.getStateO; 226
Checkbox.paramStringO; 227
Checkbox. setStateO: 232
CheckboxPeer. setStateO; 250
Checkbox:221
addltemLi stenerQ:224
addNoti fy Q; 224
CheckboxO; 224
getCheckboxGroupO; 225
get Label Q; 226
getSel ectedObjectsO: 226
getStateO; 226
paramString(): 227
processEventO; 228
processItemEventО> 228
removelterrListenerO; 229
setCheckboxGroupO: 229
setLabel Q: 230
setStateO: 232
CheckboxO,
Checkbox:224
CheckboxGroup:233
CheckboxGroupO; 233
get Current(). replaced bv
getSelectedCheckboxО:236
getSelectedCheckboxО;237
setcurrent О. replaced b>
setSelectedCheckboxO: 237
setSelectedCheckboxQ: 237
toString(); 238
CheckboxGroupO,
CheckboxGroup:236
CheckboxMenuItem:239
addltemListenerO: 241
addNotifyO; 242
CheckboxMenuItemO: 242
getSelectedObjects():242
getStateO; 243
paramStringO: 243
processEventO: 243
processItemEventO:244
removeltemListenerO;245
setStateO; 245
CheckboxMenuItemО,
CheckboxMenuItem;242
CheckboxMenuItemPeer; 247
setStateO: 248
CheckboxPeer:249
setCheckboxGroupO: 250
setLabel():250
setStateO; 250
checkIDO,
MediaTracker: 1022
checkimageО,
Component: 324
ComponentPeer:413
Toolkit: 1479
child,
container. ContainerEvent.getChi Id'
chil dResi zedO,
Scrol 1 PanePeer;1361
Choice,
addltemListenerO: 255
Choice: 251
add 0:254
addltem():255
addNot i fy();255
ChoiceO: 256
count Iterns О. replaced h\
getltemCountO; 256
getltem();257
getltemCount();257
getSelectedlndexQ; 257
getSelectedTtemQ; 258
getSelectedObjectsO: 258
insertQ: 258
paramStringO; 259
processEventO; 259
processItemEventQ: 260
remove О;260
removeAl1 ():262
removeltemLi stenerO: 262
seiect();263
ChoiceO,
Choice: 256
choice items,
adding. ChoicePeer.add(): 266
event handling.
Choi ce.processEventO;259
Choi ce.processItemEvent 0:260
inserting. Choice. insertQ: 258
items. See Choice
гепк>\ ing.
Choice.removeAl1Q;262
Choi cePeer. removeAl IQ; 267
1572
retrieving.
Choice.getltemO; 257
Choice.getltemCountO: 257
Choice.getSelectedlndexO; 257
Choice.getSelectedltemf): 258
Choi ce.getSelectedObjects 0: 258
selecting.
Choice.selectO: 263
ChoicePeer.select 0: 267
ChoicePeer;265
addO; 266
addltemO. replaced by addO: 266
removeО:267
selectO: 267
choices*
components*
checkbox group vs. CheckboxGroup; 233
Choi ce;251
event types fired by. Tabic. AWT Event; 115
peers,
Choi cePeer; 265
creating. Choice. addNotifyO; 255
Too 1 kit.createChoiceO; I486
state. Choice.paramStringO; 259
term definition. Choice; 251
circles,
filled. Graphics.fi1lOval ( ); 717
outline. Graphics .drawOval (); 704
Class objects,
data flavor use. Data Fl avor: 500
clearQ,
Li st. replaced by removeAl 1 (); 991
ListPeer. replaced by removeAll (); 1012
clearRectO,
Graphics: 689
clickCount,
Event, replaced by
MouseEvent.getClickCount();552
clipboard*
callback method.
Clipboardowner. TostOwnershipO; 277
StringSelection.lostOwnershipO; 1379
Clipboard; 268
contents.
Cl i pboard.getContents();271
Clipboard.setContentsО;275
field. Clipboard.contents; 271
converting strings for. StringSelection: 1374
data flavor use, DataFlavor: 5(X)
encapsulating data fur. Transferable: 1496
name.
Cl ipboard.getNameO: 271
term definition. Clipboard; 268
ow ner.
Cl ipboardOwner: 276
field. С1 ipboard.owner; 275
term definition. Cli pboard; 268
тепieving, loolkit .getSystemCl ipboard0
1493
s\stem. term definition. Clipboard: 268
term definition, Clipboard; 268
Clipboard:268
ClipboardC):271
contents:271
getContentsO; 271
getNameO: 274
owner; 275
setContentsO; 275
ClipboardC),
Clipboard; 271
ClipboardOwner: 276
lostOwnershipO; 277
clipping area*
ret i lev ing,
Graphi cs.getCIi p():724
Graphics.getCIipBoundsQ: 725
setting. Graphics. setCl ip(): 728
shrinking. Graphi cs . cl i pRect 0: 690
term definition. Graphics; 687
clipRectC),
Graphics; 69(1
cl oneO-
GridBagConstraints; 743
TmageF liter: 827
Insets;884
cloning,
gridbag. GridBagConstraints .cloneO; 74.'
image filters, ImageFi 1 ter. clone(): 827
insets. Insets* cl one (); 884
code base I RL,
applet,
Applet: 75
Applet-getCodeBaseO: 84
AppletStub.getCodeBase О;99
collection,
gridbag as collection of components,
GridBagConstraints; 738
с
INDEX
Color: 278
black; 282
blue:283
brighterQ: 283
Color();283
cyan; 285
darker();285
darkGray:285
decodeО:285
equal sQ: 287
getBlue(); 287
getColorO: 288
getGreenO: 290
getHSBColor(): 290
getRedO; 291
getRGBO;29l
gray; 291
qreen; 291
hashCodeO: 292
HSBtoRGBO; 292
IightGray;292
magenta;293
orange;293
pi nk: 293
red;293
RGBtoHSBO; 293
toStringO: 294
whi te;294
ye 11ow;294
ColorO,
Color: 283
color(s),
See Aho RGB
alpha component.
ColorModel.getAlphaO; 299
Di rectColorModel.getAlphaO: 531
IndexColorModel .getAlphaO: 848
IndexColorModel.getAlphas():849
background.
Component .getBackgroundO: 336
Component. setBackgroundO: 383
ComponentPeer. setBackgroundO; 419
title bar. SystemColor.activeCaption: 1389
window. SystemColor.window: 1494
black. Col or. bl ack; 282
blue. Color .blue: 283
blue component.
Color .getBlueO: 287
ColorModel .getBlueO; 300
Di rectColorModel.qetB1ue(): 531
Di rectColorModel,getB1ueMaskO: 532
IndexColorModel .getBlueO: 849
IndexColorModel .getBluesO: 849
border.
SystemColor.act iveCaptionBorder: 1390
window, SystemColor .wi ndowBorder: 1404
brightness. Color.brighter(): 283
class. Color: 278
component background.
SystemColor.control: 1392
e\an. Color, cyan: 285
darkGray. Color. darkGray. 285
darkness. Co I or, darker 0; 285
desktop. SystemColor.desktop: 1 395
equality testing. Co lor. equal s(): 287
filtering.
RGBImageFi1 ter.filter-
IndexColorModel(): 1311
testing. RGBImageFi 1 ter. can! i 1 ter
IndexColorModel:1311
foreground.
Component .qetForegroundO; 339
Component. setl-oregroundO: 385
ComponentPeer. setForeqroundO; л?()
Graphics.getColorO: 725
Graphics. setColorQ: 731
gray
Col or.darkGray:285
Color.gray: 291
Color. 1 ightGray; 292
green. Color. green; 291
green component.
Col or .getGreenO: 290
ColorModel .getGreenO: 300
Di rectColorModel.getGreenO:532
DirectColorModel.getGreenMaskO:532
IndexColorModel .getGreenO; 850
IndexColorModel .getGreensO: 850
hash code, calculating. Color.hashCodeO: 29?
HSB.
Col or .getHSBColorO: 290
term definition. Color; 278
icons.
Beaninfo.ICON_COLOR_16xl6: 166
Beaninfo. ICON. COIOR_32x32; 16/
info-tags.
background. SystemColor. info: 1397
text. SystemColor. infoText: 1397
1574
label text SystemColor. contro I Text; 1395
magenta. Col or. magenta: 293
map. IndexColorModel .getMapSizeQ: 850
menus.
background. SystemColor.menu; 1397
text. SystemColor.menuText: 1398
model.
ColorModel;295
ColorModel.getRGBdefault Q; 301
Component.getColorModelQ: 337
ComponentPeer.getColorModelQ; 414
converted. RGBImageFiIter.newmodel; 1318
converting pixel values to.
ColorModel .getRGBQ; 301
default, term definition. ColorModel; 296
direct, term definition.
ColorModel:296
Di rectColorModel; 527
ImageConsumer.setColorModelQ; 8J7
ImageF i1 ter.setColorModelQ: 828
index, term definition. Col or Mode 1; 295
IndexColorModel .getRGBQ; 851
original. RGBImageFi 1 ter.origmodel; В19
Pi xelGrabber. getColorMode IQ; 1170
PixelGrabber.setColorModel Q; 1175
replacing. RGBImageFi 1 ter. subst i tute-
ColorModelQ; 1320
RGBImageFi1 ter.setColorModel(): 1319
Toolkit.getColorModeIQ;1487
models. IndexColorModel: 845
native components. SystemColor: 1381
orange. Color .orange: 293
pink. Color .pink: 293
red. Color. red; 293
red component.
Color .getRedQ: 291
ColorModel.getRedQ; 300
Di rectColorModel .getRedQ; 533
Di rectColorModel .getRedMaskQ; 533
IndexColorModel .getRedQ: 851
IndexColorModel .getRedsQ: 851
RGB.
Col or. decode Q; 285
Color.getColorQ; 288
RGBImageFilter: 1309
term definition. Color: 278
scrollbars, background.
SystemColor. scrol Ibar; 1398
string representation. Color. toStringQ; 294
system,
string representation.
SystemColor. toStringO; 1403
Tool ki t. loadSystemColorsQ; 1494
system cache. SystemColor; 1382
SystemColor:1381
text.
background. SystemColor.text: 1400
background. SystemColor. textHighlight;
1402
component. SystemColor. textText; 1403
highlighted.
SystemColor.textHighlightText;1402
inactive,
SystemColor.textlnactiveText: 1402
title bat.
SystemColor.acti veCaptionText: 1392
window, SystemColor.windowlext;1404
title bar background.
SystemColor.inactiveCaption:1396
title bar text.
SystemColor.i nacti veCaptionText; 1396
white. Color.whi te; 294
yellow. Color.ye 1 low: 294
ColorModel:295
ColorModel Q: 299
getAlphaQ; 299
getBlueQ: 300
getGreenQ; 300
getPixelSizeQ: 300
getRedQ: 301
getRGBQ; 301
getRGBdefaultQ: 3ol
pixel-bits; 302
ColorModelO.
ColorModel;299
columns.
grid,
GridLayout.getColumnsQ: 783
GridLayout. setCol umnsQ; 788
grids. GridLayout: 781
text area.
retrieving. TextArea.getColumnsO: 1409
TextArea. setCol umnsQ: 1420
text fields,
TextField: 1456
TextField .getCol umnsQ; 1460
TextField. setCol umnsQ; 1465
С
INDEX
columns < (ominui'd/
weight.
GridBagConstraints.weightx; 757
Gr i dBag! ayout. co I urrnWei ghts; 764
u idth. GridBagl ayout. columnwi dths: 766
columnWeights,
Gri dBagl ayout: 764
columnWidths,
GridBagLayout;766
COMPLETE,
MediaTracker:1022
COMPLETESCANLINES,
ImageConsumer:816
Component;303
action О. replaced by Acti onLi stener: 317
add():319
addComponentLi stenerO; 320
addFocusLi stenerO: 121
addKeylistener();321
addMouseLi stenerO; 321
addMouseMotionListenerO:322
addNot i fyO • 322
BOTTOM ALIGNMFNT; 323
boundsO. replaced by getBoundsO; 323
CENIFR_ALIGNMENt/323
checklmageO: 324
Component 0:326
contai ns();326
createTmageO: 329
deliverEvent(), replaced by
di spatchEventO; 331
di sable(), replaced by setEnabl edО; 332
di sabl eFventsO: 332
dispatchEventO:332
doLayout():335
enableO. replaced In setEnabled0: 335
enableEvents О;335
getAl i gnmentXO: 336
getAl ignmentYO; 336
getBackground 0:336
getBoundsO: 337
getColorMode1 0:337
getComponentAtО;337
getCursorO; 338
getFontO; 338
getFontMetrics():339
getForegroundО:339
getGraphicsO; 340
get Local eO; 340
get Locati on();340
qetL ocat ionOnScreenO: *41
getMax irrurrSi ze(): 342
qetMi nimurrSi ze(): 342
getNameO; 343
getParentO: 345
getPeerO; З45
getPreferredSizeO: 345
getSizeO: 46
getloolki t():346
qetT recLock():346
go t Foe us О. replaced by Focus! istener: 34 ’
handlelventO- replaced by
processEvent():348
hi de О, replaced by setVi sible(): 349
imagellpdateO: 349
insideO- replaced by contai ns(): 350
invaIidateO; 350
i sFnabledO: 350
i sFocusI raversableO: 3>1
isShowingO: 353
isValidO: 353
i sVi si ble():353
keyDownO- replaced by KeyListener: 354
keyUpO-те placed by KeyListener; 155
layoutO. replaced by doLayout (): 355
LEFT. ALIGNMENT: 356
1i st():356
locateO- replaced by getComponentAtО; 356
1 ocat ion О. replaced by get Locati on(): 357
lost Focus (). replaced by Focus! i stener: 357
mi nimumSizeO. replaced by
getMinimumSizeO: 158
mouseDownO- replaced by Mouse! istener: 358
mouseDraqO- replaced by
MouseMot ionLi stener: *59
mouseEnterO. replaced by MouseListener: >61
mouseExit O- replaced by MouseLi stener: 361
mouseMoveO. replaced by
MouseMotionl istener: *62
mouseUpO- replaced by MouseListener: 362
moveO, replaced by setLocationO; 363
n ext Focus О. replaced by
t ransferFocusO; 363
pai nt():363
pai ntAl1():364
paramStri ng О;368
post Event О. replaced by
dispatchEvent0: 369
1576
preferredSi zeO. replaced by
getPreferredSizeO: 369
preparelmageO; 369
printO: 370
printAl 1 0: 37()
processComponentEventO; 371
processEventO; 371
processFocusEventO: 373
processKeyEventO; 374
processMouseEventO: 375
processMouseMotionEventO; 375
remove О;376
removeComponentListenerO:376
removeFocusListener ();377
removeKeyl istenerO; 377
removeMouseListenerQ;378
removeMouseMotionListenerO; 378
removeNotifyO: 379
repaintO; 379
requestFocusO: 381
reshape О. replaced by
Component.setBounds0;382
res i?e(). replaced by
Component. setSizeO; 382
RIGHT-ALIGNMENT; 382
setBackgroundO: 383
setBoundsO; 38-4
setCursorO; 384
setEnabledO; 384
setFontO; 385
setForegroundO; 385
sett ocale(); 3X6
setLocati on():386
setNameO; 387
setSi ze();387
setVI si bleO; 387
show(), replaced by setVi si bl eO: 389
s i zeO - replaced by getSize(); 390
TOP-ALIGNMENT; 390
toStri ngO; 390
transferFocusO; 39|
update О;391
validateO: 393
Component О,
Component;326
COMPONENT-ADDED,
Conta i nerEvent;463
COMPONENT-EVENT-MASIG
AWTEvent; 121
component events,
adapter class, ComponentAdapter; 396
cal I hack methods.
ComponentAdapter.componentHi ddenО:
399
ComponentAdapter.componentMovedO;399
ComponentAdapter.componentShownO;400
Component! i stener.componentHi ddenО;
409
ComponentLi stener.componentMoved();
409
ComponentLi stener.component-
ResizedO; 410
ComponentL i stener.componentShownO;
410
ComponentPeer. handleFventO: 116
component events. ComponentAdapter. compo-
nentResi zed();399
ComponentEvent: 401
components that fire, lahlc. AWTEvent: 115
dispatching,
AWTEventMulti caster.component -
HiddenQ: 1-37
AWTEventMulti caster.component•
ResizedO; 138
AWTEventMulti caster.componenthownQ:
139
e\ent id.
ComponentEvent.COMPONENT-FIRST: 404
ComponentEvent.COMPONENT-HIDDEN; 404
ComponentEvent.COMPONENT-LAST; 405
ComponentEvent.COMPONENT MOVED:405
ComponentEvent.COMPONtNl-RESIZFD;405
flow. Нун re. ComponentEvent; 402
listener. Component. removeComponent-
Listener();376
mask for. AWTFvent. COUPON ENT ..EVENT .MASK;
121
processing.
Component.processComponentEventO;371
Component.processEventO: 371
retrieving component that fired.
ComponentEvent.getComponent(): 407
state. ComponentEvent.paramString(): 407
types. lubl(\ AWTFvent; 11 5
COMPONENT-FIRST,
ComponentEvent:404
COMPONENT-HIDDEN,
ComponentEvent;404
с
COMPONENT_LAST.
Component! vent:405
COMPONENT-MOVED,
ComponentEvent;405
COMPONENT-REMOVED,
ContainerEvent:463
COMPONENT-RESIZED.
ComponentEvent: 405
component! s),
Src A/.vu adjustable components: beans: buttons;
canvas components; checkbox components:
menu components: text components
adapters, callback methods.
ComponentAdapter.componentShown(): 400
adding to containers.
Contai ner.add():431
Contai ner.addlmpl();432
adding to lav out.
BorderLayout.addlayoutComponent0: 179
GridBagLayout.addLayoutComponent():
763
LayoutManager?.addLayoutComponent():
9/9
alignment.
Component.U M_AL IGNMENT: 356
Component.RIGHT-AIIGNMENT: 38?
I-1 owl ayout: 618
top. Component .TOP-ALIGNMENT: 390
alignment point, term definition.
L ayoutManagerZ:972
background color, Syst emColor. control; 1392
bounds. Component. getBoundsO: 337
camas.
Canvas: 202
Canvas. paintO: 206
choice, checkbox groups compared with; 2 33
class. Component: 303
color.
Component .getForegroundf); 339
Component. setBackgroundO: 383
Component. setForegroundO; 385
ComponentPeer.set Васkground(): 419
ComponentPeer. setl-oreground(); 420
colors. SystemColor: I 38?
constiaints.
Gri dBagl ayout. lookupConstraintsQ: 776
in container.
Contai ner.getComponentCount 0:437
Contai ner. getComponentsO: 437
current.
CardLayout.fi rstO: 212
Cardl ayout.1ast(): 216
CardLayout.nextO: 217
CardLayout,previous():218
CardLayout. showO: ??(>
cursor. Component .getCursorQ; 318
customer. Customi zer: 486
destroying. ComponentPeer.di spose(): 414
disabling.
Component. setEnabledO: 384
ComponentPeer.set! nabledQ: 419
display area, term definition. GridBagLayout: 759
enabled, testing. Component. i sEnabl ed(): 350
enabling.
Component.setEnabled(): 384
ComponentPeer.setEnabled();419
exceptions.
Ill egal ComponentSt ateExcepti on;79'
toe us traversable.
(omponent. t ransferLocusO: 391
fonts.
Component.get Font():318
Component. setFontO: 385
Component Peer.setFont O; 429
grid. GridLayout, addLayoutComponent (): 783
gridbag.
as collection of. Gri dBagConst rai nt s. 738
GridBagLayout.AdjustForGravi ty(): 764
GridBagLayout.layoutcontainer(): 773
GridBagLayout.setConstraints(): 7/9
height.
GridBagConst raints.gridheight;746
width.
GridBagConstraints.gridwidth. ''46
\ coordinate cell location.
GridBagConstraints.gridx: 748
\-coordinate cell location.
GridBagConstraints.gridy: 749
hiding.
ComponentEvent.COMPONL NT-HIDDEN: 404
ComponentLi stener.componentHidden():
409
invalidating. Component. invalidateO: 350
Living out.
BorderLayout.1ayoutContai ner():184
CardLayout.1ayoutContai ner();216
FlowLayout.1ayoutContainer(): 624
GridLayout.layoutContainer();787
1578
Layoutvanager.layoutContainer(): 969
layout.
Component.getLayoutAli gnmentXQ;336
Component.getLayoutAlignmentYQ; 336
lightweight.
canvas components compared with: 202
native components compared with.
Component:308
listener.
Component.addComponentli stenerO:320
ComponentLi stener: 408
ComponentLi stener.componentMovedО;
409
locale.
Component.getLoca1e():3 40
Component. setLocaleO; 386
term def inition. Component: 306
hx'ation.
Component.getLocat i on():340
Component.getLocationOnScreenO; 341
ComponentPeer.getLocationOnScreenO:
415
menu. See menu components
menu components compared with.
MenuComponent;1069
model. See beans
moving.
Component.setBoundsO:384
Component.setLocation 0: 386
ComponentAdapter.componentMovedО: 399
Componenttvent.COMPONENT-MOVED: 405
Component!, i stener. componentMoved 0:
409
ComponentPeer. setBoundsO; 419
name.
CardLayout.addLayoutComponentО:211
Component.getNameO: 343
Component.setNameO: 387
term definition. Component: 305
native, lightweight components compared with.
Component: 308
painting.
Component,paint О:363
Component. pa i ntAl 1 О; 364
Component.repa int O:379
Component. updateO; 391
ComponentPeer.pai nt 0:417
Componentpeer. repaintO; 418
pantds. Panel: 1162
parent. Component .get Pa rent (): 345
peers.
ComponentPeer: 4! I
creating. Component. addNoti fу(): 322
destroying. Component. removeNot i fy(): 3'-9
Tool kit.createComponentO: 1481
popup menu inconsistencies, PopupMenu; 1193
printing.
information about. Component .1i st (): 356
on a graphics context.
ComponentPeer.pri nt():417
removing.
BorderL ayout.remove! ayout-
ComponentO; 186
Cardl ayout.remove!ayoutComponent О:
219
Contai ner.removeО:453
Contai ner.removeAl1 Q; 453
Gri dLayout.reroveLayoutComponent О:
788
LayoutManager.removeLayout
Component О:971
resizing.
Component. setBoundsO; 384
ComponentAdapter.componentRes i zed():
399
ComponentEvent.COMPONENT-RESIZED: 405
ComponentLi stener.component-
ResizedO: 410
Component Peer. setBoundsO: 419
retrieving.
Component.getComponentAt();337
Contai ner.getComponentAtО;437
scrollbars. Sc roll bar; 1321
showing,
ComponentAdapter. componentShownO; 400
ComponentEvent.COMPONENT-SHOWN;406
ComponentLi stener.componentShown О:
410
ComponentPeer.setVisiblef):420
si/e.
Component.getMaximumSizeO: 342
Component. getMi nimumSizeO; 342
Component.getPreferredSi ze();345
Component.getSize();346
Component.setSizeO; 387
ComponentPeer.getMi nimumSi ze();415
ComponentPeer.getPreferredS ize(); 415
state, Component. paramStringO: 368
INDEX
com pone n t (s) (nmtinuech
string representation.
Component . toSt ri nq(): 390
term definition. Component: 303
toolkit.
Component.getToolkit(): 346
ComponentPeer.getToolki t Q; 415
traversable focus.
testing for.
Component.isFocusTraversableQ; 351
testing for. ComponentPeer. i sFocus •
TraversableO: 416
tree lock. Component. getTreeLockQ: 346
validating, Component. va 1 i dateQ; 393
visibility.
Component.setVi si bleQ:387
ComponentAdapter.componentHi ddenQ:
399
testing for. Component. i sShowi ng(); 353
testing tor. Component. i sVi si bleQ: 353
COMPONENT-SHOWN.
ComponentEvent;406
ComponentAdapter:396
componentHiddenQ: 399
componentMovedO; 399
componentResizedQ: 399
componentShownO; 400
componentAdded О,
AWTEventMulticaster; 136
ContainerAdapter; 459
Contai nerLi stener:467
ComponentEvent: 40]
COMPONENT FIRST: 404
COMPONENT.HIDDEN: 404
COMPONENT.! AST; 405
COMPONENT MOVED;405
COMPONENT-RESIZED:405
COMPONENT-SHOWN; 406
ComponentEvent Q;406
getComponentO; 406
paramStri ngQ;407
ComponentEventО,
ComponentEvent; 406
componentHiddenО,
AWTEventMul ti caster: 137
ComponentAdapter;399
ComponentLi stener; 409
ComponentListener;408
componentHiddenQ: 409
componentMovedO: 409
componentResi zedQ: 410
componentShownO: 410
componentMovedO.
AW1EventMulticaster;138
ComponentAdapter;399
ComponentLi stener: 409
ComponentPeer;411
checklmageO; 413
createlmageQ: 413
di sableQ. тeplaced by setEnabled0: 41 3
di sposeQ: 414
enabl eQ, replaced by setEnabledQ: 414
qetColorModelQ: 414
getFontMetricsQ: 414
getGraphi csQ: 414
getLocationOnScreenQ;415
getMinimumSizeQ; 415
get PreferredSizeQ: 415
getToolki tQ; 415
handleEventQ; 416
hideQ. replaced by setVi si bl e(): 416
i sFocusTraversableQ: 416
minimumsize(). replaced by
getMi nimumSizeQ: 416
pai nt (): 4 17
preferredSizeQ. replaced by
getPreferredSizeO; 417
preparelmageQ: 417
pri nt();417
repaintO: 418
requestFocusO: 418
reshapeQ. replaced by setBoundsQ: 418
setBackgroundO; 419
setBoundsQ: 419
setCursorQ: 419
setFnabl edQ: 419
setFontQ: 420
setForegroundQ: 420
setVisibleQ; 420
showQ. replaced by setVi si bleQ: 420
componentRemovedQ.
AW1 LventMu1ticaster:138
Contai nerAdapter; 459
Contai nerLi stener;467
componentResized(),
AWTEventMulticaster:138
ComponentAdapter; 399
ComponentLi stener:410
issn
componentShown(),
AWTEventMulticaster;139
ComponentAdapter: 4CK>
Component!i stener:410
comptable,
Gri dBagLayout; 766
constrained properties,
PropertyDescri ptor.setConst rai ned():
1247
term definition. PropertyChangeEvent: 1216
testing. PropertyDescri ptor. i sCon-
strainedO: 1243
vetoing.
VetoableChange! istener; 1505
VetoableChangel istener.vetoable-
ChangeC):1508
constraints,
grid bag.
GridBagConstraints; 738
See fill; gridbag, anchor: gridbag. fill; grid bag.
insets; gridbag. internal padding; grid bag.
position; gridbag. xi/e; gridbag. weight
consumeO,
AWTEvent;122
InputFvent:876
consumed,
AWTEvent: 122
consumer,
ImageFi Iter; 827
consumers,
color model.
ImageConsumer.setColоrMode1(); 817
destroying.
ImageProducer. removeConsumerO; 843
dimensions.
ImageConsumer.setDimensionsO: 818
Fi 1teredlmageSource.addConsumerO:615
Fi 1 teredlmageSource. removeConsumerO:
615
Fil teredlmageSource.requestTopDown-
1eftRightResend О; 616
FilteredlmageSource.st artProduct ion О;
617
hints,
ImageConsumer.COMPLFT ESCANLINES; 816
ImageConsumer.RANDOMPIXELORDFR: 817
ImageConsumer,setHi ntsО; 818
ImageConsumer.SINGl EFRAME: 820
ImageConsumer.SINGLEPASS; 821
ImageConsumer.I0PD0WNLEFTRIGH1; 821
ImageConsumer; 811
ImageFiIter.consumer; 827
ImageProducer.addConsumerO;843
ImageProducer.removeConsumerO;843
MemorylmageSource.addConsumerO;1032
MemorylmageSource. removeConsumerO: 1033
pixel delivery.
ImageConsumer.COMPLETESCANLINES:816
ImageConsumer. set Pi xel sO: 819
properties.
ImageConsumer.set Propert ies():819
status |]ags.
ImageConsumer.IMAGFABORTFD: 816
ImageConsumer.IMAGEERROR; 817
ImageConsumer. SINGL FFRAMFDONE; 8?()
ImageConsumer.STAITCIMAGFDONE;821
term definition.
Image;795
ImageConsumer; 811
testing for.
Fil teredlmageSource. isConsumerO; 616
ImageProducer.i sConsumerO;843
MemorylmageSource.i sConsumerO;1032
consuming,
event*..
AWTEvent. consumeO: 122
AWT Event.consumed: 122
AWTFvent. isConsumedO; 123
term definition.
AWIEvent; 113
InputEvent; 871
input events.
InputEvent. consumeO: 876
testing for. InputEvent. i sConsumedO: 878
Container:421
add 0:431
addContainerLi st ener(); 432
addlmplO; 432
addNotifyO; 433
Contai ner();434
countcomponents О. replaced by
getComponentCount Q; 44
del i verEvent (). replaced by
Component.di spatchEventO:434
doLayoutO; 435
getAl i gnmentXO; 435
getAl ignmentYO; 436
getComponentO; 434
C INDEX
Container (<<>нпнне<Ь
getComponentAtО: 437
getComponentCountQ:437
getComponentsQ; 437
getlnsetsO; 438
getLayoutQ: 440
getMaximumSi ze(): 440
getMinimumSizeO; 440
getPreferredSizeO: 441
insetsО. replaced by getlnsetsO: 441
invalidateO; 442
i sAncestorOf();442
layout (X replaced bv do! ayout(); 443
list():444
1 ocateQ. replaced bv getComponentAtО; 446
minimumSizeO, replaced by
getMinimumSizeO: 446
pai nt0:447
pai ntComponentsO: 450
paramStri ng О;450
preferredSi zeO. replaced bv
getPreferredSizeO: 451
pri nt();451
printComponentsO: 451
processContainerFventQ:452
processEventO; 452
removeО;453
removeAl1Q; 453
removeContai nerLi stenerO: 454
removeNot i fу О;454
setLayoutO; 454
validateO; 456
validateTreeO: 457
ContainerQ,
Contai ner; 434
CONTAI NER_EVENT_M ASK,
AWTEvent: 122
container events,
adapter class. Contai nerAdapter; 458
callback methods.
Conta i nerAdapter.componentAddedQ:459
Contai nerAdapter.componentRemoved():
459
Contai nerLi stener.componentAdded О:
467
Contai nerLi stener.Component-
Removed (): 467
class. Contai nerEvent: 460
components (hat fire. Table. AWTEvent: 115
Container: 122
dispatching.
AWTEventMu1ti caster.component
AddedO: 136
AWTEventMulticaster.component-
Moved О: 1 38
AWTEventMulti caster.component-
RemovedО; 138
event id.
ContainerEvent.C0MP0NEN1-ADDFD; 46^
Contai nerEvent.COMPONENT.REMOVED; 463
ContainerEvent.CONTAINER„FIRST: 464
Contai nerEvent.CONTAINER_LAST: 464
flow. Figure. ContainerEvent: 461
listeners.
Container.addContai nerLi stenerQ; 432
mask lor. AW1 Event. CONTAINER-EVENT, MASK:
122
processing.
Contai ner.processContainerEventQ: 452
Container.processEventQ: 452
state. Contai nerEvent.paramString(): 465
tvpes. I able. AWTEvent: 115
Wi ndow;1519
CONTAINER-FIRST,
Contai nerEvent; 464
CONTAIN ER_LAST,
Conta i nerEvent;464
contained si.
See Л1.\а item events
adding components to.
Contai ner. addQ; 431
Container.addlmpl(); 432
LayoutManager2.addLayoutComponentQ;
979
adding scroll pane components.
Scroll Pane.addlmplО;1349
alignment point, term definition. LayoutManager?:
973
ancestor, testing. Contai ner. i sAncestorOf ():
442
child. ContainerEvent.getChi IdQ: 465
class. Contai ner: 421
component lav out relationship to. Component: 306
components in.
Container.getComponentcount(); 437
Container.getComponents(): 4U
disabled, term definition. Container; 422
focus traversable. Contai ner: 423
15X2
fonts. MenuContainer.getFontO; 1086
gridbag,
calculating layout.
Gri dBagLayout .GetLayoutlnfoO: 768
GridBagLayout.layoutContainer(); 773
term definition, GridBagLayout: 759
in sei. term def inition. Container; 422
insets.
Contai ner. getlnsetsO: 418
ContainerPeer.getlnsetsO: 469
I ayoutManager; 964
invalidating. Contai ner. i nvali dateO: 442
layout.
Container .getLayoutO; 440
Contai ner. getLayoutAl ignrrentXO: 435
Container. getLayoutAl ignmentYO; 436
Container. setLayoutO; 454
FlowLayout.layoutContainerO; 624
Gri dBagLayout.ArrangeGr id(); 764
LayoutManager; 964
LayoutManager?.getLayoutAlign-
mentXO: 979
LayoutManager?.getLayoutAli gn-
mentY();980
management: 421
LayoutManager.addLayoutComponent О;969
lightweight. native containers compared with.
Container; 424
listener. Con tai nerLi stener: 466
listeners. Contai ner. removeContainer-
Li stenerO; 454
menu,
.Ser Also Frame: Menu; MenuBar
MenuContainer: 1(182
native, light weight containers compared with.
Container; 424
painting. Container.paintO; 447
painting components, on graphics context,
Container.paintComponentsO: 450
panels. Panel: 1162
peers.
ContainerPeer:468
cieating. Container. addNoti fyO; 413
destroying, Contai ner. removeNoti fy О; 454
priming.
component hierarchy. Contai ner. 1 i st (); 444
components on a graphics context.
Container.printO; 451
components on a graphics context.
Contai ner.printcomponents():451
removing components from,
Contai ner.removeО;453
Container.removeAl1();453
removing menu components from.
MenuContainer. removeO: 1087
retrieving.
Containertvent.getContai ner0:465
size.
Contai ner.getMaximumSize0:440
Container.getMinimumSizeO; 440
Container.getPreferredSizeO; 441
state. Contai ner,paramStri ng(); 450
term definition. Contai ner: 421
valid state, term definition. Container; 421
validating.
Contai ner.validateQ; 456
Container.validateTreeO; 457
validating components,
ContainerPeer. beginVali dateO; 469
ContainerPeer.endVal idateO; 469
validity. 1 ayoutvanager: 964
ContainerAdapter:458
componentAddedO: 459
componentRemovedO; 459
ContainerEvent,
COMPONENT_ADDED; 463
COMPONENT-REMOVED; 463
CONTAINER-FIRST: 464
CONTAINER. LAST; 464
Contai nerEvent():464
getChildO: 465
getContai ner();465
paramStringO; 465
ContainerEventО,
ContainerEvent: 464
ContainerListener;466
componentAddedO: 467
componentRemovedO: 467
ContainerPeer;468
begi nVal idateO; 469
endVa 1 idateO: 469
getlnsetsO: 469
i nsets O, replaced by get Insets О; 470
containsQ,
Component:326
Polygon; 1188
Rectangle;1292
INDEX
contents,
С1 ipboard; 271
context,
applet. See applet(s). context
graphics. See graphics context! s)
control,
SystemColor; 1392
Control key,
InputEvent.CTRL.MASK: 876
testing. InputEvent . i sCont rol Downf): 879
controlDkShadow,
SystemColor: 1394
control DownО*
Event, replaced by
InputEvent.i sControlDownO: 552
controlHighlight,
SystemColor;1394
controlLtHighl ight,
SystemColor; 1394
control Shadow,
SystemColor; 1394
control Text,
SystemColor:1395
conventions,
accessor method signature.
IndexedPropertyDescri ptor: 856
PropertyDesr r i ptor: 1231
listener support method signature.
FventSetDescriptor: 578
coordinates,
frames. Frame; 667
graphics context. Graph i cs; 686
mouse. MouseEvent: 1132
mouse events.
MouseEvent.t ranslatePoint(); 1142
point. string representation.
Point. toStringO; И82
print graphics context, Pri ntGraphics; 1201
windows, wi ndow: 1519
x. cell location for component.
GridBagConstraints.gridx;748
y. cell location for component.
Gri dBagConstrai nts,gri dy:749
copyAreaC).
Graphi cs; 691
copying.
areas on draw ing surface.
Graphics.copyAreaO; 691
graphics context. Graphi cs. create 0: 693
gridbag. GridBagConst raints.cloneO: 74
image filters. ImageFi Iter. cloneO: 82 7
insets. Insets.clone():884
pointhк Point.getLocationO; 1181)
countComponentsO.
Container, replaced by
getComponentCount();434
countltemsO,
Choice, replaced by getltemCountO: 257
I ist. replaced by getltemCountO: 991
Menu, replaced by getltemCountO: 1046
countMenusO,
MenuBar, replaced by getMenuCount (): 1058
createQ,
Graphics: 693
createButtonO,
Toolkit: 1479
createCanvas(),
Ioolkit;1479
createCheckboxC),
1oolkit:1480
createCheckboxMenuItemQ.
Toolkit; 1480
createChoiceQ,
Toolkit; 1480
createComponentО,
Toolkit: 1481
c reateDi alog О,
Toolkit; 1481
createFileDialogO*
Toolkit: 1482
createFramef),
Toolkit: 1482
createlmageO,
Component:329
ComponentPeer;413
Toolkit; 1482
createLabelC),
Toolkit: 1483
createListO*
Toolkit: 1483
createMenuO,
Toolkit: 1484
createMenuBarQ,
Ioolkit;1484
createMenuItemО,
Toolkit; 1485
createPanel(),
1oolkit; 1485
1584
createPopupMenuQ,
Toolkit:1485
createScrollbar(),
Toolkit; I486
createScrollPanet),
Toolkit: 1486
createTextAreaO,
Toolkit: I486
c reateT ex t Fi el d (),
Toolkit: 1487
createWindow(),
Toolkit: 1487
creating,
instances. See each individual class
peers. See add Not i fyO
CropImageFilter;471
CropImageFilterO; 475
setDimensionsO; 475
setPixels(): 475
setPropertiesO; 476
CropImageFilter(),
Crop Image Г i 1 ter: 475
cropping,
images. CropImageFil ter: 471
crosshair cursor,
Cursor.CROSSHAIR-CURSOR: 480
CROSSHAIR-CURSOR,
Frame, replaced by
Cursor.CROSSHAIR CURSOR; 670
Cursor; 480
CTRL_MASK,
Fvent, replaced by InputEvent.CTRL MASK; 553
Act ionCvent:36
Inputtvent; 876
Cursor; 477
CROSSHAIR.CURSOR; 480
CursorO:480
DEFAULT-CURSOR; 480
E-RESIZE CURSOR;481
getDefaul tCursorO; 481
getPredefi nedCursorO: 481
getTypeO; 482
HAND.CURSOR; 483
MOVE-CURSOR: 483
N_RESIZE_CURSOR: 483
NE_RESIZE_CURSOR; 484
NW_REST7E_CURS0R; 484
S .RESIZE CURSOR: 484
SE_RESIZE_CURSOR:484
SW_RFSI7F_CURS0R: 485
TEXT CURSOR:485
W_RFSIZE-CURSOR;485
WAIT_CURSOR: 485
CursorQ.
Cursor: 480
cursors,
class. Cursor; 477
crosshair. Cursor.CROSSHAIR .CURSOR: 480
default.
Cursor.DFTAU1T.CURSOR;480
Cursor.getDefaul tCursorO; 481
Frame:667
hand, Cu rsor.HAND-CURSOR: 483
moving. Cursor .MOVE_CURSOR; 483
predefined.
Cursor.getPredefi nedCursorO: 481
property. Frame: 667
resizing.
Cursor.E RESIZE.CURSOR;481
Cursor.N RESIZE.CURSOR;483
Cursor,NF_RFSIZF—CURSOR; 484
Cursor.NW-RFSIZE—CURSOR; 484
Cursor.S_REST7F_CURS0R: 484
Cursor.SE-RESIZE-CURSOR; 484
Cursor .SW_RESIZE,_CURSOR; 485
Cursor.W-RESIZE-CURSOR; 485
retrieving. Component .getCursorO: 338
setting.
Component. setCursorO; 384
ComponentPeer.setCursorO; 419
term definition. Cursor: 477
text. Cursor .TEXT_CURSOR; 485
types. Cursor.getTypeO: 482
wait. Cursor. WATT_CURSOR: 485
customizer,
class,
as bean descriptor attribute. Table: 155
Customi zer;486
term definition. Customi zer; 486
Customizer; 486
addPropertyChangeLi stenerO:498
removePropertyChangeLi stenerO;498
setObjectO; 499
cyan,
Col or. cyan; 285
cyan,
Color: 285
D
INDEX
D
darkerf),
Color: 285
darkGray,
Col or: 285
data,
retrieving.
Transferable.getT ransferDataQ;1501
data flavor.
class. DataFlavor; 500
equality, testing for. Dat aFlavor.equals(): >04
exception. UnsupportedFlavorException: 1503
plain text, DataF lavor. plai nText Г1 avor: 507
retrieving,
StringSelection.getTransferData-
FlavorsQ: 1377
T ransfenable.getT ransferData-
FlavorsO; 1502
sinne. DataFlavor. stri ngFl avor: 508
string selections. StringSelecti on: 1374
supported. Transferable: 1496
term definition, DataFl avor; 500
testing.
Stri ngSelection.i sDataFlavor-
SupportedO: 1378
Transferable.i sDataFlavor-
SupportedO: 1502
DataFlavor;500
DataFlavor();503
equalsО - 504
getHumanPresentabl eName. (): 504
getMimeType(); 505
getRepresentationClassO: 505
i sMimeTypeEqual();505
normalizeMimeTypeО: 506
normali zeMimeTypeParameterQ;506
pl a inText Fl avor; 50/
setHumanPresentableNameO: 507
strinqFlavor; 508
DataFlavorО,
DataFl avor: 503
debugging.
See paramStri ng<)
decapitalizeО*
Introspector;899
decapitalizing strings.
Int rospector.decapi talize();899
decodeO,
Color: 285
Font:643
decrement.
block. Bl OCK DECREMENT; 67
unit. AdjustmentEvent.UMT_DLC.RLMLNT. 69
default color model.
term definition. ColorModel; 296
DEFAULT-CURSOR.
Frame, replaced by
Cursor.DEFAULT-CURSOR: 670
Cursor; 480
defaultConstraints,
CridBagLayout:766
deleteShortcutf).
VenuBar; 1058
Menuitem: 1092
delltemf),
I ist:992
MenuPeer: 1110
delltemsO'
Li st. replaced bx using multiple invocations of
remove();992
ListPeer:1012
del i verEventO.
Component, replaced by dispatchEvent(): ^31
Container, replaced by
Component .di spatchEventO: 434
delivery.
pixel.
AreaAveragingScaleFiIter.set -
PixelsO: 104
CropImageFi1 ter.setPi xels():475
ImageConsumer.COMPL FTESCANLINES: 816
ImageConsumer.RANDOMPIXLLORDF R; 817
ImageConsumer.SINGLEPASS; 821
ImageFi1 -
ter.resendlopDownLeftRight0: 828
ImageFi1 ter.setPixels(): 830
ImageObserver.SOMEBITS; 837
ImageProducer.requestTopDown-
LeftRightResendO: 844
ImageProducer, startProductionO; 844
MemorylmageSource.newPi xels0: 1031
MemorylmageSource.requestTopDown-
t ef tRi ght ResendQ: KB5
MemorylmageSource.setFul1 Buffer
UpdatesQ: 1038
MemoryImageSource.startProducti on О;
1038
PixelGrabber.setPixels():1176
1586
Repl icateScaleF i 1 ter.setPixel sO: 1306
RCBImageF i Iter.setPixelsO: В19
del Menu О*
MenuBarPeer;1068
deprecated.
acti on О replaced by ActionListener: 317
CheckboxGroup. get Cur rent () replaced by
getSel ectedCheckboxO; 236
CheckboxGroup. set Cur rent О replaced hy
setSelectedCheckboxQ; 237
Choice, countitems О replaced by
getltemCountO: 256
ChoicePeer. add!temО replaced by
addO; 266
Corrponent. boundsC) replaced by
getBoundsO; 323
Component.de! i vertvent О replaced by
diSpatchEventO; 331
Component. d i sabl e О replaced by
setFnabledO; 332
Component.enableO replaced by
set Enabled0:335
Component .hand! eEvent О replaced b\
processEventO; 348
Component. hide() replaced by
setVi si bleO: 349
Component, ins ide О replaced by
containsО; 350
Component. layout О replaced hy
doLayout():355
Component. locateQ replaced by
getComponentAt();356
Component. loc at ion О replaced hy
getLocationO; 357
Component.minimumSizeО replaced by
getMi nimumSi zeO; 358
Component .moveO replaced by
setLocation(): 363
Component.nextFocusО replaced by
transferFocusO; 363
Component. post Event О replaced hy
di spatchEventO: 369
Component. preferredSizeО replaced by
getPreferredSizeO: 369
Component. reshape Q replaced hy
setBoundsO; 382
Component. resizeO replaced by
setSizeO: 382
Component .showO replaced by
setVisi bleO; 389
Component. si zeO replaced by
getSizeO: 390
ComponentPeer. di sable О replaced by
setEnabledO: 413
ComponentPeer.enable() replaced by
setEnabled(): 414
ComponentPeer. hi de О replaced by
setVi si Ы eO; 416
ComponentPeer.minimumSi ze() replaced by
getvi nimumSizeO: 416
ComponentPeer. prefer redSizeO replaced hy
getPreferredSi ze();417
ComponentPeer. reshapeO replaced by
setBounds();418
ComponentPeer. showO replaced by
setVisibleO: 420
Container. countcomponents О replaced by
qetComponentCount(): 434
Container.deliverEventO replaced by
Component .di spatchFventO: 434
Container.insets() replaced by
getlnsetsO; 441
Contai ner. layout О replaced by
doLayoutО;443
Container. 1 ocateО replaced by
qetComponentAtO: 446
Container.minimumSizeO replaced by
getMinimumSizeO; 446
Contai ner.preferredSi ze() replaced by
getPreferredSizeO: 451
ContainerPeer. insetsO replaced by
getlnsetsO: 470
Event .ACTION EVENT replaced by
ActionEvent. ACTION..PERFORMED: 551
Event .ALT_MASK replaced hy
InputEvent. ALT..MASK; 551
Event .arg replaced by event specific fields and
methods; 551
Event .clickCount replaced by
MouseEvent.getClickCount0: 552
Event. control Down О replaced by
InputEvent. i sControlDownO; 552
Event.CTRL_MASK replaced by
InputEvent.CTRL_MASK: 553
Fvent.DOWN replaced by KeyEvent.VK JXIWN; 55
Event. END replaced by KeyEvent. VK_END; 553
Event .evt replaced by EventQueue; 554
D
INDEX
deprecated 'cominurfb
Event. Fl replaced by KeyEvent . VK_F1; 555
Event. F10 replaced by KeyEvent. VK.F10; 555
Fvent. Fil replaced by KeyEvent.VK Г11: 555
Event. Г12 replaced by KeyEvent.VK.F12; 555
Event . F2 replaced by KeyEvent . VK.F2; 556
Event. F3 replaced by KeyEvent .VK_F3; 556
Event. Г4 replaced by KeyEvent,VK_F4; 556
Event. Г5 replaced by KeyEvent. VK.F5: 556
Event. F6 replaced by KeyEvent. VK. F6; 557
1 vent.F7 replaced by KeyLvent.VK.F7; 557
Event. F8 replaced by KeyFvent.VK_F8: 557
Event. F9 replaced by KeyEvent,VK_F9: 558
Event - GOT FOCUS replaced by
FocusEvent.FOCUS_GAINED: 558
Fvent.HOME replaced by KeyEvent.VK.HOME: 558
Event. Id replaced by AWTEvent.get ID(); 559
Event.KEY_ACTION_RELEASE replaced by
KeyEvent.KEY.RF LEASED; 560
Event.KEY-ACTION replaced by
KeyLvent.KEY-PRESSED: 559
Fvent. KEY-PRESS replaced by
KeyEvent.KEY-PRESSED; 560
Event. KFY_RELEASE replaced by
KeyFvent.KEY. RELEASED: 561
Fvent.key replaced by
KeyEvent.get KeyCode0:559
Event. LFFT replaced by KeyEvent . VK.LEFT; 561
Event .LIST .DESELECT replaced by
ItemEvent,DESEL FCT: 561
Event.LIST.SELECT replaced by
ItemEvent.DESELECT; 562
Event. LOST_FOCUS replaced by
FocusEvent.FOCUS_1 OST: 562
Event . ME7A..MASK replaced by
InputEvent.META_MASK; 562
Event. metaDown() replaced by
InputFvent. i sMetaDownQ; 562
Event.modi f i ers replaced by
InputEvent.getModifiers(): 563
Event. MOUSE DOWN replaced by
MouseEvent. MOUSE.PRESSF D; 563
Event.MOUSE DRAG replaced by
MouseEvent.MOUSE-DRAGGED: 564
Event. MOUSE .ENTER replaced by
MouseEvent.MOUSE-ENTERED: 564
E vent .MOUSE_EXIT replaced by
MouseEvent.MOUSE-EXITED: 564
Fvent.MOUSE-MOVE replaced by
MouseEvent.MOUSE-MOVED; 564
Event. MOUSE_UP replaced by
MouseEvent.MOUSE-RELEASED; 565
Event.paramString() replaced by
AWTEvent.paramString(); 565
Fvent. PGDN replaced by
KEYEvent.VK_PAGE_DOWN:565
Event. PGUP replaced by
KeyFvent .VK-PAGE-UP: 565
1 vent .RIGHT replaced by
KeyEvent.VK-RIGHT: 566
Event. SCROLL-ABSOLUTE replaced by
Adj ustmentEvent.TRACK;566
Event. SCROLL_LINE-DOWN replaced by
AdjustmentEvent.UNI!_ INCREMENT: 567
Event. SCROLL_1 INE. UP replaced by
Adj ustmentEvent.UNIT-DECREMENT: 567
Event. SC ROLL. PAGE-DOWN replaced by
Adjustment Event.BLOCK DECREMENT: 567
Event. SCROL L .PAGE UP replaced by
AdjustmentEvent.BLOCK-DECREMENT: 567
Fvent. SHIFT-MASK replaced by
InputEvent.SHIFT-MASK;567
Event. shiftDownC) replaced by-
input Event .i sShiftDown(): 568
Event.target replaced by
AWTEvent .getSourceO; 568
Event. toStri ng() replaced by
AWTEvent .toStringO: 568
Event. t rans 1 ate() replaced by
MouseEvent.trans 1atePoi nt():568
Fvent.UP replaced by KeyFvent.VK UP; 569
Event.when replaced by
InputEvent.getWhenO; 569
Event .WINDOW DEICONIFY replaced by
WindowEvent.WIND0W_DFIC0NIFIED;570
Event .WINDOW. DESTROY replaced by
Wi ndowEvent.WINDOW-CLOSING; 570
Event .WINDOW_EXPOSE replaced by
Wi ndowEvent.WINDOW-ACTIVATED;570
Event.WINDOW.ICONIFY replaced by
WindowEvent.WINDOW_ICONIFIED: 571
Fvent.WINDOW-MOVED replaced by
Component!vent.COMPONENT.MOVED; 57]
Event.x replaced by MouseEvent.getX0: 571
Event. у replaced by MouseEvent. getY(); 572
FontMetri cs. getMaxDecentО replaced by
getMaxDescent();664
1588
F name . CROSSH AIR..CURSOR replaced by
Cursor.CROSSHAIR,CURSOR:670
Frame.DEFAUl Tw CURSOR replaced by
Cursor.DEFAULT-CURSOR: 670
Frame. E RESIZE-CURSOR replaced by
Cursor.E-RESIZE-CURSOR:672
Frame.getCursorlypeQ replaced by
Component.getCursorQ .getTypeQ: 673
Frame. HAND .CURSOR replaced by
Cursor.HAND CURSOR:674
Frame .MOVE .CURSOR replaced by
Cursor.MOVE-CURSOR;674
Frame.N-RESTZE. CURSOR replaced by
Cursor. N _RES1ZE_CURSOR; 674
Frame. NF__RESTZE_ CURSOR replaced by
Cursor.NE_RESIZE_CURSOR;675
Frame. NW_RESIZE CURSOR replaced by
Cursor.NW_RESIZE_CURSOR: 675
Frame. S-RESTZE. CURSOR replaced by
Cursor.S .RESIZF-CURSOR:677
Frame. SF_RESTZE,CURSOR replaced by
Cursor.SF-RESIZE-CURSOR;677
Frame, setCursorQ replaced by
Component.setCursorQ:677
Frame. SW^RFSIZE.CURSOR replaced by
Cursor.SW-RESTZE CURSOR; 677
Frame.TEXT-CURSOR replaced by
Cursor.TEXT-CURSOR: 682
Frame. W. RFSIZF-CURSOR replaced by
Cursor.W_RFSIZE^CURSOR: 682
Fra me. WAIT CURSOR replaced by
Cursor.WAIT CURSOR;68?
Graphi cs.ge t С1ipRect О replaced by
getClipBoundsQ: 725
List. al lowsMu it ipleSelect 1 ons() replaced
by i sMulti pl eModeQ:991
List .clearO replaced by removeAI10;991
List .count I terns О replaced by
getItemCoиntQ; 991
Li st. del Items О replaced by using multiple
invocations of remove 0: 992
L i s t. i sSe 1 ec ted О replaced by
islndexSelectedQ; 999
Li st .minimumSizeQ replaced by
getMinimumSizeО; IIM)i
Li st .preferredSi ze() replaced by
getPreferredSi zeQ. 1002
Li st. setMul ti pl eSei ect i ons О replaced by
setMul tipi eMode Q; 1(X)9
I i stPeer. addi tem() replaced by add О: 1011
Li st Peer. cl ear О replaced by
removeAl IQ; 1012
Li stPeer.mi nimumSizeQ replaced by
getMi nimumSizeO; 1014
ListPeer.preferredSizeQ replaced by
getPreferredSizeO: 1014
ListPeer.setMultipleSelections() replaced
by setMul ti pleModeQ: 1015
Menu . countltemsQ replaced by
getltemCountO: 1046
MenuBar. count Menus О replaced by
getMenuCountQ; 1058
MenuComponent. post Event О replaced by
di spatchEventO; 1077
MenuContai ner. post Event () replaced by
MenuComponent. di spatchEventO; 1086
Menuitem, di sable О replaced by
setEnabled О;1093
Menu I tem. enable О replaced by
setEnabl edQ; 1095
MenuItemPeer .di sable О replaced by
setEnabledQ: 11U8
MenuItemPeer. enable О replaced by
setEnabledQ; 1108
Pi xelCrabber. statusO replaced by
getStatusO; 1177
Point.move() replaced by
setLocati onQ; 1181
Pol ygon .getBoundi ngBoxQ replaced by
getBoundsQ; 1188
Polygon. ins ide О replaced by
containsQ: 1189
Rectangle.insideO replaced by
containsQ; 1296
Rectangle.moveQ replaced by
setLocationQ; 1297
Rectangl e. reshape О replaced by
setBoundsО:1298
Rectangle. resi zeQ replaced by
set Si zeQ; 1299
Scrol Ibar .getLi nelncrement () replaced by
getUni tlncrementQ: 1327
ScrolIbar.getPagelncrementO replaced by
getBlocklncrementO: 1329
Scrollbar.getvisibleQ replaced by
getVisibleAmountQ: ВЧ0
Scrollbar. setLinelncrementО replaced by
setUnitlncrementQ:1334
D
INDEX
deprecated (continued)
Scrol Ibar. setPagelnc rementО replaced by
setBlocklncrementO: 1338
Scroll Pane.layoutО replaced by
doLayout О; 1 155
TextArea.appendTextО replaced by
appendQ; 1409
1 ext Area. i nsertTextО replaced by
insert():1415
TextArea.minimumSizeO replaced by
getMinimumSizeO; 1415
TextArea. pref er redSizeO replaced by
getPreferredSizeO; 1416
TextArea. rep lac eText О replaced by
replaceRangeO; 1418
TextAreaPeer.insertText () replaced by
insertO: 1425
TextAreaPeer .minimumSizeO replaced by
getMinimumSizeO; 1425
TextAreaPeer.preferredSi zeO replaced by
getPreferredSizeO; 1425
TextAreaPeer. replaceTextO replaced by
replaceRangeO; 1426
TextHeld.minimumSizeО replaced by
getMinimumSizeO; 1462
TextFie Id.preferredSize() replaced by
getPreferredSizeO: 1462
TextField. setEchoCharacterO replaced by
setEchoCharO; 1467
TextFieldPeer .mi nimumSi zeO replaced by
getMinimumSizeO; 1469
TextFieldPeer. setFchoCharacterO replaced
by setEchoCharO: 1470
Wi ndow. post Event О replaced by
Component.di spatchEventO; 1528
descent,
font.
FontMetrics.getDescentО;661
FontMetri cs. getMaxDescentO: 664
fonts, term definition, FontMetrics; 653
descriptors,
beans.
BeanDescriptor; 154
introspector use. Beaninfo: 161
term definition. BeanDescri ptor; 154
event set.
attributes. Table, EventSetDescri ptor; 577
explicit, term definition.
FventSetDescri ptor; 577
implicit, term definition.
EventSetDescriptor:577
term definition. Even t Set Des cr i ptor: 576
feature.
FeatureDescr iptor; 591
FeatureDescri ptor.attributeNames();
595
FeatureDesc r i ptor.setNameO:599
introspector construction of.
Introspector;890
SimpleBeanlnfo;1365
term definition. FeatureDescri pt or; 591
indexed properly.
attributes. Table.
IndexedPropertyDescri ptor;855
IndexedPropertyDescriptor: 854
method.
FventSetDescri ptor.getLi stener-
MethodDescriptorsQ: 587
MethodDescri ptor; 1116
MethodDescri ptor. getMethodO: 1119
MethodDescri ptor.getParameter
Descriptors(): 1119
parameter, term definition.
ParameterDescri ptor; 1166
parameter. MethodDescriptor.getParameter
Descriptors(): 1119
properly, PropertyDescriptor; 1229
desel ectO.
Li st:993
ListPeer: 1012
DESELECTED,
ItemEvent:905
design-time,
flag.
Beans .setDesignTimeO: 174
testing. Beans. isDesignTimeO; 173
term definition. Beans: 168
desktop,
label text. SystemColor.desktop: 1395
desktop,
SystemColor; 1395
destHeight,
ReplicateScaleFiIter;1305
destroyO>
Applet: 83
destroying,
applets. Applet .destroy0: 83
components, ComponentPeer .disposeО; 414
1590
consumers,
ImageProducer.removeConsumerO; 843
frames. Frame. di sposeO: 671
graphics contexts.
Graphics - di sposeO; 695
Graphi cs.finalizeO;724
images Image,flushO;80l
windows, wi ndow. di sposeO; 1524
destWidth,
ReplicateScaleFilter;1305
dialog,
class. Dialog; 509
exent types tired by. Table, AWTEvent; 115
file.
Fi 1 eDialog; 601
FileDialog.paramStringO; 607
peers, creating, Fi 1 eDi al og. addNoti fy О;
605
load file,
FileDiaiog.LOAD; 607
term definition, Fi 1 eDialog; 601
modal, term definition. Dialog; 509
modal property. Dialog. setModal О; 516
model property, testing for. Di alog.i sModal О;
514
peers,
creating. Dialog. addNotify();512
Di a logPeer; 519
Toolkit .createDialogO; 1481
resizable property.
Dialog.setResizable ();516
DialogPeer. setResizableO; 520
testing tor. Dialog. isResizableC); 515
testing tor. F rame.i sResi zabl e(); 674
save file,
F i1eDi alog.SAVE;608
term definition. Fi 1 eDi al og; 601
showing.
Dialog.showO; 518
PopupMenu. showO; 1196
PopupMenuPeer. showO; 1200
Window. showO; 1530
state. Dialog.paramSt ringO; 515
term definition. Dialog; 509
title property.
Di alog.getTi tie О;514
Dialog.setTitle();517
DialogPeer.setTi tie О; 520
Dialog; 509
addNoti fy(): 51 2
DialogO; 51 2
getTi tle();514
i sModal O; 514
isResizableO: 515
pararStri ng(): 515
setModal 0:516
setResizableO; 516
setTitle(): 517
showO; 518
Dial og(),
Dialog; 512
DialogPeer;519
setResizableO; 520
setTit leO; 520
digest,
term definition. Applet; 76
Dimension; 521
Dimension();522
equals C):523
getSi ze():523
hei ght;525
setSizeO; 525
toStringO; 525
width; 526
DimensionO,
Dimension;522
dimensions,
class. Dimensi on; 521
equality, testing. Di men si on. equal s(); 523
gridbag. Gri dBagLayout. getLayout-
DimensionsO; 767
height. Di men si on. hei ght; 525image.
CropImageFi 1 ter.setDimensionsO; 475
ImageConsumer.setDi tensions О;818
ImageFi Iter. set Di mens ionsO: 829
Pi xelGrabber. setDimensionsO; 1175
Repl i cateScal eFi 1 ter. set Di mens i onsO;
1306
maximum, for component layout.
Gri dBagLayout.maximumLayoutSi ze();776
minimum. GridBagLayout.GetMi nSi zeO; 772
page. Printlob.getPageDimensionC); 1214
print graphics context, Pri ntGraphi cs; 1201
si/e.
Dimension.getSize():521
Dimension. setSi zeO; 525
D INDEX
dimensions (eoniuiuctb
string representation.
Dimension.toStringO: 525
term definition. Dimension: 521
viewport Scrol 1 Pane.getViewportSizeO:
1353
direct color model.
Di rectColorModel:527
term definition. ColorModel: 296
Di rectCol orModel; 527
Di rectColorModel():530
getAlpha():531
getAlphaMaskQ:531
getBlueQ: 531
getBlueMaskQ: 532
getGreenQ: 532
getGreenMaskQ; 532
getRedQ: 533
getRedMaskQ: 533
getRGBQ: 533
DirectColorModel
Di rectColorModel:530
directory property,
file dialog.
Fi 1 eDialog.qetDi rectoryQ: 606
Fi 1 eDialog.setDi rectoryQ: 608
Fi 1 eDialogPeer. setDi rectoryQ: 612
file dialogs, term definition. FileDialog: 601
disabled.
Component, replaced by setEnabledQ; 332
ComponentPeer. replaced by settnabl edQ: 413
Menuitem, replaced by setEnabledQ: 1093
MenuItemPeer. replaced by setfnabl edQ: 1108
disabled property,
menu items, term definition. Menu I tem: 1088
di sableEventsQ,
Component;332
Menuitem:1093
disabling.
components.
Component. setEnabledQ: 384
ComponentPeer.setEnabled():419
containers, term definition. Container: 422
events.
Component. di sableEventsQ; 332
Menuitem.disableFventsQ; 1093
menu items,
Menuitem. setEnabledQ: 1102
MenuItemPeer.setEnabledQ: 1108
dispatch(),
Act ivelvent:45
di spatchEventO,
Component: 332
MenuComponent: 1072
dispatching,
action events. AWTEventMulticaster.action-
PerformedQ; 133
adjustment events. AWTEventMul t i
caster.adjustmentValueChangedO: 135
component events.
AWTEventMul t Raster.component-
HiddenQ: 137
AWTEventMulti caster.component-
MovedQ: 138
AWTEventMu11 i caster.component
RemovedQ; 118
AWI EventMulti caster,component-
ResizedQ: 138
AWTFventMulticast er,component
ShownO: 139
container events, AWTEventMulti caster. compo
nentAddedQ: 136
event.
AWTEventMulticaster; 128
thread, term definition. EventQueue: 573
eveins,
ActiveEvent: 45
ActiveEvent .dispatchQ: 45
AWTEvent; 112
Component.di spatchEvent();33?
MenuComponent.di spatchEventO: 1072
focus events.
AWTEventMu 1t Raster. focusGai nedQ. 139
AWTEventMulticaster. focusl ostQ: 140
item events. AWTEventMul ti -
caster. itemStateChangedQ: 140
key events.
AWTEventMulticaster,keyPressed():141
AWTEventMulti caster.keyReleasedQ. 141
AWTEventMultleaster.keyTypedQ: 142
mouse events.
AWTEventMul t Raster, moused i eked ():
142
AWTEventMul t Raster .mouseDraggedQ:
143
AWTEventMul ti caster .mouseEnteredQ;
143
AWTEventMulticaster.mouseEx i tedQ. 144
1592
AWTEventMulticaster.mouseMovedО;144
AWTEventMulti caste г. mousePressedQ;
144
AWTEventMulticaster.mouseReleasedQ;
145
text events. AWTEventMul ticaster .text-
ValueChangedQ: 148
window events.
AWTEventMulticaster.wi ndow-
ActivatedQ: 149
AWTEventMulti caster.wi ndowClosedQ;
149
AWTEventMulti caster.wi ndowClosingQ;
150
AWTEventMulticaster.window-
Deacti vatedQ: 150
AWTEventMulticaster.window-
Dei coni fiedQ; 151
AWTEventMulticaster.window-
IconifiedQ: 151
AWTEventMulti caster .wi ndowOpenedQ:
151
display area,
component, term definition. Gri dBagLayout; 759
disposeQ.
ComponentPeer:414
F rame: 671
Graphics:695
MenuComponentPeer;1081
Window: 1524
document base L'RL,
for an applet.
Applet.getDocumentBaseQ: 85
AppletStub.getDocumentBaseQ; 99
documents,
HTML. AppletContext. showDocumentQ; 96
URL. applet use. Applet; 75
doLayoutO,
Component;315
Container; 435
ScrollPane;1350
dontUseGui O,
Visibility: 1517
double-buffering,
term definition. Component; 308
DOWN.
Event, replaced by KeyEvent. VK_D0WN; 553
dr aw 30 RectQ,
Graphics; 695
drawArcO,
Graphics;697
drawBytesQ,
Graphics; 699
drawCharsО,
Graphics; 699
drawlmageО,
Graphics:700
drawing,
See painting
drawing surface,
copying areas on, Graphics.copyAreaQ; 691
term definition. Graphics; 685
drawLi neQ,
Graphics; 702
drawOval O>
Graphics;704
drawPolygonО,
Graphics;705
drawPolyline()<
Graphics; 707
drawRectO,
Graphics, Graph!cs .drawRect(); 708
drawRoundRect(),
Graphi cs; 710
drawstringО<
Graphics; 712
DS A encryption,
JAR support for. Appl et; 76
E
E_RESIZE—CURSOR,
Frame, replaced by Cursor.E_RESIZE_CURSOR;
672
Cursor: 481
east,
resizing cursor. Cursor. E_RESIZE_CURSOR; 48!
EAST,
BorderLayout; 181
Gri dBagConstrai nts; 744
echo,
character,
retrieving, TextField.getEchoChar(); 1461
setting, TextField. setColumnsQ; 1465
setting, TextFieldPeer.setEchoCharQ;
1470
testing, TextField.echoCharlsSetO; 1459
property, TextFi eld; 1456
Е
INDEX
echoCharlsSetO,
TextField:1459
editing beans.
bean desetiptor use. BeanDescriptor: 154
Customi zer: 486
environment interaction. Beans: 108
PropertyEditor: 1248
Property^ di tor.. getCustomEdi tor (): 1256
PropertyFditorManager:1262
PropertyEditorSupport:1267
getCustomEditorQ: 1275
element type,
indexed propertv term definition.
IndexedPropertyDescriptor:854
elliptical arc.
painting. Graphi cs .drawArc 0: 697
enable().
Component, replaced by setEnabled0: 335
ComponentPeer. replaced bv setFnabledO: 414
Menuitem, replaced by setEnabledQ: 1095
MenultemPeer. replaced by setFnabledO: I 108
enabled,
component, testing. Component. i stnabl ed():
350
menu item, testing. Menuitem, i sEnabledO:
1097
menu items, term definition. Menu I tem: 1088
properly, term definition. Component: 305
enabl eEventsO,
Component:335
MenuItem:1095
enabling,
components.
Component.setEnabled();384
Component Peer.setEnabledО: 419
event types.
Component. enableEventsO: 135
term definiiion; I 12
events.
Menuitem.enableEvents():1095
term definition. AWTEvent: 113
menu items.
Menuitem. setEnabledO: 1102
MenultemPeer.setEnabledf): 1108
encryption algorithms,
J/\R support for. Applet; 76
END,
Fvent. replaced by KeyEvent. VK„END: 551
end(),
Pri nt Job: 1211
endVal i dateO,
Contai nerPeer: 469
environment,
applet. Sec applet, context
beans, term definition. Beans: 168
component. See locale
equality,
data flavor, testing for.
DataFlavor .equalsO: 504
dimensions, testing. Di mens ion. equa 1 s(); 5?l
font, testing for. Font. equals(): 644
insets.
testing for. Insets. equa 1 s(): 884
testing fur. MenuShortcut.equal s(): 111'
testing for. Point .equal s(): 1180
MIME content tvpe. testing tor.
DataFlavor.i sMimeTypeEqual(): 505
rectangles, testing lor. Rectangle.equal$():
1293
equals().
Color: 287
DataFlavor; 504
Di mensi on:521
F ont: 644
Insets: 884
MenuShortcut; 1113
Poi nt:1180
Rectangle:1291
ERROR,
ImageObserver: 834
ERRORED,
MediaTracker;1023
errors.
See AEo debugging: evcnt(s); exceptions: state:
status flags
AWTError: 108
image loading.
MediaTracker.ERRORED:1023
Medi aTracker.getErrorsAnyO: 1023
Medialracker.getE rrorsIDf): 1023
Medi aTracker. i sErrorAnyO; 1024
Matus flags. ImageConsumer, IMAGEERROR: 817
Event,
ACTION-EVENT, replaced by
ActionEvent.ACTION_PFRFORMED: 551
ALT MASK, replaced by
InputEvent.ALT_MASK:551
1594
arg. replaced by event-specific fields and methods:
551
cl ickCount. replaced hy
MouseEvent.getClickCount(): 552
cont co 1 Down ( ). replaced by
InputEvent.isCont rolDown(): 552
CTRL .MASK, replaced by
InputEvent.CTRL. MASK: 553
DOWN, replaced by KeyEvent .VK .DOWN: 551
END. replaced by KeyEvent. VK_END: 553
EventQ; 553
evt. replaced by EventQueue: 554
Fl. replaced by KeyEvent .VK _Г1: 555
F10. replaced by KeyEvent .VK _F10;555
Fil. replaced by KeyFvent.VK. Г11: 555
F12. replaced bx KeyEvent. VK^Fl'2; 555
F2. replaced by KeyFvent.VK_F2; 556
F3, replaced by KeyEvent.VK_F3: 556
F4. replaced by KeyFvent.VK_F4: 556
F5, replaced by KeyEvent .VK_F 5: 556
Г6. replaced by KeyEvent .VK_F6: 557
F7, replaced by KeyEvent. VK_F7; 557
F8. replaced by KeyEvent .VK_F8: 557
Г9. replaced by KeyEvent,VK_F9: 558
GOT FOCUS, replaced by
FocusEvent.FOCUS„GAINED: 558
HOME, replaced by KeyEvent .VK HOME; 558
id. replaced by AWTEvent .getIDO: 559
key. replaced by KeyEvent .getKeyCodeO; 559
KEY .ACTION, repla<-rd by
KeyEvent.KFY_PRFSSED;559
KEY_ACriON_RFLEASF, replaced by
KeyEvent.KEY„RELEASED:560
KEY .PRESS, replaced by
KeyEvent.KEY-PRESSED;560
KEY_RELEASE, replaced by
Key Event. KEY-RELEASED: 561
LEFT, replaced by KeyEvent .VK.LEFT: 561
LIST-DESELECT. replaced by
ItemEvent.DESELECT: 561
I 1ST SELECT, replaced by
ItemEvent.DESELECT: 562
LOAD.FILE;562
LOST_FOCUS, replaced hy
FocusEvent. FOCUS_LOST; 562
ME IA .MASK, replaced by
InputEvent.META^MASK; 562
TetaDown(). replaced hy
InputEvent.isMetaDownO; 562
modifiers, replaced by
InputEvent.getModifiersO: 563
MOUSF-DOWN, replaced by
MouseEvent.MOUSE_PRFSSED:563
VOUSE_DRAG, replaced by
MouseEvent.MOUSE-DRAGGED; 564
MOUSE_ENTER. replaced by
YouseFvent.MOUSE ENTERED:564
MOUSE FXTT. replaced hy
MouseEvent.MOUSF_EXIT FD: 564
VOUSF-VOVE. replaced by
MouseEvent.MOUSE-MOVED: 564
MOUSE-UP. replaced bx
MouseEvent.MOUSE_RE1 EASED; 565
paramStri ngO. replaced by
AWTEvent.paramString():565
PGDN. repluce<J by К EYE vent. VK PACE_D0W’N: 565
PGUP, replaced by KeyEvent .VK PAGE.UP; 565
replaced by AWTEvent: 534
RIGHT, replaced by KeyEvent.VK.RIGHT; 566
SAVF-F1LE:566
SCROLL .ABSOLUTE, replaced by
AdjustmentEvent. TRACK;566
SCROLL. LINE. DOWN, replaced by
AdjustmentEvent.UNIT_INCREMENT: 567
SC RO LI_LINE_UP. replaced by
AdjustmentEvent.UNIT-DFCREMENT; 567
SCROL I _PAGE_.DOWN. replaced hy
AdjustmentEvent.BLOCK-DECREMENT;567
SCROI L_PAGE_bP. replaced by
AdjustmentEvent.BLOCK DECREMENT; 567
SHTFT_MASK. replaced by
InputEvent.SHIFT .VASK;567
shi ftDownO. replaced by
InputEvent. i sShi ftDownO; 568
target, replaced by
AWTEvent. getSourceO: 568
toStringO. replaced by
AWTEvent.toStringO: 568
translateO. replaced by
MouseEvent.translatePoint();568
UP, replaced by KeyEvent.VK_UP; 569
when, replaced by InputEvent. getWhenO: 569
WINDOW.DE I CON IF Y. replaced by
Wi ndowEvent.WINDOW .DEICONIFIED: 570
WINDOW-DESTROY. replaced by
WindowEvent .WINDOW.Cl OSING: 570
WINDOW-EXPOSE, replaced by
WindowFvent.WINDOW ACTIVATED:57U
E INDEX
Event (con firmed)
WINDOW ICONIГУ. replaced by
WindowEvent.WINDOW_ICONIFIED: 571
WINDOW-MOVED, replaced by
ComponentEvent.COMPONENT-MOVED; 571
x. replaced by MouseEvent.getXO; 571
y. replaced by MouseEvent .getYO: 572
EventQ,
Event;553
event(s),
See A/wi AWTEvent
action. See action events
active. See active events
adapter, term definition. AWTEvent; 111
adjustment. See adjustment events
AWT. AWTEvent; 110
bean set de fault.
Beaninfo .getDefaul tEventlndexO; 164
SimpleBeaninfo.getDefaultEvent-
lndexO; 1370
term definition; 162
bean info.
Beaninfo.getEventSetDescri ptors0: 165
SimpleBeanlnfo.getEventSetDescri p-
torsO; 1371
button, Button.processEventO: 196
catching, See listeners
checkbox menu items, CheckboxMenuItem; 239
checkboxes.
Checkbox;221
Checkbox.processEventO; 228
Checkbox.processItemEventO; 228
checked menu items,
CheckboxMenuItem.processEventO: 243
choice, Choice.processEventO: 259
choice components. Choice; 251
component. See component(s). events
components.
Component.processComponentEventO; 371
Component.processEventO; 371
consuming,
AWTEvent .consumeO; 122
AWTEvent.consumed; 122
AWTEvent. i sConsumedO: 123
term definition, AWTEvent; 113
container, See container(s). events
containers. Contai ner. processEventO; 452
Dialog; 509
disabling.
Component .di sabl eEventsO; 332
Menuitem.di sableEventsO; 1093
dispatching.
ActiveEvent. di spatchO: 45
AWTEvent; 112
AWTEventMul ti caster; 128
Component .di SpatchEventO; И2
MenuComponent. di spatchEvent О; 107
enabling, term definition, AWTEvent; 113
flow.
ActionEvent:32
AdjustmentEvent;63
ComponentEvent;402
Contai nerEvent; 461
/• igure, AW1 Even t; 112
FocusEvent;632
InputEvent;872
ItemEvent;903
KeyEvent; 928
MouseEvent;1130
TextEvent;1451
WindowFvent; 1539
focus, See focus events
Frame;668
guaranteed sequences, MouseEvent: 1130
input. See input events
item.
See item events; item(s), events
key. See ke\ events
labels. Label; 955
iist(s). List.processEventO; 1003
listener.
AWTEventMulticaster.a;133
AWTEventMulticaster.b:136
listeners,
AWTEventMulticaster. removeO; 145
AWTEventMultleaster.remove
Internal():146
term definition. AWTEvent: 111
lists.
List; 983
Li st.processActionEventО; 1002
Li st.processEvent0:1003
Li st.processItemFvent();1003
Li st.removeActionLi stenerO: 1005
List. removeltemListenerO; 1007
musks.
AWT Event.ACTION. EVENT-MASK:120
1596
AWTEvent.ADJUSTMENT ,EVEN1_MASK;120
AWTEvent.COMPONENT EVENT-MASK; 1? I
AWTFvent.CONTAINER-EVENT MASK; 122
AWTEvent.FOCUS_EVENT„MASK; 123
AWTEvent.ITEM EVENT-MASK: 124
AWTFvent.KFY_tVENT_MASK; 124
AWTEvent.MOUSE_FVFN1 MASK; 124
AWTEvent.MOUSE-MOTION EVENT-MASK: 125
AWTEvent.TEXT.FVFNT.MASK; 126
AWTEvent.WINDOW-EVENT_MASK; 127
term definition. AWTEvent; 113
menu components.
MenuComponent.processEventQ; 1077
menu items. Menuitem. processFventQ; 1099
MenuBar; 1055
MenuComponent;1069
Menuitem;1089
menus. Menu; 1041
model. AWTEvent; HO
mouse. See mouse events
notification,
AWTEvent; 112
AWTEventMulticaster;128
processing, Container. processEventO; 452
properly change.
multi-change, PropertyChangeEvent: 1217
propagation id. PropertyChangeEvent; 1217
PropertyChangeEvent:1215
See property change events
queue.
adding to. FventQueue.postEventQ: 575
FventQueue; 573
EventQueue.getNextFventO; 574
EventQueue.peekEventQ; 575
(erm definiiion. FventQueue; 573
Toolkit. getSystemFventQueueO; 1493
Toolkit.getSystemEventQueuelmplQ;
1494
selectable. ItemSelectable: 914
semantics of. term definition. AWTEvent: 111
serializing of. FventQueue; 573
sources, term definition. AWTFvent; 111
state. AWTEvent. paramStri ngQ; 125
siring representation, AWTEvent. toStringO; 126
subtypes, term definition. AWTEvent, 110
term definition.
AWTEvent;110
Component; 307
text.
See text events
text components.
TextComponent. processFventQ: 1438
text fields. TextField. processFventQ; 1464
types.
action, term definition. AWTFvent; 111
AW Г event hierarchy organization of.
AWTFvent: 110
Component .enabl eEven tsQ; 335
defining. AWTFvent: 115
fired by AW I'components. Table. AWTEvent:
115
item, term definition. AWT Event: 111
Menuitem. enableFventsQ: 1095
vetoing. VetoableChangeSupport; 1510
window. See window events
windows.
Window,processEventQ;1529
Window.protessWindowEventQ: 1529
event sets,
class, FventSetDescriptor: 576
default attributes. EventSetDescriptor.set •
TnDefaultEventSetQ; 590
descriptor.
attributes. Table. FventSetDescri ptor; 577
term definition. EventSetDescriptor; 576
listener methods,
EventSetDescriptor.getLi stener-
MethodDescriptorsQ: 587
EventSetDescriptor.getLi stener-
Met hods Q;.588
listener support methods. EventSet-
Descriptor , getAddi i stenerMethodO; 58'
listener type. EventSetDescriptor .get-
Li stenerTypeO: 588
multicast signature pattern, Introspector: 892
Mate. EventSetOescriptor. isInDefault-
EventSetQ:589
term definition and components.
FventSetDescriptor; 576
unicast.
EventSetDesc riptor.isUnicastQ; 589
testing. FventSetDescriptor.set-
Uni castO; 590
unicast compared with multicast.
EventSetDescriptor; 578
unicast signature pattern. Introspector; 892
INDEX
EventQueue;573
EventQueueO: 574
getNextEvent():574
peekFventO; 575
postEvent О;575
EventQueueCX
EventQueue:574
EventSetDescriptor:576
EventSetDescr i ptorO:582
getAddListenerMethodO: 585
get Li stenerMethodDescriptorsO:587
getListenerMethods():588
getl i stener ГypeO; 588
getRemoveListenerMethodO; 589
isInDefaultEventSet(): 589
i sbnicast O:589
setInDefaultEventSet(); 590
setLni cast():590
EventSetDescriptorO<
EventSetDescriptor: 582
evt.
Event, replaced by EventQueue: 554
exceptions.
AWTException; 153
bean*. IntrospectionException; 887
data flavor.
UnsupportedFlavorException; 1503
Il legal ComponentstateExcept ion:793
IntrospectionException; 887
\etoablc properties.
PropertyVetoException:1286
expert.
as bean descriptor attribute. Tihlc\ 155
explicit.
bean descriptor, term definition,
BeanDescriptor; 154
tealure descriptors, Introspector; 890
indexed property descriptor,
IndexedPropertyDescriptor; 855
extension.
features. FeatureDescriptor,getValue(): 597
F
Fl.
Event, replaced by KeyEvent.VK_F1: 555
F10.
Event, replaced by KeyEvent.VK_F10; 555
Fil.
Event, replaced by Key Event .VK Fil; 555
F12.
Event, replaced by KeyEvent.VK_F12: 555
F2,
Event, replaced by KeyEvent.VK_F2: 556
FB.
Event, replaced by KeyEvent .VK_F3: 556
F4.
Event, replaced by KeyEvent .VK_F4; 556
F5.
Event, replaced by KeyEvent .VK_F 5: 556
F6.
Event, replaced by KeyLvent - VK_F6: 557
F7.
Event, replaced by KeyEvent.VK_F7; 557
F8.
Event, replaced by KeyEvent. VK_F8: 557
F9.
Event, replaced hy KeyEvent.VK E9: 558
family.
font.
Font;640
Font.getFamilyO: 645
feature descriptors.
bean info. SimpleBeanlnfo; 1165
class, ГeatureDescriptor; 591
introspector construction of, Introspector:;
name.
FeatureDescriptor.getNameO; 596
FeatureDescriptor.setNameO: >99
names. FeatureDescriptor,attribute-
NamesO; 595
(erm definition. FeatureDescriptor; 591
FeatureDescriptor;591
attributeNamesO: 595
FeatureDescriptorO; 596
getDiSplayNameO: 596
getNameO: 596
getShortDescriptionO; 597
getValueO; 597
i sExpert():598
isHiddenO; 598
setDisplayNameO: 598
setExpertО;599
setHi ddenО;599
setName():599
setShortDescri pti on 0:690
setVal ueO; 600
FeatureDescri ptorO,
FeatureDescriptor: 596
1598
features.
at hi bines.
IeatureDescriptor.isFxpertQ; 598
FeatureDescriptor.setHiddenQ:599
testing expert.
FeatureDescriptor.i sExpert О;598
testing hidden.
FeatureDescriptor.isHiddenQ; 598
description.
FeatureDescriptor.getShort-
Descri pt ion(): 597
FeatureDescri ptor.setShort-
DescriptionQ: 60(1
extension.
FeatureDescriptor .getValueQ: 597
FeatureDescri ptor. set Va 1 ueQ: 600
name.
FeatureDescri ptor.getDi spl ayNameQ;
596
FeatureDescriptor .getNameQ; 596
FeatureDescriptor.setDi spl ayNameQ;
598
TeatureDescr iptor. setNameO: 599
term definition.
FeatureDescriptor.getNameO: 591
file dialog,
directory property,
Fi 1 eDi alog.setDi rectoryO: 698
Fi leDialogPeer.setDi rectoryO: 612
file property.
F il eDi alog. getFi leQ: 666
FileDialog. setFi 1 eQ: 608
FileDialogPeer.setFileQ; 612
FileDialog; 601
mode.
Г ileDialog.getModeQ: 607
Fi leDialog.setModeQ; 609
peers. FileDialogPeer; 611
creating, FileDialog. addNot i fy0: 605
Mate. Fi leDi alog.paramStri ngQ; 607
file dialogs.
peers. Tool к i t .create Fi leDi a log Q; 1482
file format,
for archhes. See JAR (Java Archive)
file property,
file dialog,
f ileDialog.getFileQ. 606
Fi 1 eDialog.setFi leQ; 608
Fi1eDi alogPeer.setF i 1 eQ: 612
file dialogs, term definition. Fi leDialog; 601
FileDialog;601
addNoti fyQ;605
Fi leDialogQ; 605
getDi rectoryO; 606
getFi leQ: 606
getFi 1 enameF i IterQ: 607
getModeQ: 607
LOAD;607
paramStringQ: 607
SAVE:608
setDi rectoryO: 608
setFi leQ: 608
setFi lenameFi IterQ: 609
setModeQ; 609
FileDialogO,
FileDialog:605
FileDialogPeer; 611
setDi rectoryQ; 612
setFileQ; 612
setFilenameFiIterQ; 612
filename,
file dialog.
Fi leDialog.getFi 1 enameFiIterQ; 607
Fi leDialog. setFilenameFi IterQ; 609
Fi leDialogPeer.setFi lenameFi 1 terQ;
612
property,
FileDialog. getFi 1 enameFi IterQ; 607
fill,
gridbag.
GridBagConstraints.BOTH;743
GridBagConstraints.fi11;744
type. GridBagConstrai nts.HORIZONTAL;
749
type, GridBagConstrai nts.NONE; 753
type, GridBagConstrai nts .VERTICAL: 757
as gridbag constraint, tenn definition.
GridBagConstraints;738
fill,
Gri dBagConstrai nt s;744
fill3DRect(X
Graphics; 714
fillArcO,
Graphics:715
filled,
are, painting. Graphics.fi UArcQ; 715
circles, painting, Graphics.fi 1 lOval Q; 717
oval, painting, Graphics, fi 1 lOval Q; 717
event.
KeyEvent;928
MouseEvent;1130
TextEvent:1451
WindowEvent: 1539
FlowLayout: 618
getAlignment (): 622
getHgapO: 622
getVgapO: 624
layoutContainerQ; 624
setAli gnmentО: 626
setHgapO; 626
setVgapQ: 627
toStringO; 627
FocusEvent:632
InputFvent:872
ItemEvent;903
FlowLayout; 618
addlayoutComponentf):621
CENTER: 621
FlowLayout O; 621
getAlignment 0:622
getHgapO: 622
getVgapO; 624
layoutContainerO: 624
LFFT; 624
mi nimumLayoutSizeO; 625
preferredLayoutSizeO; 625
removeLayoutComponentO; 626
RIGHT: 626
setAlignmentО:626
setHgapO: 626
setVgapO: 627
toStri ng0: 627
Fl ow LayoutO,
FlowLayout;62 i
flush(),
Image:KOI
focus,
adapter, terrn definition. FocusAdapter; 628
Contai ner: 423
levels, term definition. FocusEvent; 632
requesting.
Component. requestFocusO; 381
ComponentPeer.request FocusО; 418
retrieving component with.
Window.getFocusOwnerО; 1525
tenn definition.
Component;305
FocusEvent:631
trasersable.
Component:305
Component. transferTocusO: 391
Container: 423
testing for.
Component, i sTocusTraversableO; 351
testing for. ComponentPeer. i sFocus-
TraversableO; 416
FOCUS_EVENT—MASK,
AWTEvent;123
focus events,
adapter class, FocusAdapter: 628
callback methods,
FocusLi stener.focusGai ned():638
Focus! istener. focusLostO;638
dispatching,
AW1 EventMul ticaster. focusGainedO: 139
AWTEventMulticaster.focusLost();140
event id,
FocusFvent.FOCUS_FIRS1; 634
FocusEvent.FOCUS.GAINED; 634
FocusEvent.FUCUS.l AS Г: 634
FocusEvent.FOCUS.!OST; 635
focus level. FocusEvent. i sTemporaryO: 636
FocusEvent: 631
listener.
Component.addFocusl istenerO: 321
Component.removeFocusLi stenerO:377
FocusLi stener: 63"?
mask for, AWTEvent. FOCUS EVENT.MASK: 123
processing. Component. processFocusEvent О:
373
state, FocusEvent.paramStringO; 636
terrn definiiion, FocusEvent; 631
FOCUS_FIRST,
FocusEvent:634
FOCUS—GAINED,
FocusFvent:634
FOCUS. LA ST,
FocusEvent: 634
FOCUS-LOST,
FocusEvent:635
FocusAdapter; 628
focusGai ned();630
focusLostО;630
FocusEvent; 631
FOCUS FIRST; 634
FOCUS-GAINED; 614
F
INDEX
filled ( continued)
poi > gon, painting. Graphics.fi 1 IPolygonQ:
718
rectangle, painting. Graphi cs.fi11 Rect (); 720
rectangles x\ ith 3D outline, painting.
Graphics.fillBDRectQ: 714
rounded rectangle, painting.
raphics.fi 11 RoundRectQ: 721
fillOval Q.
Graphics: 717
fil IPolygonO.
Graphi cs: 718
fill Recto.
Graphics: 720
fillRoundRectO,
Graphics: 721
FilteredlmageSource; 613
addConsumerQ;615
Fi 1 teredlrrageSourceQ: 615
i sConsumerQ: 616
removeConsumerO: 616
requestlopDowni ef tRi ghtResendQ: 616
start Product ionQ; 617
Fil teredlmageSourceO.
FilteredlmageSource:615
filterlndexColorModelQ.
RGBImageFilter: 1313
fil terRGBO.
RGBImageFilter: 1316
filterRGBPixels(),
RGBImageFilter:1316
filters.
area axeraging scale; 101
colors. RGBImageFi 1 ter .fil terlndex-
Col orModel (): 1313
file dialog.
F i1eDi al og.getFilenameFi1 ter();607
Fi1eDi alog.setFilenameFiIterQ:609
Fi ieDialogPeer.setFilenameFiIterQ:
612
term definition, FileDialog: 601
image.
AreaAveragi ngScal eFil ter; 101
AreaAveragingScaleFiIter.setHi ntsQ;
104
AreaAveragingScaleFiIter.set-
PixelsQ; 104
cropping. CropImageFi Iter; 471
ImageF il ter; 822
ImageFi Iter.cloneQ: 827
Imagel liter.getTi 1 terlnstanceQ: 827
oxen ide. RGBImageFi I ter.fi1 terRGBQ;
1316
override. RGBImageFi 1 ter.f i 1 terRGBPix-
els(): 1316
RGB. RGBImageFilter: 1309
stream. building, Fi 1 teredlmageSource; 611
term definition. ImageFi Iter: 822
term definition. Repl icateScal eFilter; 1104
replicate scale.
area axetaging scale filter compared with.
AreaAveragingScaleFilter;1OJ
term definition. Repl icateScal eF i 11 er; 1 Ю4
final izat ion.
Graphics.f i na1i ze():724
final izeQ.
Graphics;724
Pri nt Job: 1211
findEditorO.
PropertyEditorManager;1265
f i rePropertyChangeO,
PropertyChangeSupport:1227
PropertyEditorSupport:1272
fi reVetoabl eChangeO,
VetoableChangeSupport;1512
first,
exent id,
ItemEvent.ITEM FIRST; 906
Pai ntEvent. PAINT_FIRST Q: 1159
event ids. MouseEvent .MOUSE FIRSTQ; 1139
firstO,
Cardlayout: 212
flavors.
dat a.
retrieving. Stri ngSelect i on .get! ransfer
DataFlavorsQ: 1177
string selections. StringSelection; 1374
testing. Stri ngSelecti on. isDataFlavor-
SupportedQ: 1378
flickering.
term definition. Component; 308
flow,
ActionEvent:32
Adjustmentr vent;63
AWTEvent: 112
ComponentEvent:402
Contai nerEvent:461
1600
INDEX
FocusEvent (continued)
FOCUS.l ASI; 634
FOCUS LOST: 635
FocusEvent(); 635
isTemporaryO: 636
paramStringO: 636
FocusEvent(),
FocusEvent;635
focusGainedO,
AWTEventMulticaster; 139
FocusAdapter: 630
Focusl i stener; 638
FocusListener;637
focusGai ned():638
focusLostO; 638
focusLostO*
AWTEventMulticaster; 140
FocusAdapter: 630
FocusListener; 638
Font;639
BOLD; 642
decode0: 643
equals();644
FontO; 644
getFamily(); 645
getFontO; 646
getNameO; 646
getPeerO: 647
getSizeO: 647
getStyleO: 647
hashCodeО: 648
isBoldO:649
i sitaii с O:649
isPlainO; 649
ITALIC; 650
name;650
PLAIN: 650
size; 651
style: 651
toString(); 651
FontO*
Font; 644
font,
FontMetrics: 659
fontlsh
Sr? 4/.vo characters; strings; text
ascent.
Font Met ri cs . getAscentO: 661
FontMetrics.getMaxAscentO: 664
term del i ninon. Font Met ri cs: 653
baseline, term definiiion. FontMetrics: 653
class. Font; 639
dealing. Font. decode 0: 643
descent.
FontMetrics.getDescentO:661
FontMet rics.getMaxDescentО;664
(erm definition. Font Met ri c$; 653
equality testing lor. Font. equal s(): 644
famik name. Font .getFami lyO: 645
graphics context. Graphi cs: 686
hibh code, calculating. Font. hashCodeQ: 648
height,
FontMet rics.getHeight0:661
term definition. FontMetries: 654
leading.
FontMet rics.getLeadi ngО;662
term definition. FontMetrics: 653
li4 of. Tool kit. getFontLi st O: 1488
logical name.
Font .getFontO: 646
Font.name:650
metrics.
Component.getFontMet ri csO; 339
ComponentPeer.getFontMetricsО:414
FontMetrics: 653
FontMet rics.font:659
FontMetrics.getFontQ: 661
FontMet rics. toStringO: 666
Graphi cs.getFontMetri cs():727
Toolki t. getFontMet ricsO; 1488
name. Font. getName 0: 646
peers.
Font.getPeerO; 647
FontPeer; 652
lool ki t .getFontPeerO: 1489
piopertics. Font: 639
re trie \ mg.
Component.getFontO: 338
Font .getFontO; 646
F ontMetrics. get Font Q: 661
Graphics.getFontO; 726
MenuComponent .getFontO: 1(174
MenuContainer.getFont();1086
setting.
Component. setFontO; 385
ComponentPeer. setTontO: 420
Graphi cs.setFont О;732
MenuComponent.setFontО:1078
1602
size. Font .getSizeO: 647
siring representation. Font.toString(): 651
style,
Font. BOLD; 642
Font .getStyleO: 647
Font.ITALIC:650
Font.PLAIN:650
Font.style:651
lesting. Font. i sBoldQ; 649
testing. Font. isltal ic(): 649
testing. Font.isPlai n(): 649
term definition. Font; 639
widest character in font.
FontMetri cs.getMaxAdvanceC);662
width. FontMet ri cs. getWi dths 0: 664
FontMetrics; 653
bytesWidthf):658
charsWi dth():659
charWidth(): 659
f ont; 659
ГontMetricsO; 660
getAscentO;661
getDescentO; 661
getFontO; 661
getHeightО;661
getLeadingО:662
getMaxAdvanceC);662
getMaxAscent(); 664
getMaxDecent(). replaced by
getMaxDescent(): 664
getMaxDescentO: 664
getWidths0: 664
stringwidth О: 666
toStringO; 666
FontMetricsQ,
FontMetrics: 660
Font Peer; 652
foreground,
color.
Component.getForeground():339
Component. setForeqroundO: 385
ComponentPeer.setForeground();420
Graphics; 686
Graphics.getColor():725
Graphics.setColor(): 731
format.
file, for archives. Sec JAR (Java Archive)
Frame; 667
addNoti fyO: 670
CROSSHAIR_CURSOR. replaced by
Cursor.CROSSHAIR-CURSOR; 670
DEF AULT. CURSOR, replaced hy
Cursor.DEFAULT-CURSOR;670
disposeO; 671
F_RESIZE_CLRSOR. replaced by
Cursor.F_RESIZE_CURSOR: 672
Framef):672
getCursorTypeO. replaced by
Component.getCursor().get!уpi
getlconlmageO; 673
getMenuBarQ: 673
getTi tle(); 674
HAND CURSOR, replaced by
Cursor.HAND_CURSOR: 674
isResizableQ; 674
MOVE CURSOR, replaced by
Cursor.MOVE-CURSOR: 674
N-RFSIZt CURSOR, replaced by
Cursor.N_RESIZE_CURSOR; 674
NE. RLS1ZL-CURS0R, replaced by
Cursor.Nt RESIZE_CURSOR: 675
NW.RESIZE CURSOR, replaced by
Cursor.NW_RESIZE_CURSOR: 675
paramStri ng(); 675
remove();676
S_RFSIZE_CURSOR, replaced by
Cursor.S_.REST7F_CURS0R: 677
SE_RESIZE-CURSOR, replaced by
Cursor. SE-RESIZF-CURSOR; 677
setCursorO. replaced by
Component. setCursorO: 677
setlconlmageO; 678
setMenuBar();679
setResizableO; 680
setTi tle():681
SW_RESIZE-CURSOR, replaced by
Cursor.SW_RESIZE-CURSOR;677
TEXT-CURSOR, replaced by
Cursor.TEXT-CURSOR; 682
W_RFSIZE-CURSOR, replaced by
Cursor.W_RESIZE_CLRSOR:682
WAIT_CURSOR. replaced by
Cursor.WAIT CURSOR; 682
FrameO,
F rame;672
FRAMEBITS,
ImageObserver: 835
INDEX
FramePeer:683
setlconlmageO; 684
setMenuBarQ: 684
setResizableQ; 684
setTitle():684
frames,
class. Frame: 667
cursor, Frame: 667
destroying. Frame, di sposeO; б'71
event types fired by. table. AWTEvent: 115
events. Frame: 668
hints, ImageConsumer.SINGLEFRAME: 820
icon image.
F rame; 667
Frame.getlconlmageO: 673
Frame. setlconlmageO; 678
FramePeer. setlconlmageO: 684
menu bar,
Frame.getMenuBarf): 673
F rame.remove(); 676
Frame.setMenuBar(): 679
ГramePeer. setMenuBarO; 684
multi frame images,
term definition. Image: 796
term definition. ImageConsumer: 811
term definition. MemorylmageSourceO; 1029
peers.
creating. Frame. addNotifyO: 670
FramePeer; 683
Toolkit .createFrameO: 1482
popup menu. Frame, remove 0: 676
properties. Frame; 667
resizable property.
Frame.setResi zabl eO: 680
FramePeer. setResi zableO: 684
testing for. Frame,isResizable(); 674
status tlags>
ImageConsumer.SINGLE!RAMEDONF; 820
ImageObserver.FRAMEBITS: 835
term definition. Frame; 667
title.
Frame:667
FramePeer.setTi 11e();684
title property,
Гrame.getTi tleO; 674
Frame. setTi tleO; 681
G
gaps.
Ser А/л о inlets
border layout. BorderLayout: 177
card layout; 208
FlowLayout;618
grids. GridL ayout: 781
horizontal.
BorderLayout, getHgapO; 182
BorderLayout. setHgapO: 187
CardLayout.getHgapO:213
CardLayout. setHgapO: ? 19
FlowLayout.getHgapO; 622
FlowLayout.setHgapO;626
Gri dl ayout .getHgapO; 784
Gri dLayout. setHgapO: 790
vertical.
Borderl ayout. getVgapO: 183
Borderl ayout. setVgapO; 187
CardLayout.getVgapO; 215
Card! ayout.setVgapO: 219
FlowLayout .getVgapO: 624
Flow! ayout. setVgapO: 627
GridLayout .getVgapO: 786
GridLayout.setVgapO: 791
geometric shapes,
.See lines: ovals; points; polygons: rectangles: Sha
geometry.
See AEo arc: coordinates; lines: origin; ovals;
points: polygons; polyline: rectangles
gesture,
popup menu, term definition. PopupMenu: 1192
get/set signature pattern,
Introspector; 891
g e tAc t i onCommand(),
ActionEvent:37
But ton; 194
MenuItem:1096
getAdditionalBeanlnfoC),
Beaninfo: 163
SimpleBeanlnfo; 1169
getAddLi stenerMethodO,
EventSetDescriptor:585
getAdj ustabl e(),
AdjustmentEvent:67
getAdj ustmentTypeO,
AdjustmentEvent:68
1604
INDEX
getAlignmentO,
FlowLayout;622
Label;957
getAl i gnmentXO,
Component;336
Container; 435
getAl ignmentYO,
Component:316
Container: 436
getAlpha(),
ColorModel;299
Di rectColorModel: 531
IndexColorModel; 848
getAl phaMaskQ,
Di rectColorModel:531
getAlphas(),
IndexColorModel: 849
getAppletО,
AppletContext; 94
ge tApplet Con t e x t Q,
Applet;83
AppletStub:99
getAppl etlnfoO,
Applet:83
getAppl etsO,
AppletContext;94
getAscentC),
FontMetrics; 661
getAsTextO,
PropertyEdi tor: 1255
PropertyEditorSupport;1273
get AudioCi ipO*
Applet: 84
AppletContext:95
getBackgroundQ.
Component: 336
getBeanClassQ,
BeanDescriptor; 159
getBeanDescriptorО,
Beaninfo; 163
SimpleBeanlnfo:1370
getBeanlnfoO,
Introspector; 900
getBeanlnfoSearchPathO,
Introspector; 901
getBloc kinc rement(),
Adjustable: 57
Scrollbar; 1327
getBlueO.
Color: 287
ColorModel: 300
Di rectColorModel:531
IndexColorModel;849
getBl ueMaskQ,
Di rectColorVode1:5*2
getBluesQ,
IndexCo1orModel:849
getBoundingBoxQ,
Polygon, replaced by getBoundsO; 1188
getBoundsO.
Component:337
Polygon: 1188
Rectangle: 1294
Shape;1364
getCaretPosi tion О ,
TextComponent;1431
TextComponentPeer;1448
ge tChec kboxG roup().
Checkbox:225
getChildQ.
Containertvent;465
getCl ickCountQ,
MouseEvent:1136
getCl ipO,
Graphics; 724
getClipBoundsO,
Graphics; 725
getCl ipRectO,
Graphics, replaced by getClipBoundsO:
getCodeBaseO,
Applet: 84
AppletStub;99
getColorO.
Color: 288
Graphics;725
getColorModelO,
Component; 337
ComponentPeer:414
PixelGrabber; 1170
Toolkit; 1487
getCol umnsQ,
Gri dLayout;783
TextArea; 1409
FextFi eld; 1460
getComponentQ,
ComponentEvent; 407
Container; 436
INDEX
getComponentAt(),
Component:337
Contai ner: 437
getComponentCount О -
Contai ner: 437
getComponents()»
Contai ner:437
getConstraints(),
GridBagLayout:766
getContainer(),
ContainerEvent: 465
getContentsO,
Cl i pboard: ?71
getCurrentO,
CheckboxGroup, replaced h>
get Select edCheckboxQ; 236
getCursorO,
Component:338
getCursorType().
Frame. replaced b\
Component.getCursorO • getTypeO: 673
getCustomEditorО •
Property^ di tor; 1256
PropertyEdi torSupport: 1275
getCustomizerClassO,
BeanDescriptor; 160
getDefaul tCursorO,
Cursor; 481
getDefaultEventindexО,
Beaninfo:164
SimpleBeanlnfo; 1370
getDefaul tPropertylndexO,
Beaninfo;164
SimpleBeanlnfo;1371
getDefaul tTool ki tO,
Toolkit: 1488
getDescent(),
FontMetri cs: 661
getDirectoryO,
Fi 1 eDialog: 606
getDisplayNameО,
FeatureDescriptor;596
getDocumentBaseO,
Applet: 85
Appl etStub;99
getEchoCharO,
TextField: 1461
getEditorSearchPathO,
PropertyEditorManager;1265
getErrorsAnyO,
Med i aT racker;1023
getErrorsIDO,
MediaTracker: 1023
getEventSetDescriptorsf
Beaninfo: 165
SimpleBeaninfo: I 371
getFamilyO,
Font:645
getFileO,
Fi1eDi alog:606
getFilenameFilter(),
Fi1 eDialog;607
getFil terlnstanceO*
ImageFi 1 ter: 827
getFocusOwnerQ'
Window:1525
getFontO,
Component:338
Font: 646
f ontMetrics:661
Graphics: 726
MenuComponent:1074
MenuContai ner; 1086
getFontListO,
Toolkit: 1488
getFontMetricsO,
Component:339
ComponentPeer:414
Graphics;727
Toolkit;1488
getFontPeerO,
Toolki t: 1489
getForegroundO,
Component: ^9
getCraphicsO,
Component:340
ComponentPeer: 414
Image: 802
Pri ntJob: 1211
getGreenQ*
Col or; 290
ColorModel:300
Di rectColorModel:532
IndexColorModel:850
getGreenMask(),
DirectColorModel:532
getGreens(),
IndexColorModel:850
1606
jetHAdjustable().
Scroll Pane; 1350
getHeightO,
FontMetrics; 661
Image;ХОЗ
PixelGrabber: 1171
getHelpMenuО,
MenuBar: 1061
getHgapO,
BorderLayout: 182
CardLayout;213
FlowLayout: 622
GridLayout;7X4
getHSBColorO,
Color; 290
getHScrol1barHeightО,
ScrolIPane;1352
Scroll PanePeer; 1361
getHumanPresentabl eNameO,
DataFlavor: 504
getlconO'
Beaninfo; 165
SimpleBeanlnfo:1371
getIconimageО,
Frame:673
getIDO,
AWTEvent;123
getImageО,
Applet;85
AppletContext;96
Toolkit; 14X9
getlndexedPropertyTypeO,
IndexedPropertyDescriptor; 861
getlndexedReadMethodO,
IndexedPropertyDescriptor:861
getlndexedWri teMethodO,
IndexedPropertyDescriptor;865
getlnsetsO,
Container; 438
Contai nerPeer; 469
getlnstanceOfO,
Beans;171
getltemO,
Choi ce;257
ItemEvent;905
Li st:993
Menu;1047
getltemCountO,
Choice;257
Li st;993
Menu;1047
getltemsO,
Li st; 994
getltemSel ectabl eO,
ItemEvent:906
getJavain i11 ali zat i onSt r i ng О
PropertyEditor;1256
PropertyEditorSupport:1278
getKeyO,
MenuShortcut:1113
getKeyCharO,
KeyEvent:935
getKeyCodeO^
KeyEvent;937
getKeyModi f iersTextO,
KeyEvent:938
getKeyTextO,
KeyEvent;938
getlabelO,
Button; 195
Checkbox; 226
Menuitem;1096
getLayoutO,
Container; 440
getLayoutAl ignmentXO,
BorderLayout: 181
CardLayout; 212
Gri dBagLayout; 767
LayoutManager?; 979
getLayoutAl ignmentYO,
BorderLayout: 181
CardLayout; 212
GridBagLayout;767
LayoutManager?: 980
get LayoutDi mens ions О,
Gri dBagLayout;767
GetLayoutlnfoO,
GridBagLayout: 768
get LayoutOri gin О.
GridBaglayout;768
getLayoutWeightsО,
GridBagLayout;770
getLeadingO,
FontMetrics; 662
getLineincrementО,
Scrol Ibar, replaced by
getUni tlncrementQ: 1327
INDEX
getLi stenerMethodDescri ptorsO,
EventSetDescriptor;587
getListenerMethodsO'
EventSetDescriptor; 588
get Li stene гТуре О *
E ventSetDesc riptor;588
getLocaleO'
Applet; 85
Component;340
Window; 1526
getLocationO.
Component;340
Point;1180
Rectangle; 1294
get Locati onOnScreen().
Component;341
ComponentPeer: 415
getMapSizeO,
IndexColorModel:850
getMaxAdvanceO.
F ontMetrics; 66?
getMaxAscentCX
FontMetri cs:664
getMaxDecentO,
FontMet rics. replaced b\
getMaxDescentO: 664
getMaxDescent О.
FontMetrics; 664
getMaximumO.
Adjustable;57
Sc rol Ibar; 1328
getMaximumSizeO.
Component;342
Container: 440
getMenuO.
MenuBar;1061
getMenuBarO'
Frame;673
getMenuCountO.
MenuBar; 1062
getMenuShortcutKeyMaskO'
Toolkit; I49|
getMethodO.
MethodDescriptor; 1119
getMethodDescri ptorsO.
BeanInfo: 165
SimpleBeanlnfo; 1372
getMimeTypeO.
DataFlavor: 505
getMinimumО.
Adjustable: 57
Scrol 1 bar: 1328
getMi n i mumSi ze О ♦
Component:342
ComponentPeer; 415
Contai ner; 440
L ist:994
I i st Peer; 1011
TextArea; 1411
TextAreaPeer;1424
TextField;1461
TextFieldPeer: 1469
CetMinSizeO.
Gri dBagLayout;772
getModeO.
Fi 1 eDialog: 607
getModi fiersO.
Acti onEvent:37
Input Event:876
getNameO.
Cli pboard:274
Component: 43
F eatureDesc ri ptor;596
Font:646
MenuComponent;1074
getNat i veContai ne г О.
Tool kit: 1491
getNewValue().
PropertyChangeFvent:1219
getNextEventO.
EventQueue: 574
getOl dValueO.
PropertyChangeEvent: 1220
getOri entat i on О.
Adjustable: 57
Scrollbar; 1328
getPageDimensionO.
PrintJob; 1214
getPagelncrementО>
Scrollbar. replaced Ih
getBlocklncrementO; 132
getPageResol utionO.
Pri nt lob; 1214
getParameterО.
Applet;86
Appletstub:100
getParameterDescr iptors О,
MethodDescriptor: 1119
1608
getParameterlnfoQ. Applet:86 getParentQ, Component:145 MenuComponent:1076 getPeerC), Component: 345 Font: 647 MenuComponent:1076 getPixelsQ. PixelGrabber; 1171 getPixelSizeQ, ColorModel:300 getPointQ, MouseFvent;1136 getPredefi nedCursorO. Cursor: 481 getPreferredSizeO, Component: 145 ComponentPeer;415 Container; 441 Li st;995 Li stPeer: 1013 TextArea: 1411 TextAreaPeer;1424 TextField; 1462 TextFieldPeer; 1469 getPrintJobO, PrintGraphics;1202 Toolkit; 1491 getPropagat i onld Q, PropertyChangeEvent;1220 getPropertyO, Image; 804 Toolkit: 1492 getPropertyChangeEvent О, PropertyVetoException;1287 getPropertyDescriptors(). Beaninfo; 166 SimpleBeanlnfo:1372 getPropertyEditorClassО, PropertyDescriptor; 1235 getProper tyName О, PropertyChangeEvent.1220 get Proper tyType О, PropertyDescriptor: 1237 get ReadMe thod(). getRedQ. Color: 291 ColorMode1: 301 Di rectColorModel:533 IndexColorModel;851 getRedMaskQ, DirectColorModel:533 getRedsQ. IndexColorModel:851 getRemoveLi stenerMethod О EventSetDescriptor:589 get Representat i onClassО, DataFlavor; 505 getRGBQ, Color; 291 ColorModel;301 Di rectColorModel:533 IndexColorModel;851 SystemColor: 1395 getRGBdefaultO< ColorModel:301 getRowsO, Gri dLayout: 785 List:995 lextArea; 1412 getScaledlnstance Q, Image;804 getScreenResolutionQ, Toolkit: 1493 getScreenSizeO' Tool ki t: 1493 getScrol1barDi splayPoli суО ScrollPane:1352 getScrol1 barvisibility(), TextArea:1412 ge tSc rol1Pos i t i on Q. ScrollPane:1352 getSelectedCheckboxQ, CheckboxGroup: 237 getSelectedlndex Q. Choice;257 Li st:996 getSel ectedlndexesO. List: 996 ListPeer; 1013 getSelectedltem О, Choice;258
PropertyDescriptor: 1238 list: 996 getSel ectedl temsO* Li st;997
INDEX
getSelectedObjects О •
Checkbox;226
CheckboxMenuItem:24?
Choice;258
ItemSelectable:917
Li st;998
getSelectedText О,
TextComponent:1432
getSel ectionEndO.
Textcomponent:1433
TextComponentPeer;1448
getSelectionStartO*
TextComponent;1434
TextComponentPeer:1448
getShortcutO.
Menuitem;1096
getShortcutMenuItemO,
MenuBar: 1063
getShortDescriptionO,
FeatureDescriptor; 597
getSizeO.
Component: 346
Di mension; 523
Font; 647
Rectangle;1294
getSourceO.
Image:806
getStateO.
Checkbox;226
CheckboxMenuItem; 243
getstateChangeO<
ItemLvent:906
getStatusO.
Pi xelGrabber: 1172
getStyl eO.
Font;647
getSystemCl ipboardO.
Toolkit; 1491
getSystemEventQueueO.
Toolkit: 1493
getSystemEventQueuelmpl ().
Toolkit: 1494
getTagsO,
PropertyEdi tor: 1257
PropertyFdi torSupport: 1278
getTextO,
l abel;958
TextComponent:1436
TextComponentPeer;1449
getTitleO,
Di alog:514
F rame; 6 /4
getTool ki tO.
Component:346
ComponentPeer: 415
Window; 1526
getT ransferDataCL
StringSelection:1376
1ransf erable:1501
getTransferDataFl avorsO.
StringSelection; 1 377
1ransferable;1502
getTransparentPixel().
IndexCo1orMode1: 852
getTreeLockO-
Component:346
getTypeO,
Cursor: 482
getUnitlncrementO.
Adjustable;58
Scrol 1 bar: I 329
getllpdateRectO.
Pai ntEvent;1159
getVAdj ustable().
Scrol1 Pane: 1353
getValue(),
Adj ustable;58
AdjustmentEvent: 68
FeatureDescriptor;597
PropertyFditor;1257
PropertyEditorSupport;1279
Sc rol Ibar: 1329
getVgapO.
BorderLayout; 183
CardLayout: 215
FlowLayout:624
GridLayout:786
getVi ewportSizeO.
ScrollPane: 1353
getVisibleO.
ScrolIbar. replaced by
getvi si bleAmountO: 1330
getVisibleAmountО.
Adjustable; 58
Scrol Ibar; 1330
getVi si bl eindex О.
Li st:998
1610
INDEX
getVScrol1 barWidth()< Scrol1 Pane:1355 Scrol 1 PanePeer: 1 361 getWarningStringQ, Window;1526 getWhenO, InputEvent:877 getWidthO. Image:808 Pi xelGrabber: 1172 getWidthsQ* FontMetrics: 664 getWindow(). WindowEvent:1545 getWri teMethod()♦ PropertyDescriptor; 1240 getxo, MouseEvent: 1136 getYO, MouseFvent:1137 GOT.FOCUS, Event. replaced by FocusFvent.FOCUS.GAINFD; 558 gotFocusO, Corponent, replaced by FocusListener; 347 grabPixelsO. PixelGrabber: 1173 Graphics;685 clearRect(); 689 cli pRectО:690 copyAreaQ: 691 create О; 693 disposeO: 695 draw3DRectO: 695 drawArcQ: 697 drawBytesO: 699 drawChars():699 drawTmageO: 700 drawLi ne();70? drawOval0;704 drawPolygonО;^05 drawPolyline();707 drawRect0: 708 drawRoundRect(); 7Ю fi 1IRect O; 720 fi1IRoundRectO- 721 f i nal izeO: 724 getClipO: 724 getCl i pBoundsO: 725 getCli pRect (). replaced hy getC 1 ipBoundsO: 725 getColor0:7?5 getFontO: 726 getFontMetrics();727 GraphicsO: 728 setCl ipO: 728 setColorO: 731 setFontO: 732 set Pai ntModeO: 733 setXORModeO: 733 toStringO; 735 translate():735 GraphicsO* Graphics: 728 graphics context;s), class, Graphi cs; 685 clipping area, Graphi cs. cl i pRect0:690 Graphics.getflip(): 724 Graphics. getCl ipBoundsO: 725 Graphics. setClipO: 728 copying. Graphics. create 01 693 ci eating. for a print job. Pri ntlob.getGraphicsO; 1211 destroying. Graphics.di spose0:695 Graphics.finalize(); 724 Hushing. Tool к i t. sync 0: 1495 font metrics. Graphi cs.getFontvetr icsO; fonts. Graphi cs . get Г ontO: 726 Graphi cs. setFontO; 732 foreground color. Graphics.getColorO: 725 Graphics.setColorО:731 images. Image.getGraphics(): 802 initial values. Graphics: 687 moving. Graphics. trans lateO; 735
drawStri ng();712 fi 11 SDRectO: 714 f i 11 Arc (); 715 fillOval 0:717 fi 11 PolygonO; 718 paint mode. Graphics. setPaintModeO; 733 Graphics. setXORModeO; 733
INDEX
graphics con tex t( s) (conn'iiucth
painting,
characters, Graphics .drawBytesf): 699
characters, Graphi cs .drawChars(): 699
container components on,
Contai ner. pai ntComponentsO: 450
Graphics .drawImageO: 700
Graphi cs.drawLine():702
Graphics.drawOva1(): 704
Graphics-drawPolygon(); 705
Graphics.drawRectO: 708
Graphics.drawRoundRect();710
Graphi cs.drawSt r i ng():712
Graphics.fi11BDRect();714
Graphics. f i 11 Arc(): 715
Graphics.fi 1 lOval 0:717
Graphics, fill PolygonO: 718
Graphics.fi 11 RectO: 720
Graphics.fi11RoundRect():721
poly lines. Graphics.drawPolylineO; 707
print. PrintGraphics: 1201
printjobs, Pri nt Job. getGraphi csQ: 1211
printing.
components on.
ComponentPeer.print0: 417
container components on.
Contai ner.pri nt 0:451
Contai ner. pri ntComponentsO: 451
retries ing.
Component.getGraphi cs0:340
ComponentPeer.getGraph ics(): 414
state. Graphics,toString(): 735
term definition. Graphi cs: 685
translating. Graphi cs . t ransl ate(): 735
Bray,
Color.gray: 29]
dark. Color.darkGray: 285
light. Col or. 1 i ghtGray: 292
gray,
Color: 29|
green.
Color: 2.91
green component,
bit mask.
Di rectCo 1 orModel .getGreenMaskO: 532
Color.green; 291
pixel.
ColorModel .getGreenQ: 300
IndexColorModel .getGreenO: 850
IndexColorModel .getGreensO: 850
pixels. Di rectColorModel . getGreenO: 5 *2
retrieving. Color.getGreenO: 290
grid.
columns.
GridLayout.getColumns():783
Gri dl ayout. setColumns 0; 788
grid. Gridl ayout. setCol umnsQ: 788
lax out.
GridLayout.addl ayoutComponentО:783
Gri dLayout .getHgapO: 784
Grid! ayout .getVgapO: 786
GridLayout.layoutContainer():787
GridLayout .setHgapO: 790
GridLayout.setRowsО:791
Gridl ayout. setVgapO: 791
rows.
GridLayout.getRowsO: 785
Gri dLayout. setRowsO; 791
string representation.
Gri dl ayout.toStri ng();792
gridbag,
anchor.
GridBagConst rai nt s. anchor; 741
term definition. GridBagConstraints: 738
type. GridBagConstraints.CENT ER: 743
type, GridBagConstrai nts. EAST: 744
type. CridBagConst rai nts . NORTH: 75 *
type. GridBagConstrai nts . NORTHEAST; 753
type. Gri dBagConstrai nts. NORTHWEST: 753
type. Gri dBagConst rai nt s. SOUTH: 756
type. GridBagConstra ints. SOUTHEAST; 756
type. GridBagConstrai nts. SOUTHWEST: 756
type, GridBagConstraints.WEST: 758
cells. GridBagl ayout .MAXGRTDSI7F: 776
cloning. Gri dBagConstrai nts. cloneO: 743
column, width.
GridBagLayout.columnWidths: 766
components,
Gri dBagLayout,AdjustF оrGravity(): 764
constraints,
GridBagConstraints;738
GridBagl ayout.defaultConstrai nts: 766
Gri dBagLayout.getConstrai nts():766
GridBagLayout.lookupConstraints(), 776
GridBagLayout.setConstraintsf): 779
container, calculating layout.
Gri dBagLayout.GetLayoutInfo();768
a\ container, term definition. GridBagLayout; 759
1612
INDEX
copying. GridBagConstraints.clone(): 743
dimensions.
Gr idBagLayout .getLayoutDi men si onsQ:
767
GridBagLayout .GetMinS i zeO; 772
GridBagLayout.MAXGRIDSIZE: 776
fill.
GridBagConstraints.fi11: 744
term definition. GridBagConst rai nts; 738
lype.
GridBagConstrai nts.BOTH;743
GridBagConstrai nts.HORIZONTAL: 749
GridBagConstraints.NONE:751
GridBagConstraints.VERTICAL;757
hash table, GridBagLayout.comptable: 766
height of component,
GridBagConstraints.gridheight: 746
i n set
Gri dBagConstraints.insets:750
term definition. Gri dBagConstra i nts: 738
mleniiil padding,
height. GridBagConstraints.ipady; 75?
term definition. GridBagConstraints: 738
width. GridBagConstrai nts. ipadx; 751
laying out. GridBagL ayout.ArrangeGridO; 764
layout.
GridBagLayout;759
GridBagLayout.addiayoutComponentO:
763
GridBagLayout.getLayoutAlignmentXO:
767
GridBagL ayout .getLayoutAl ignmentYO:
767
GridBagLayout.invalidate! ayout0: 772
GridBagL ayout .layoutContainerO: 773
location, Gri dBagLayout. getLayoutOri gin О;
768
position, term definition. GridBagConstraints;
738
si/e.
GridBagConstrai nts-RELATIVE: 754
GridBagConstraints.REMAINDER; 754
term definition. GridBagConstraints; 738
state, GridBagLayout. toStringO; 780
term definition, GridBagConstraints; 738
weight.
column.
GridBagConstraints.wei ghtx;757
Gri dBagLayout.columnWeights:764
row.
GridBagConstraints.weighty; 758
GridBagLayout.rowWeights; 779
term definition. GridBagConstra i nts: 738
weighs,
GridBagLayout.getLayoutWeights():770
width of component.
GridBagConstraints.gridwidth: 746
л -coordinate cell location for component.
GridBagConstraints.gridx: 748
\-coordinate cell location for component.
GridBagConstraints.gridy: 749
GridBagConstraints;738
anchor: 741
BOTH: 743
CENTER: 743
cloneQ: 743
EAST: 744
fill:744
GridBagConstraints():745
gri dheight:746
gri dwidth: 746
gridx: 748
gridy; 744
HORIZONTAi : 749
i nset s:750
ipadx:751
i pady:752
NONE;753
NORTH:753
NORTHEAST; 753
NORTHWEST; 753
RELATIVE;754
REMAINDER:754
SOUTH; 756
SOUTHEAST; 756
SOUTHWEST; 756
VERTICAL;75?
wei ghtx;757
wei ghty;758
WEST: 758
GridBagConstraintsQ,
GridBagConstraints:745
GridBagLayout:759
addLayoutComponentО: 763
AdjustForGravi tyO: 764
ArrangeGridO: 764
columnweights;764
columnwidths;766
н
INDEX
Gri dBag Layou t (< on tinned)
comptable: 766
defaultConstraints;766
getConstrai ntsO;766
get LayoutAli gnmentXO: 767
getLayoutAl i gnmentYO; 767
getLayoutDimensionsO: 767
CetLayoutlnfoO; 768
get LayoutOriginO: 768
getLayoutWeights();770
GetMinSizeQ; 772
GridBagLayoutO; 772
i nvalidateLayoutO; 772
1ayoutContai ner(): 773
1ayoutlnfo; 773
locati on(); 773
lookupConstrai ntsO; 776
MAXGRIDSIZE;776
maximumLayoutSize(); 776
minimumLayoutSize();777
MINSI7F;777
preferred! ayoutSizeO; 777
PRLFLRRFDSIZE; 778
removeLayoutComponentO; 778
rowHeights:778
rowWeights;779
setConstraintsO; 779
toStringO; 780
GridBagLayoutO,
GridBagLayout; 772
gridheight,
GridBagConstraints;746
GridLayout;781
addLayoutComponentO;783
getColumnsO; 783
getHgapO; 784
get Rows О;785
getVgapO; 786
GridLayoutО:786
1 ayoutContai nerO; 787
minimumLayoutSizeO: 787
preferredLayoutSizeO; 788
removeLayoutComponentO: 788
setColumnsQ; 788
setHgapO; 790
setRowsO: 791
setVgapO; 791
toStri ngO; 792
GridLayoutO,
Gri dLayout;786
grids,
columns. GridLayout; 781
components.
GridLayout.addLayoutComponent О;783
gaps, GridLayout; 781
Gri dLayout;781
rows. GridLayout; 781
term definition, Gri dLayout; 781
gridwidth,
GridBagConstrai nts;746
gridx.
Gri dBagConstrai nts;748
gridy,
GridBagConstraints;749
growOw
Rectangle;1294
GUI (Graphical User Interface),
See window(s)
H
hand,
cursor. Cursor. HAND_CURSOR: 483
HAND-CURSOR,
Frame, replaced by Cursor.HAND-CURSOR: 674
Cursor; 483
handleEventО,
Component, replaced by processEventO; ^48
ComponentPeer:416
hash code,
color, calculating, Color.hashCodeО; 292
font, calculating. Font.hashCode(): 648
point, calculating. Point. hashCodeO; 1181
rectangle, calculating, Rectangle. hashCodeО:
1295
hash table,
GridBagLayout.comptable; 766
hashCodeQ,
Color: 292
Font;648
Poi nt:1181
Rectangle;1295
height,
component.
GridBagConst raints.gridheight;746
dimension, Dimension.height; 525
font, FontMetrics .getHeightО: 661
fonts, term definition, FontMetrics; 654
1614
INDEX
image. Image.getHeight (); КОЗ
images.
ImageObserver.HEIGHT: 835
ReplicateScaleFiIter.srcHei ght:13()X
internal padding. GridBagConstrai nts. ipady:
752
minimum. GridBagLayout. rowHeights: 778
pixel buffer. Pi xel Grabber. getHei ght Q: 117]
rectangles, calculating. Rectangle.hheight: 1295
rows, Gri dBagLayout. rowHeights: 778
scaled images. Repl icateScalefi It er. des-
tHeight; 1305
height.
Di mension:525
HEIGHT,
ImageObserver: 815
height.
Rectangle: 1295
Help menus,
MenuBar.getHel pMenuQ:1061
venuBar. setHel pMenuQ: 1065
MenuBarPeer, addMenuO: 1068
term definition. MenuBar; 1054
hidden,
as bean descriptor attribute. Table 155
hideQ,
Component, replaced by setVi si bl e(): 349
ComponentPeer, replaced by setVi si bl e(): 416
hiding,
components.
ComponentAdapt er.componentHi ddenQ:
399
ComponentEvent.COMPONENT-HIDDEN; 404
ComponentListener.componentHiddenQ:
409
features,
FeatureDescriptor. set ExpertO; 599
FeatureDescriptor. setHiddenQ: 599
testing expert.
FeatureDescriptor.isExpertQ: 598
testing hidden.
Featu reDesc r i ptor.i sHi dden(); 598
hierarchy.
class, esent t\pe use constiained by. AWTEvent: I 15
component, term definition; 3<)3
hints,
frames, ImageConsumer.SINGLEFRAME: 820
image.
AreaAveragi ngScal eFi 1 ter. setHi ntsQ:
104
ImageConsumer. setHintsQ: 818
ImageConsumer.SINGLEFRAME: 820
ImageFi Iter. setHintsQ: 829
PixelGrabber. setHint s(): 1175
images, term definition. ImageConsumer: 811
pixel delivers,
ImageConsumer .COMPLFIESCANLIN’ES; 816
ImageConsume r.RANDOMPIXELORDER;817
ImageConsumer.SINGLEPASS: 82!
ImageConsu'ner.TOPDOWNLFFTRIGHT: 821
HOME,
Event, replaced by KeyEvent .VK-HOME; 558
horizontal.
gap.
BorderLayout .getHgapQ; 182
BorderLayout. setHgapO; 187
CardLayout.getHgapQ: 213
CardLayout. setHgapO; 219
FlowLayout.getHgapQ; 622
FlowLayout. setHgapQ; 626
GridLayout. getHgapQ; 784
GridLayout. setHgapO; 790
gaps, FlowLayout; 618
HORIZONTAL,
Adjustable: 59
GridBagConstraints; 749
Scro 1 Ibar; 1330
HSB (hue. saturation, brightness) color system,
converting RGB to. Color. RGBtoHSBQ; 293
convening to RGB, Color .HSBtoRGBQ: 292
creating color from. Color. getHSBColorQ; 29(
term definition. Color; 278
HSBtoRGBQ,
Color; 292
HTML (Hypertext Markup Language).
applet tag. Applet: 77
pagev Appl etContext. showDocumentQ: 96
I
IC0N_C0L0R_16xl6.
Beaninfo; 166
ICON—COLOR_32x32,
Beaninfo: 167
icon image,
frame.
Frame.setlconlmageO: 678
FramePeer. setlconlmageO; 684
frames. Frame .getIconimageQ: 673
property. Frame; 667
term definition. Frame: 667
I
INDLX
ICON_MONO_16x16.
Beaninfo: 167
ICON—MONO_32x32,
Beaninfo: 167
icon i fied,
term definition. Wi ndowEvent: 15 V)
id,
I-vent, replaced by AWT Fvent . getlDQ: 559
AWTEvent: 123
ids.
event See e\ent(s|. id
Ill egalComponentStateException;793
Il 1 egalComponentStateExceptionQ: 794
Il 1 egal ComponentStateExceptionO«
TilegalComponentStateFxception:794
Image;795
flushO: 801
getGraphicsQ: 802
getHeightQ:803
getPropertyQ: 804
getScaledlnstanceQ: 804
getSourceQ: 806
getWidthQ; 808
SCALE_AREA_AVERAGING: 808
SCALE.DEFAULT: 809
SCALE FAST: 809
SCALE REPLICATE:809
SCALE-SMOOTH:810
UndefinedProperty:810
image(s)'
.See Also pixels
color model,
ImageConsumer.setColorModelQ:8I7
ImageFi1 ter.setColorModelQ: 828
original. RGBImageF i 1 ter.origmodel: 1119
PixelGrabber,setColorModel Q: 1175
replacing. RGBImageFil-
ter. subst i tuteCol orMode IQ: 1320
RGBImageFi1 ter.setColorModelQ: 1319
completion status,
ImageConsumer.imageComp 1 eteQ: 816
Imageri 1 ter, imageCompl eteQ: 828
PixelGrabber.imageCompleteQ: 1173
consumers. See con sinners
creating.
Component.createlmageО;329
ComponentPeer.createlmageQ: 413
Tool ki t. createlmageQ: 1482
Toolki t .getlmageQ: 1489
cropping, CropImageF i 1 ten 471
destroying. Image. flushO: 801
dimensions,
CropImageF i1 ter,setDimensionsO:475
ImageConsumer.setDimensi onsQ: 818
ImageFi Iter.setDimensionsO: 829
Pi xelGrabber. setDimensi onsQ: 1175
ReplicateScaleF ilter.set-
Dimensi onsQ: 1306
filter. RGB. RGBImageFilter: 1309
filtering. RCBImageFilter.fi Iterlndex-
Col orModel Q: 1313
filters.
AreaAveragingScaleFi1 ter: 101
AreaAveragingScaleFi Iter.setHintsQ:
104
ImageFiIter: 822
ImageFiIter.cl one(J: 827
ImageFi 1 ter. getFi 1t erlnstanceQ: 827
override. RGBImageFi 1 ter.f i 1 terRGBQ.
1316
override. RGBImageFi 1 ter. f i 1 terRGBPi x
elsQ: 1316
ReplicateSca1eFi1 ter: 1304
stream, building. Fi 1 teredlmageSource: 6В
tetm definition. ImageFiIter: 822
graphics context. Image .getGraph i cs Q: 802
height.
Image.getHei ght Q: 803
ImageObserver.HEIGHT: 835
Repl i cateScaleFi 1 ter. srcHei ght: I Ю8
hints,
AreaAveragingScaleFi Iter .setHintsQ:
104
ImageConsumer.COMPLETESCANLINLS: 816
ImageConsumer.RANDOMPIXELORDFR: 8P
ImageConsumer.setHintsQ:818
ImageConsumer.SINGLEFRAME: 820
ImageConsumer.SINGLEPASS: 821
ImageConsumer.TOPDOWNLEFTRIGHT: 821
ImageFi Iter. setHi ntsQ: 829
Pi xelGrabber.setHintsQ: 1175
term definition. ImageConsumer: 811
icon.
Frame; 667
Frame.getlconlmageQ; 673
Frame. setlconlmageQ: 678
ГramePeer. set IconlmageQ: 684
Image;795
1616
loading.
Component .ImageUpdateO: 349
ImageObserver. imageUpdateO: 836
MediaTracker:1016
MediaTracker.ABORTED:1020
Medialracker.checkAl1();1021
Medi aTracker. checkIDO: 1022
MediaTracker.COMPLETE.1022
MediaTracker.FRRORED:1023
•Medi aTracker .imageUpdateO: 1024
MediaTracker.i sErrorAny(): 1024
MediaTracker. isErrorlDO: 1024
MediaTracker. 1OADING; 1025
MediaTracker. removeTmageO: 1025
MediaTracker.waitForAl1O;1027
MediaTracker .waitForlDO; 1028
SimpleBeanlnfo. loadlmageO; 1372
Tool к i t. preparelmageO; 1495
triggering.
Component .preparelmageO: 369
ComponentPeer. preparelmageO: 417
multi-frame,
term definition. Image; 796
term definition. ImageConsumer: 811
observer, term definition. Image: 795
observers. See observers
off-screen, term definition. Image; 796
pai ruing.
Graphics: 687
Graphics.drawImageO; 700
pixel delivery,
AreaAveragingScaleFil -
ter. setPixel sO: 104
CropImageFi1 ter.setPi xels(): 475
ImageConsumer.setPixels(): 819
ImageFi1 -
ter. resendTopDownLeftRightO: 828
ImageTi Iter. setPixelsO; 830
PixelGrabber.abortGrabbingO: 1170
PixelGrabber.grabPixels();1173
PixelGrabber. setPi xel sQ; 1176
PixelGrabber.startGrabbing():1177
Repl icateScaleFi 1 ter. setPixelsO; 1306
retrieving. PixelGrabber; 1167
RGBImageFi 1 ter. setPi xel sO: 1319
produced, term definition. Image; 796
pnxiucers. See producers
properties,
CropImageFil ter. setPropertiesO: 476
Image. getPropertyO: 804
Image,UndefinedPropert y: 810
ImageConsumer.setPropertiesO: 819
ImageFi Iter. setPropertiesO; 830
ImageObserver.PROPERTIES: 837
PixelGrabber.setPropert ies0: 1176
Repli cateScaleFiIter.set
PropertiesO: 1307
term definition. Image: 796
retrieving. AppletContext. getlmageO: 96
scaled.
Rep1icateSca1eFi1 ter.destHeight;130:
Repl icateScaleFi Iter.destVvidth: 130
scaling.
AreaAveragi ngScaleFi1 ter: 101
Image.getScaledlnstanceO:804
Image.SCAI E AREA„AVERAGING specification
of: 808
Image. SCALF. REPLICATE specification ol; 81
Medialracker.addTmageO: 1021
specification of. Image. SCALE_DF FAULT: 809
specification of. Image.SCALF FAST: 809
specification of. Image.SCALF_SMOOTH; 810
state.
Component. checklmageO; 324
ComponentPeer.checklmageO:413
ImageConsumer.I^AGEERROR: 817
Medi aT racker. getErrorsIDO: 1023
MediaTracker.statusAll(); 1026
Toolki t. checklmageO; 1479
status flags.
ImageConsumer.IMAGEABORTED: 816
ImageConsumer.SINGLEFRAMEDONE; 820
ImageConsumer.STATICIMAGEDONF; 821
ImageObserver.ABORT: 834
ImageObserver.ALLBITS: 834
ImageObserver.ERROR: 834
ImageObserver.FRAMEBITS; 835
ImageObserver.HEIGHT: 835
ImageObserver.PROPERTIES: 837
ImageObserver.SOMEBITS; 837
ImageObserver .VvIDTH; 837
MediaTracker.ABORTED:1020
MediaTracker.COMPLETE;1022
MediaTracker.ERRORED: 1023
MediaTracker.LOADING; 1025
term definition. Image: 795
at a URL. Applet .getlmageO; 85
1
INDEX
Image (continued}
width.
Image.getWidth(): KOS
ImageObserver.WIDTH; 837
ReplicateScaleFilter.srcWidth; 1308
IMAGEABORTED.
ImageConsumer;816
i mageComplete()*
ImageConsumer; 816
ImageFi 1 ter; 828
Pi xelGrabber; 1173
ImageConsumer; Kl 1
COMPl FIFSCANLINFS: 816
I MAGE ABORTED; 816
imageCompleteO; 816
IMAGEERROR; 817
RANDOMPIXFl ORDER; 817
setColorModelQ: 817
sotDimensionsO: K18
setHints();818
setPi xels();819
setPropertiesO; 819
STNGI FFRAMF;820
SINGLEERAMEDONE;820
SINGLEPASS;821
STATICIMAGEDONE; 821
TOPDOWNLEFTRIGHT; 821
IMAGEERROR,
ImageConsumer:817
ImageFilter;822
cloneQ; 827
consumer: 827
getFi 1terlnstance(); 827
imageCompleteO; 828
resendTopDownLeftRightO; 828
setCo1orMode1 0:828
setDimensions();829
setHi nt s():829
setPixelsO: 830
setPropertiesO: 830
ImageObserver;831
ABORT; 83*4
ALLBITS:834
ERROR;834
FRAMFBITS;835
HEIGHT: 835
i mageUpdate (); 836
PROPERTIES;837
SOMEBITS;837
WIDTH: 837
ImageProducer:838
addConsumer();843
i sConsumerO: 843
removeconsumerО:843
requestlopDownLeftRightResendO: 844
startProduction(); 844
imageUpdateO,
Component; 149
ImageObserver: 816
Medi alracker; 1024
implicit,
bean desetiptor. term definition.
BeanDesc r i ptor: 154
implicit indexed property descriptor,
term definition.
IndexedPropertyDescriptor;855
i nact i veCapt i on,
SystemColor; 1396
i nac t i veCapt i on Во г de r,
SystemColor;1396
inactiveCaptionText.
SystemColor;1396
increments.
block.
adjustable components, term definition.
Adjustable: 48
Adjustable.getBlockincrement 0: 57
Adjustable.setBlоскIncrement(): 59
BLOCK_INCREMENT: 37
scrollbar.
Scrol Ibar.setLi nelncrement0: 1342
Scrol1 bar.setPageIncrement(); 1 42
ScrollPanePeer,setUni tIncrement():
1362
scroll bars.
Scrol1 bar.setBlockIncrement 0. 13 U
Scrol 1 bar. setMaximumO: 1334
ScrolIbar.setMinimumC):1335
Scrollbar.setUnitlncrement();1338
unit.
adjustable components, term definition.
Adjustable;48
Adjustable.get Uni tine rement(); 58
Adjustable.setUni tlncrementО.60
AdjustmentEvent.UNIT INCREMENT; 69
independence.
platform. See A No peers
1618
index color model.
IndexColorModel: 845
ierm definition.
ColorModel: 295
IndexColorModel.845
IndexColorModel:845
getAlphaQ:848
getAlphasQ: 849
getBlueQ:849
getBluesQ; 849
getGreenO; 850
getGreensQ: 850
getMapSizeQ; 850
get Red Q; 851
getRedsQ;851
getRGBQ: 851
get IransparentPi xelQ:852
IndexColorModelQ:852
IndexColorModelQ,
IndexColorModel;852
indexed properties,
accessor methods.
IndexedPropertyDescri ptor.get-
IndexedReadMethodQ; 861
IndexedPropertyDescri ptor.get-
IndexedWri teMethodQ: 865
descriptor.
attributes. Table,
IndexedPropertyDescriptor;855
IndexedPropertyDescriptor; 854
term definition.
IndexedPropertyDescriptor; 854
element tv pc. IndexedPropertyDescrip-
tor .getIndexedPropertyTypeQ: 861
signature pattern. Introspec tor: 892
term definition, IndexedPropertyDescri ptor:
854
IndexedPropertyDescriptor; 854
getlndexedPropertyTypeQ; 861
getlndexedReadMethodQ; 861
getlndexedWri teMethodQ: 865
IndexedPropertyDescri ptorQ;866
IndexedPropertyDescriptorQ,
IndexedPropertyDesc ri ptor; 866
info,
SystemColor: 1197
info-tags,
background color: 1397
SystemColor.info: 1397
term definition. SystemColor: 1382
text color. SystemColor. i nfolext: 1397
infoText,
SystemColor: 1397
initO,
Applet;87
initializing,
applets. Applet.init Q; 87
property x allies.
PropertyEdi tor.getJavaini tializa-
tionStringQ; 1256
PropertyEdi torSupport.get Java-
Ini tial izationStringQ: 1278
input events,
consuming.
term definition. InputFvent; 871
testing lor. InputEvent. isConsumedQ; 878
How.InputEvent:872
InputFvent;871
modifier keys,
InputEvent:872
InputFvent.META_MASK:880
InputFvent.SHIFT-MASK;880
masks. InputEvent.ALT MASK; 874
musks. InputEvent, CTRL .MASK: 876
state. InputEvent. getModi fiersO; 876
testing. InputEvent. i sAl tDownQ; 878
testing. InputEvent. i sCont rol Down Q; 879
testing, InputEvent. i sMetaDownQ; 879
testing. TnputEvent.i sShi ftDownQ: 879
mouse button modifier mask.
All kev. InputEvent. BUTT0M_MASK; 875
Alt kev. Input Event. BUTT0N2-MASK; 875
Alt key, InputEvent.BUTTONS-MASK; 875
processing of, AWTEvent; 11 3
simulating. InputEvent; 872
timestamp.
InputFvent;872
InputEvent.getModi fi ers():876
InputEvent:871
Al I-MASK; 874
RUTTOM_MASK; 875
BUГT0N2_MASK:875
BUTTON3-MASK:875
consumeQ:876
CTRL MASK; 876
1
INDEX
InputEvent ((OfitiHued;
getModifiers O: 876
getWhen(); 877
1sAltDown(); 878
isConsumed(): 878
i sCont ro1 Down();879
i sMetaDownQ < ^79
isShiftDownO: 879
META_MASK; 880
SHIFT-MASK: 880
insertO,
Choice;258
Menu:1047
TextArea;1414
lextAreaPeer:1424
i nsertSepa rator O.
Menu:1049
insertTextQ,
Tex tArea, replaced by insertO; 1415
TextAreaPeer. replaced by insertO: 1425
insets,
See Also gaps
bottom. Insets .bottom: 884
card layout: 208
cloning. Insets.cloneO: 884
container.
Container .getlnsetsO: 438
ContainerPeer.getlnsetsQ: 469
LayoutManager: 964
containers, term dellnition. Contai пег: 422
copying. Insets.cloneO; 884
equality, testing for. Insets. equal sQ: 884
frames, Frame; 667
gridbag. GridBagConstrai nts. insets; 750
as gridbag constraint, term definition,
GridBagConstraints: 7$8
Insets;881
left value, Insets.left: 885
right value. Insets, right: 885
string representation. Insets.toStringO; 885
term definition. Insets; 881
top value, Insets. top: 885
Insets;881
bottom;884
cloneO: 884
equalsO; 884
InsetsO: 885
1 eft:885
right; 885
top: 885
toStringO: 886
insets,
GridBagConstraints;750
Insetsf).
Insets: 885
insetsO,
Container, replaced by getlnsetsO: 441
ContainerPeer, replaced by get InsetsO; 47(
insideO.
Component, replaced by contai ns О; 350
Pol ygon, replaced by contai ns 0: 1189
Rectangle, replaced by contai ns О; 1296
instantiateO,
Beans;172
interaction,
adjustable components class. Adjustable; 47
interface,
event listener, term definition, AWTEvent: 111
internal padding.
gridbag.
height, GridBagConstraints. ipady: 752
width. GridBagConstraints. ipadx: 751
as gridbag constraint, term definition.
GridBagConstraints:738
i ntersectionO,
Rectangle;1296
intersections,
rectangle, calculating.
Rectangle,intersect!on();1296
rectangles, testing for.
Rectangle.intersectsf); 1297
intersectsO*
Rectangle:1297
introspection.
See Also method descriptors
exceptions, IntrospectionException; 887
lenn definition.
Beaninfo:161
IntrospectionException; 887
Introspector:890
SimpleBeanlnfo;1365
IntrospectionException:887
IntrospectionException О; 889
IntrospectionException().
IntrospectionException:889
introspector.
bean descriptor access, BeanDescriptor; 154
1620
bean-in t и,
Introspector.getBeanlnfoО;900
Introspector.getBeanInfo-
SearchPath();901
Introspector.setBeanInfo-
SearchPathO: 901
event set descriptor u>e bx.
EventSetDescriptor: 577
string decapitalization.
Introspector.decapita 1 izeO: H99
Introspector; 890
decapi tai ize(); 899
getBeanlnfo(); 900
getBeanlnfoSearchPathO: 901
setBeanlnfoSearchPathf);901
invalidatef),
Component:350
Container: 442
i nvali dateLayou t О,
BorderLayout:184
CardLayout; 216
Gri dBagLayout;772
LayoutVanager2:980
invalidating.
components. Component.inval idate(); 350
containers. Container.!nvalidateO; 442
layout manager state.
BorderLayout. i nval i dateLayoutO; 184
CardLayout.invalidateLayoutO:216
GridBagLayout.invalidatelayout(): 772
LayoutManager?.invalidateLayout O; 980
invisibility;
setting. Component. setVi s ible(): 387
invoking,
layout manager.
Component.doLayoutO; 335
Contai ner.do!ayoutО; 435
Scrol 1 Pane .doLayoutO: 1350
ipadx,
Gri dBagConstraints;751
i pady,
Gri dBagConstrai nts;752
is/get/set signature pattern,
Introspector: 891
isActionKeyO,
KeyFvent;941
isActiveO,
Applet; 87
AppletStub;100
isAltDown(),
InputEvent;878
isAncestorOfQ,
Container; 442
isBoldO,
Font; 649
isBoundO.
PropertyDescriptor; 1242
isConstrainedO,
PropertyDescr i ptor: 1243
i sConsumedO,
AWTEvent: 123
InputFvent:878
isConsumerQ,
FilteredlmageSource: 616
ImageProducer: 843
MemorylmageSource; 1032
isControlDown О*
InputEvent;879
i sDataFlavorSupported(),
StringSelection;1378
Transferable;1502
i sDesignTimeO,
Beans; P3
isEditableQ,
TextComponent; 1436
isEmptyO,
Rectangle:1297
isEnabledO,
Component; 350
Menuitem;1097
isErrorAnyO,
MediaTracker;1024
isErrorlDO,
MediaTracker: 1024
isExpertO,
FeatureDescriptor; 598
i sFocusT raversable(),
Component: 351
ComponentPeer; 416
i sGu i Ava i1able О,
Beans;173
isH-iddenQ,
IeatureDescri ptor; 598
isInDefaul tEventSetO,
EventSetDescriptor; 589
isInstanceOfO,
Beans;173
I
INDEX
isltalic(),
Font;649
isItemSel ectedQ,
Li st:998
isMetaDownC),
InputEvent;879
isMimeTypeEqual(),
DataFlavor; 505
isModal O,
Dialog: 514
isMultipi eMode(),
List; 999
isPaintableO,
PropertyEditor: 1258
PropertyEditorSupport:1279
isPlainO,
Font;649
i sPopupTri gger О,
MouseEvent; I 117
isResizable(),
Dialog: 515
Г rame:674
isSelectedO,
List, replaced bv i slndexSelectedO: 099
isShiftDownO*
InputEvent:879
isShowingO*
Component:353
isTearOffO,
Menu:1049
isTemporaryO,
FocusEvent:6*6
isUnicastO,
EventSetDescriptor; 589
isVal id().
Component;35 *
isVisibleQ,
Component;353
ITALIC,
Font:650
ITEM_EVENT_MASK,
AWTEvent;124
item events,
callback method,
ItemListener,i temStateChangedO; 913
Checkbox;221
checkbox.
Checkbox.processItemEventO; 228
menu item. CheekboxMenuTterr.process-
ItemEvent 0: 244
choice. Choi ce. processItemEvent (): 260
components that tire.
See Checkbox; CheckboxMenuItem; Choice.
List
Table. AWTEvent: 115
dispatching. AWTEventMu 11 icaster. i t em
StateChangedQ: 140
event id.
ItemEvent.ITEM_FIRST: 906
ItemEvent.ITFM_lAST; 906
ItemEvent.ITEM STATE-CHANGED; 907
ItemEvent:902
getltemO: 905
getltemSelectableC);906
getStateChangeO: 906
ITFM_FIRSI; 906
ItemLi stener;909
hst. Li st. processItemEvent O; 1003
lislenei.
Checkbox.addltemListenerO:224
Checkbox, removelteml istenerO; 229
CheckboxMenuItem.addltemli stenerO:
241
CheckboxMenuItem.removeitem
ListenerO; 245
Choice.addltemListenerO; 255
Choice.removeltemListenerO:262
ItemSelectab1e.addltemLi stenerO;917
ItemSelectable.removelteml i stenerO:
918
Li st. addltemLi stenerO: 990
Li st. removeltemLi stenerO; Ю07
listening for. ItemEvent: 902
mask for. AWTFvent.ITEM„EVENT_MASK; 124
Mate. ItemEvent.paramString(); 908
state chance tvpe.
ItemEvent.DFSF1 FCTED:905
TtemFvent.SELECTED:908
term definition.
AWT Event: 111
ItemEvent;902
ITEM-FIRST,
ItemEvent: 906
ITEM_LAST,
ItemEvent;906
ITEM-STATE_CHANGED,
ItemEvent;907
1622
ItemEvent;902
DESELECTED; 905
getltem(); 905
get ItemSel ectabl eO: 906
getStateChangeO; 906
ITEM „FIRST; 906
ITEM_LAST; 906
ITEM_STATE_CHANGED;907
ItemEvent0;907
paramStri ngO;908
SELECTED; 908
ItemEvent()»
ItemEvent;907
ItemListener;909
i temStateChanged();913
items,
checkbox. See checkbox
checkbox menu items, See menu items
choice. See choice
events. See item events
ItemEvent .getltemO; 905
list. See lists
menu items. See menu items
property, term definition, ItemEvent; 903
selectable,
Checkbox.getSelectedObjectsO; 226
CheckboxMenuItem.getSelected-
Obj ectsO; 242
Choice. getSelectedObjectsO;258
ItemEvent.getItemSelectableQ; 906
ItemSelectable; 914
ItemSelectable.addltemListenerO; 917
ItemSelectable.getSelectedObjectsO:
917
ItemSel ectabl e. removeltemLi stenerO;
918
L ist .getSelectedObjectsO: 998
testing. Li st. i sltemSelectedO; 998
selected, term definition. Choice; 251
state change property,
ItemEvent.getStateChangeO;906
term definition. ItemEvent; 903
ItemSelectable;914
addltemListenerO; 917
getSelectedObjectsO; 917
removeltemLi stenerO; 918
i temStateChangedQ.
AWTEventMulticaster; 140
ItemListener; 913
J
jaggies,
reducing uith. AreaAveragingScaleFi 1 ter; 101
jar command,
as Java archive tool. Applet: 76
JAR (Java Archive),
as file format tor arch nes. Applet; 76
information resource on. (URL). Applet; 76
Java,
generating source code for initialization.
PropertyEdi tor.get Javainitializa
tionStringO: I 256
PropertyEdi torSupport.getJava-
Ini tial izationStri ngO: 1278
j ava. appl et package,
description; 1
j ava. awt package,
description; 3
java.beans package,
description; 26
К
key.
Event, replaced by KeyFvent, getKeyCodeO:
559
KEY_ACTION,
Fvent. replaced by KeyEvent. KEY PRFSSED; 559
KEY_ACTION-RELEASE,
Fvent, replaced by KeyEvent. KEY-RELEASED;
560
key code,
virtual.
MenuShortcut .getKeyO: 1113
term definition. MenuShortcut; 1111
KEY_EVENT_MASK,
AWTEvent;124
key events,
action keys,
KeyEvent; 927
testing for, KeyEvent. i sActionKeyO; 941
adapter class. KeyAdapter: 919
callback methods.
KeyAdapter. keyPressedO; 924
KeyAdapter. keyReleasedO: 924
KeyAdapter. keyTypedO: 924
Keylistener.keyPressedO; 951
Keyl istener.keyReleasedO: 953
KeyLi stener.keyTypedO: 954
к
INDEX
key events (continued)
components that lire. Table. AWTFvent; 115
dispatching,
AWT EventMulti caster. keyPressedO; 141
AWTEventMul t icaster, keyReleasedO: 141
AWTEventMulti caster. keyTypedO: 142
event id,
KeyFvent.KEY-FIRST: 942
KeyEvent. KFY_L AST: 942
KeyEvent.KLY_PRFSSED; 942
KeyEvent.KEY .RELEASED; 943
KeyEvent.KEY_TYPED; 943
key characters.
KeyEvent.CHAR.UNDFFINED: 933
KeyEvent. getKeyCharO: 935
KeyEvent. setKeyCharO; 949
term definition, KeyEvent: 927
key codes.
KeyEvent:927
KeyEvent .getKeyCodeO; 9*7
KeyEvent.setKeyCodeO: 949
KeyEvent-VK„UNDEFINED: 951
printable names. Table. KeyF vent; 938
property names. Table. KeyFvent: 938
string representation,
KeyFvent.getKeyTextО;938
Table. KeyEvent: 928
KeyEvent:928
KeyListener;952
listener.
Component. addKeyLi stenerO; 321
Component.removeKeyLi stenerO: 377
mask tor. AWTEvent.KEY-EVENT_MASK; 124
modifier keys. KeyEvent. set Modi fi ersO; 950
processing. Component,processKeyEventO:
374
simulating. KeyFvent; 928
.state. KeyEvent .paramStri ng О; 948
KEY-FIRST,
KeyEvent;942
KEY_LAST,
KeyEvent:942
KEY_PRESS,
Event, replaced by KeyEvent. KEY_PRESSE D: 560
KEY-PRESSED,
KeyEvent;942
KEY-RELEASE,
Event, replaced by KeyEvent. KEY_REL EASED;
561
KEY-RELEASED,
KeyEvent:943
key sequence,
term definition. MenuShortcut: 1111
KEY_TYPED,
KeyEvent; 943
KeyAdapter;919
keyPressedO: 924
keyReleasedO: 924
keyTypedO; 924
keyboard,
action keys.
KeyEvent;927
Table. KeyEvent: 928
events. 5c<’ key events
focus, term definition, FocusEvent:631
key character, term definition. KeyEvent: 927
key cedes. KeyEvent: 927
modifier keys. See modifier keys
shortcuts.
equality testing. MenuShortcut, equal s ()
III3
ignored in popup menus, PopupMenu: 119*
listing. MenuBar. shortcutsO: 1066
MenuBar .deleteShortcutO: 1058
MenuBar.getShortcutMenuItem(): 106*
Menultem.de!eteShortcut():1092
Menu!tem.getShortcut():1096
Menuitem. setShortcutO: 1104
term definition. Menu: 1041
term definition. MenuBar: 1054
term definition. Menu Item: 1089
term definition. MenuShortcut: 1111
keyDownO,
Component, replaced by KeyListener; 354
KeyEvent; 926
CHAR_UNDEFINED: 933
getKeyCharO; 935
getKeyCodeO; 937
getKeyModi fiersText 0:938
getKeyText();938
i sActionKeyO: 941
KFY-FIRST: 942
KFY_LAST;942
KEY .PRESSED:942
KEY-RELEASED; 94*
KLY„TYPED; 94*
KeyEventO: 945
paramStri ng0:948
1624
setKeyCharQ -949 s et К e yC ode (): 949 setModi fiers():950 VK_UNDEFINED: 951 KeyEventO, KeyEvent: 945 KeyListener;952 keyPressedO: 953 keyReleasedO; 953 keyTypedO; 954 keyPressedO, AWTEventMulticaster;141 KeyAdapter; 924 KeyLi stener: 953 keyReleased(), AWTEventMulticaster; 141 KeyAdapter; 924 KeyLi stener: 953 keys, events, Ser key events keyboard. See keyboard modi Her, See modifier keys keyTypedO, AWTEventMu 1 ticaster; 142 KeyAdapter; 924 KeyLi stener; 954 keyltpO- Conponent, replaced by KeyListener: 355 Label. CENTER; 957 Label. getAl ignmentf); 957 Label. LEFT: 958 Label. RIGHT; 959 Label. setAl ignmentO: 959 label Peer. setAl ignmentO: 963 button. Button,setLabel0;198 ButtonPeer.setLabel();201 checkbox menu item. CheckboxMenuItem.get- Sel ectedObjectsO; 242 checkboxes. Checkbox.setLabel();230 CheckboxPeer.setLabel();250 event types fired by. Table. AWTEvent; 115 events. See component events L abel;955 menu, term definition. Menu; 1040 menu items. Menuitem.setLabel();1103 MenuItemPeer.setLabel();1108 term definition. Menu!tem; 1089 peers. creating. Label. addNoti fyO; 957 LabelPeer: 962 Too 1 kit.createl abel O: 1483 retrieving. Button.getLabelO: 195 Checkbox.getLabel():226
L Label:955 addNoti fy();957 GEN ILR;957 getAlignment О;957 getTextO; 95X Label():958 LEU; 958 paramStri ng();958 RIGHT;959 setAlignment 0:959 setText0; 960 Label O, Label;958 LabelPeer;962 setAl i gnmentO, 961 setlextO: 963 labels, alignment, Label:955 Checkbox.getSelectedObjectsQ: 226 Menuitem.getLabelО:1096 term definition, Label: 955 text. Label getTextO: 958 Label.setTextO; 960 Label Peer.set I ext О; 963 text color, SystemColor.controlText; 1395 last, event id, ItemEvent. ITFM_LAST; 906 Pai ntF.vent. PAINT_LAST О: 1 160 event ids, MouseEvent - MOUSE.LAST(); 11 39 lastO. CardLayout:216 lastPageFirstO, Printlob; 1214
INDEX
layout,
alignment. LayoutManager?; 97?
applet. Applet; 74
border.
BorderLayout:176
BorderLayout.addLayoutComponent О< 1
BorderLayout.CENTtR; 180
BorderLayout. EAST; 181
BorderLayout .getHgapO; 182
Border! ayout. getl ayout Al i gnmentXO:
181
BorderLayout.getLayoutAl1gnmentYO:
181
BorderLayout.getVgapO; 183
BorderLayout. i nval idateLayoutO: 184
BorderLayout.1ayoutContainerO; 184
BorderLayout .maximumlayoutSi ze(): 184
BorderLayout.minimumLayoutSizeO; 185
BorderLayout.NORTH: 185
BorderLayout.preferredLayout Si ze();
186
BorderLayout.removeLayout-
Component О;186
BorderLayout .setHgapO; 187
Border! ayout. setVgapO; 187
BorderLayout.SOUTH: 187
BorderLayout. toStri ngO: 188
BorderLayout .WEST: 188
card,
CardLayout .getHgapO; 211
CardLayout.getLayoutAlignmentXO; 212
CardLayout.getLayoutAl ignmentYO; ?l ?
CardLayout .getVgapO; 215
CardLayout. i nval i date Layout (): 216
CardLayout.1ayoutContainer0: 216
CardLayout.maximumLayoutSi zeО: 217
CardLayout.minimumLayoutSize(): 217
CardLayout. preferred! ayoutSizeO; 218
Card! ayout. remove! ayoutComponentO:
219
Card! ayout. setHgapO; 219
CardLayout.setVgapQ;219
Card! ayout.toStringO; 220
component.
Component.get LayoutAlignmentXO • 336
Component.getLayoutAl ignmentYO; *16
container.
Contai ner .getLayoutO i 440
Contai ner.get!ayoutAli gnmentXO:435
Contai ner.getLayoutAli gnmentYO: 436
Contai ner.setLayout 0:454
CridBagLayout .ArrangeGridO: 764
Layoutvanager. addLayoutCoriponentO;
969
LayoutManager, 1 ayoutContainer(); ‘<69
IayoutManager2.addLayoutComponent():
979
LayoutManager?.getLayoutAlign
mentXO; 979
IayoutManager2.getLayoutAlign-
mentYO: 980
flow
FlowLayout:618
FlowLayout.getAli gnment():622
FlowLayout.getHgapO: 622
FlowLayout.getVgapO; 624
FlowLayout.1ayoutContai ner();6'4
FlowLayout.mi nimumLayoutSi zeO:625
FlowLayout .preferredLayoutSizeO: 625
FlowLayout.removeLayoutComponent О:
6?6
Flow! ayout.setAli gnment O;626
FlowLayout. setHgapO: 626
FlowLayout.setVgapC):6?7
FlowLayout.toStri ng 0:627
toil!. Font. toStringO; 65 I
grid.
GridLayout.addLayoutComponent(); *783
GridLayout.getHgapO; 784
Gri dLayout .getRowsO: 785
Gridl ayout .getVgapO; 786
Grid! ayout.layoutcontainerО:787
Gri dLayout .mi nimumLayoutSizeO: 787
Gri dLayout.removeLayoutComponent О;
788
Gri dLayout. setHgapO; 790
Gri dLayout.setRows 0: 79!
Gri dLayout. setVgapO; 79!
grid bug.
calculating. Gr idBagLayout .Get
LayoutlnfoO: 768
GridBagLayout:759
GridBagl ayout.addLayoutComponentО;
763
GridBagLayout.getl ayoutAl ignmentXO:
767
Gri dBagLayout.get LayoutAli gnmentYO:
767
1626
GridBagLayout.get!ayoutDi mens i onsQ;
767
Gri dBagLayout.i nvalidateLayoutQ:772
GridBagLayout.layoutContainerQ:773
Gri dBagLayout.maxi mumLayoutSi zeQ:776
GridBagLayout.minimuTl ayoutSi zeQ; 777
GridBagl ayout.vi^si/E;777
GridBagl ayout. prefer redl ayoutSi zeO;
Gri dBagLayout.PRFFERREDSIZE;778
Gri dBagLayout. toStri ngQ; 78(1
term definition,. GridBagLayout; 7.59
insets, term definition. Insets: 881
invoking layout manager.
Component .doLayoutО: 33.5
Contai ner.dolayout Q;435
Scrol 1 Pane .doLayoutQ: 1350
nnmagei s.
LayoutManager;964
LayoutManager.mini mumLayoutSi zeO: 970
LayoutManager.preferredl ayoutSizeQ:
970
LayoutManager.removeLayout-
Component^: 971
LayoutManager?.invalidateLayoutQ; 980
LayoutManager?.maximumLayoutSi ze():
981
.Ser BorderLayout; CardLayout;
Component; Container; FlowLayout:
GridBagLayout; GridLayout;
I ayoutv>anager; LayoutManager?:
ScrolI Pane
term definiiion. Component: 306
layoutO,
Component, replaced by doLayoutQ: 355
Container, replaced by dol ayout0: 443
Scrol IPane. replaced by doLayoutQ; 1355
1ayoutContai ner О,
BorderLayout:184
CardLayout; 216
Fl owlayout; 624
Gri dBagLayout;773
Gri dl ayout: 787
L ayoutManager: 969
layoutinfo,
GridBagLayout;773
LayoutManager;964
addLayoutComponentQ:969
1 ayoutContai nerQ: 969
mi nimumLayoutSi zeО;970
preferredl ayoutSi zeQ: 97(>
removeL ayoutComponent():971
LayoutManager?; 972
addLayoutComponent Q;979
getLayoutAl ignmentXQ; 979
getLayoutAlignmentYQ; 980
invalidateLayout();980
maximumLayoutSi zeQ; 981
leading,
font. FontMetrics.getleadingC): 662
fonts, term definition, FontMetrics; 653
left.
alignment.
Component. LEFT..ALIGNMENT: 356
FlowLayout. L FT Г: 624
Label. LEFT; 958
value. Insets.left; 885
LEFT,
Event, replaced by KeyEvent .VK_1 EFI; 561
FlowLayout:624
1 abel;958
left.
Insets;885
LEFT-ALIGNMENT,
Component:356
1 ightGray,
Color; 29?
lightweight,
components,
as panel replacement. Panel; 1162
canvas components compared with: 202
native components compared with. Compone
308
containers, native eon tamers compared with,
Contai ner: 424
peers. 1 ightwei ghtPeer; 982
LightweightPeer;982
lines,
painting. Graphics .drawl ineQ; 702
wrapping in text areas. TextArea; 1405
List;983
add(); 988
addAct ionL i stenerQ; 989
addltemQ; 989
addltemLi stenerQ; 990
addNotifyO; 991
al lowsMul t i pl eSelect i onsQ. replaced by
i sMu 1 tipi eMode Q; 99]
INDEX
List (i ounnuetb
c lear(). replaced by removeAl 1 Q; 991
countitemsQ. replaced by
getltemCountO; 991
del ItemО;992
del ItemsQ. replaced by using multiple invoca-
tions of remove Q:992
deselect():993
getltemQ; 993
getltemCountO: 993
get I terns Q:994
getMi nimumSi zeQ; 994
getPreferredSi zeQ: 995
getRowsQ; 995
gctSelectedlndexQ; 996
getSel ectedlndexesQ; 996
getSelectedItemQ;996
getSelectedltemsQ: 997
getSel ectedObj ect sQ: 998
getvisiblelndexQ; 998
i sltemSelectedQ; 998
i sMul tipi eMode Q:999
i sSeiectedО, replaced by
i sIndexSelec ted О;999
Li st О: 999
makeVisibleQ; 1006
minimumSizeQ, replaced by
getMinimumSi zeO; 1001
paramStringO: 1002
preferredSi zeO. replaced by
getPreferredSizeO; 1002
processActionEventQ; 1002
processEventO: 1003
processItemEventO; 1003
removeО;1004
removeActionLi stenerO; 1005
removeAl1();1005
removeltemL i stenerQ; 1007
removeNotifyO; 1007
replaceltemQ: 1004
selectO; 1007
setMultipleModeQ; 1008
setMultipl eSelect ionsQ. replaced by
setMultipleModeQ: 1009
listO.
Component;356
Contai ner: 444
ListO,
Li St;999
LIST_DESELECL
Event, replaced by ItemEvent ,DLSE l ЬCT; 561
LIST-SELECT,
Event, replaced by ItemEvent. DESELECT; 562
listeners.
See Also ActionLi stener; Adjustment-
Listener
action went.
ActionLi stener; 41
Button.addActionLi stenerO; 192
adjustment event.
Adjustable.addAdjustmentLi stenerQ;
56
Adjustable.removeAdjustment-
ListenerQ; 59
AdjustmentListener: 70
Scroll bar,addAdjustmentLi stenerQ:
1326
adjustment events. Sc rol 1 -
bar. removeAdjustment ListenerQ. 1332
button. Button. removeActionLi stenerQ: 19/
callback methods, as event set component.
EventSetDescriptor;576
component events.
Component.addComponentlistenerQ; 320
Component.removeComponentli stenerQ;
376
Component! istener:408
ComponentLi stener.componentMovedO:
409
container c veins,
Contai ner.addContai nerLi stenerQ:432
Container.removeContainerl i stenerQ;
454
Contai nerLi stener:466
event, term definition. AWT Event: 111
event set,
Event SetDesc ri ptor.getAdd-
Li stenerMethodO: 585
EventSetDescri ptor.getRemove
ListenerMethodQ; 589
support method signature conventions.
EventSetDescriptor; 578
focus event.
Component .addFocusLi stenerQ: 121
Component.removeFocusLi stenerQ:377
FocusEvent:631
FocusLi stener:637
1628
//V/УГ.Л
item event.
Checkbox.addlteml istenerO: 224
Checkbox . removeltemL istenerO; 224
CheckboxMenuItem.addItemlistenerO:
241
CheckboxMenuItem.removeltem-
l istenerO: 245
Choice.addltemlistenerO;255
Choice.removeltemLi stenerO;262
Itemli stener:909
ItemSelectable. addltemLi stenerO; 917
ItemSelectable. removelteml i stenerO;
918
L i st.addlteml i stenerO; 990
L i st. removeltemLi stenerO: 1007
key event.
Component.addKeyListenerO; 321
Component. removeKeyl. istenerO; 377
KeyAdapter; 919
Key Li stener; 952
list,
L ist.addActionListener(): 9K9
1 i st. removeActionLi stenerO; 1005
menu item.
Menuitem.addActionListenerO;1091
Menuitem. removeActionListenerO; 1100
rncthcxl descriptors.
EventSetDescri ptor.getlistener-
MethodDescriptorsO; 587
methods, EventSetDescriptor,get-
ListenerMethodsO: 588
mouse event.
Component.addMouseL istenerO; .421
Component. removeMouseLi stenerO; V78
MouseEvent:1129
MouseL i stener; 1143
mouse motion event,
Component.addMouseMotionLi stenerO:
322
Component.removeMouseMotion-
ListenerO: 378
MouseMotionListener;1154
property change event.
Customi zer.addPropertyChange
Li stenerO; 498
Customizer.removePropertyChange-
ListenerO: 498
PropertyChangeListener; 1223
PropertyChangeSupport.addProperty-
ChangeLi stenerO; 1227
PropertyChangeSupport.fi re-
PropertyChangeO: 1227
PropertyChangeSupport.remove
PropertyChangeLi stenerO: 1228
PropertyEdi tor.addPropertyChange-
Li stenerO: 1255
PropertyEdi tor.removePropertyChange-
Li stenerO; 1259
PropertyEdi torSupport.addProperty
ChangeLi stenerO; 1272
PropertyEdi torSupport.fi re-
PropertyChangeO: 1272
PropertyEdi torSupport. remove-
PropertyChangeLi stenerO; 1281
text field,
FextFi eld. addAct ion Li stenerO: 1458
TextField. removeActionLi stenerO; 1465
types. FventSetDescriptor.getListener-
TypeO;588
vetoable property change events.
VetoableChangeSupport.addVetoable-
ChangeLi stenerO; 1511
VetoableChangeSupport.removeVetoable
ChangeLi stenerO: 1513
window. Window, removeWi ndowLi stenerO;
1530
window events, Window.addWi ndowLi stenerO;
1524
listening.
for property change events,
PropertyChangeEvent; 1215
listing,
keyboard shortcuts, MenuBar. shortcuts О; 1066
ListPeer; 1010
addO; 1011
addltemO, replaced by add(): 1011
cl ear O. replaced by removeAl If): 1012
delltemsO: 1012
deselect();1012
getMinimumSizeO; 1013
getPreferredSizeO: 1013
getSelectedlndexesO: 1013
makeVi sible(): 1011
minimumSize (). replaced by
getMinimumSizeO; 1014
pref er redSizeO. replaced hy
getPreferredSizeO; 1014
removeAl 1 O; 1014
selectO; 1015
L INDEX
ListPeer (continued)
setMul tipleModeO:1015
set Mui tipi eSelect ions О. replaced by
setMul tipleModeO: 1015
lists,
of component infomiation, printing.
Component.1i st();356
events,
Li st; 983
Li st .addActionLi stenerO; 989
Li st. additeml i stenerO; 990
List. processActionEventO: 1002
Li st.processtvent();1003
List. removeActionl i stenerO; 1005
List, removeltemListenerO; 1007
ГиЫе, AW 1 Event: 115
events fired by, See item events
item events. Li st. processItemEventO; 1003
items.
Li st - addO; 988
List. addltemO: 989
Ii st.deselect О; 991
Li st. getltemQ; 993
list.getltemCountO; 993
List. getltemsQ; 994
Li st. get Se I ectedlndexO: 996
I i st .getSelectedlndexesQ: 996
List .getSelectedltemO; 996
List.getSelectedIterns 0:997
I ist.getSel ectedObjectsQ; 998
List.removeО:1004
Li st.removeAl1(): 1005
List - replaceltemO: 1004
L i st. select O: 1007
Li stPeer .addO; 1011
ListPeer.delItems(): 1012
Li stPeer. deselectO: 1012
Li stPeer. getSelectedlndexesQ;1013
Li stPeer.makeVi sibleO: 1013
ListPeer.removeAl1(): 1014
Li st Peer,seiect(); 1015
testing. Li st. i sltemSel ected О; 998
testing. Li st. i s^ulti pl eMode 0: 999
List; 983
peers.
creating. List. addNoti fyQ: 991
destroying. List. removeNot i f у (); 1007
I i st Peer; 1010
Toolkit.create! istQ: 1483
rows. List. getRows (); 995
scrolling. Li st .makeVisi bleQ: 1000
selection modes.
Li st:983
List, i sMul tipleModeO: 999
Li st.setMultipleMode():1008
L i stPeer. setMul tipleModeO; 1015
size.
Li st. getMi nimumSi zeQ; 994
Li st. getPreferredSizeO; 995
Li stPeer. getMi nimumSi zeQ; 1011
Li stPeer .getPreferredSizeO: 1013
state, string representation.
Li st. paramStri ngO: 1002
term definition. Li st: 983
visibility,
L i st.getVi si bleIndex О;998
ListPeer.makeVisi bleО;1013
LOAD,
Fi leDi alog; 607
L0AD_FILE,
Event; 562
load file dialog,
Fi1 eDialog.LOAD; 607
term definition. FileDialog; 601
loadlmageO,
SimpleBeanlnfo;1373
loading,
images,
Component.imageUpdateO: 349
ImageObserver.imageUpdateO: 836
MediaTracker:1016
MediaTracker.ABORTED;1020
MediaTracker.checkAl1():1021
MediaTracker .checkIDO: 1022
MediaTracker.COMPLETE;1022
MediaTracker.ERRORED; 1023
MediaTracker. imageUpdateO; 1024
MediaTracker.LOADING; 1025
MediaTracker.waitForAllQ; 1027
MediaTracker .wai tForlDO: 1028
triggering.
Component.preparelmageО;369
ComponentPeer.preparelmageO: 4
LOADING,
MediaTracker; 1025
1oadSystemColors О*
Toolkit;1494
1630
locale,
applets. Applet . qetl ocaleQ: 85
component.
Component .getLocaleO; 340
Component. setl ocaleQ: 386
term definition. Component: 306
u indous. Wi ndow. get Local e(): 1526
locateO,
Component, replaced by getComponentAt(); 356
Container, replaced b> getComponentAtQ: 446
locationO,
Component, replaced by getLocationQ; 357
GridBagl ayout: 773
locations,
border layout,
BorderLayout:176
BorderLayout.CENTER:ISO
BorderLayout. EAST; 181
BorderLayout.NORTH: 185
BorderLayout.SOUTH: 187
Borderl ayout.WEST: 188
cell. GridBagLayout. location(): 771
component.
Component .getLocationQ: 340
Component.getl ocati onOnSc reen О; 341
pridbag, Gri dBagl ayout .getLayoutOrigi n():
768
пннье event. MouseEvent .getPoi nt(): II36
point(s), Poi nt.getLocationQ: 1180
of points. Component. conta i ns 0; 326
rectangle. Rec tangle .getLocationQ; 1294
retrieving. ComponentPeer.getLocat ionOn-
ScreenO ; 415
locks,
tree.
Component. get!reel ockQ: 346
term definiiion. Component: 307
lookupConstraintsO,
GridBagLayout:776
loopQ,
AudioClip:106
LOST_FOCUS,
Event, replaced by FocusEvent. FOCUS-IOST:
562
lostFocusQ,
Component, replaced by FocusLi stener: 357
lostOwnershipO.
Cli pboardOwner: 277
StringSelection;I37u
M
magenta.
Color.magenta: 293
magenta.
Color: 293
makeVisi ble(),
l ist:1000
Li stPeer: 11)11
map,
color. IndexColorModel . getMapSi zeQ: 850
masks,
alpha component.
Di rectColorModel .getAlphaQ: 5^1
blue component.
Di rectColorModel.getBluevask(): 532
event,
AWTEvent.ACTION„EVENT_MASK: 120
AWTEvent.ADJUSTMENT TVFNT.MASK: 120
AWTEvent.COMPONENT EVENT-MASK: 121
AWTFvent.CONIAINFR_FVENT„MASK; 122
AWTEvent.FOCUS EVENT-MASK: 123
AWIEvent.ITEM_EVENT_MASK: 124
AWTFvent.KEY EVFNT.MASK;124
AWTEvent.MOUSE_FVENT_MASK: 124
AWTEvent .MOUSE..MOTION. EVENT-MASK: 125
AWTEvent. TEXT-EVENT MASK; 126
AWTEvent.WINDOW-EVENT-MASK: 127
events, term definition. AWTEvent: 113
green component.
Di rectColorModel .getGreenMaskQ: 532
modifier keys,
Alt key, ActionEvent .ALT_MASK; 36
All key, InputEvent.ALT-MASK: 874
Control key. InputEvent .CTR1 .MASK: 876
Meta key, InputEvent. META MASK; «80
Shift key, InputEvent. SHIFT-MASK: 880
mouse buttons,
Alt key. InputEvent .BUTTON! .MASK: 875
Alt key, InputEvent.BUTTON2.MASK: 875
.Alt key, InputEvent. BUTTONS. MASK: 875
red component.
Di rectColorModel .getRedMaskQ: 533
MAXGRIDSIZE,
Gri dBagLayout: 776
maximumLayoutSizeO,
BorderLayout:184
CardLayout; 217
Gri dBaglayout: 776
IayoutManager2; 981
м
INDEX
maximum,
si/e.
Component .getMaximumSizeO: 342
Container.getMaximumSizeO: 440
MD5 message digest algorithm,
JAR support for. Applet: 76
media tracker,
event id.
Medi aTracker. checkIDO; 1022
Medi aT racker.getErrorsIDO: 1023
MediaTracker. wa i tForlDO: 1028
term definition. Medial racker; 1016
MediaTracker;1016
ABORTED; 1020
addlmageO; 1021
checkAl1O; 102i
checkIDO: 1022
COMPLETE; 1022
ERRORED; 1023
getFrrorsAnyO; 1023
gettrrorsIDO; 1023
imageUpdateO: 1024
1 sErrorAnyO: 1024
isErrorlDO; 1024
LOADING; 1025
MediaTrackerО;1025
removelmageO; 1025
statusAl1(); 1026
statuslDO; 1026
wai tForAl1(): 1027
waitForlDO; 1028
MediaTracker(),
MediaTracker; 1025
memory buffer,
image producer use.
MemorylmageSourceO; 1029
MemorylmageSource.set Ful1Buffer-
UpdatesO; 1038
MemorylmageSource:1029
addConsumerO; 1032
i sConsumerO: 1032
MemorylmageSourceO; 1033
newPi xel sO: 1033
removeConsumerO: 1033
requestTopDownLeftRightResendO;1035
setAnimatedO: 1035
setFullBufferupdates 0:1038
startProduction();1038
MemorylmageSourceO.
MemorylmageSource:1033
Menu: 1040
addO: 1044
addNotifyO; 1045
addSeparatorO: 1046
countltems(). replaced b\ getltemCountO;
1046
getltemO: 1047
getltemCountO; 1047
insertO; 1047
insertSeparator();1049
isIearOffO: 1049
Menu О: Ю5О
paramStri ngO: 1051
remove О: J 1)5 J
removeAl1 ();1052
removeNotifyO: 1053
MenuC),
Menu; 1050
menu,
SystemColor: 1397
menu hars,
adding menu*». MenuBarPeer,addMenuO; 1068
adding menus to. MenuBar.add(): 1057
ftame.
F rame. remove (); 676
Frame. setMenuBarO; 679
FramePeer. setMenuBarO; 684
frames. Frame.getMenuBar(); 673
Help menu,
MenuBar .getHei pMenuO: 1061
MenuBar.setHelpMenu();1065
term definition. MenuBar: 1054
keyboard shortcuts.
listing. MenuBar. shortcutsO: 1066
MenuBar .deleteShortcutO: 1058
MenuBar.getShortcutMenuItemO; 1063
term definition. MenuBar; 1054
MenuBar;1054
peers,
creating, MenuBar. addNotify(); 1058
destroying. MenuBar. removeNotifyO: 1065
MenuBarPeer;1067
Toolkit. createMenuBarO: 1484
removing menus.
MenuBar.remove():1064
MenuBarPeer .delMenuO: 1068
1632
retrieving,
count ot menus, MenuBar. getMenuCount О:
1062
menus. MenuBar .getMenuO: 1061
term definition. MenuBar; 1054
menu components,
component hierarchy compared with,
MenuComponent:1069
events.
MenuComponent;1069
MenuComponent.dispatchEventO; 1072
MenuComponent.processEventO; 1077
fonts,
MenuComponent .getFontO: 1074
MenuComponent.setFontО:1078
name.
MenuComponent;1070
MenuComponent .getNameO; 1074
MenuComponent. setNameO: 1079
parent, MenuComponent .get Parent 0: 1076
peers,
dost roving,
MenuComponent.removeNotifyO;1077
MenuComponentPeer.disposeO: 1081
MenuComponentPeer; 1080
removing, MenuContai ner. remove(): 1087
menu item,
state. Menuitem.paramStringO; 1098
menu items,
action events.
MenuTtem.addActionl i stenerO; 1091
Menuitem. getActionCommandO; 1096
Menuitem. processActionEventO; 1098
Menuitem.removeActionListenerO; 1100
Menuitem. setAct ionCommandO: 1100
adding to menu. MenuPeer. addltemO; 1110
appending, Menu, add О; 1044
checkbox.
CheckboxMenuItem; 239
CheckboxMenuItem.getSelected-
ObjectsO; 242
CheckboxMenuItem.paramString(); 243
CheckboxMenuItem.processItemEvent();
244
CheckboxMenuItem.setStateO; 245
CheckboxMenuItemPeer.setStateO: 248
peers, creating,
CheckboxMenuItem. addNot i fуО; 242
state. CheckboxMenuItem,getStateO: 243
checked. CheckboxMenuItem.processEventO:
243
disabling.
Menuitem. setEnabledO; 1102
MenuItemPeer. setEnabledO; 1108
disabling events. Menuitem.disableEventsO:
1093
enabled, testing. Menuitem.isEnabledO; 1097
enabling.
Menuitem.setEnabledO; 1102
MenuItemPeer. setEnabledO: 1108
enabling events. Menuitem.enableEventsO;
1095
event types fired by, 'table. AWTEvent: 115
events. Menuitem.processEventO; 1099
inserting. Menu. i nsert О; 1047
keyboard shortcuts.
listing. MenuBar. shortcuts О; 1066
MenuBar.deleteShortcutО:1058
MenuBar.getShortcutMenuItemO: 1063
Menuitem.deleteShortcutО;1092
Menuitem.getShortcutО: 1096
Menuitem.setshortcut О;1104
term definition. Menuitem: 1089
labels.
Menuitem.getLabel(): 1096
Menuitem.setLabel():1103
MenuItemPeer.setLabelO;1108
Menu. getltemCountO; 1047
Menuitem; 1088
peers.
creating, MenuTtem. addNotifyO: 1092
MenuItemPeer: 1107
Toolkit. createMenuItemO; 1485
removing,
Menu.removeО;1051
Menu.removeAl1 О;1052
removing from menu. MenuPeer. del Item(); 1110
retrieving.
count of. Menu.getltemCountO: 1047
Menu.getltemO; 1047
separator, MenuPeer. addSeparator(): 1110
separators.
Menu.addSeparator(); 1046
Menu.insertSeparatorО;1049
term definition. Menuitem: 1088
м
INDEX
MenuBar;1054
addO: 1057
addNotifyO: 1058
countMenusO. replaced b\ getMenuCountO:
1058
deleteShortcutO; 1058
getHei pMenuO: 1061
getMenu();1061
getMenuCountO: 1062
getShortcutMenuItem();1063
MenuBarO: 1064
removeО;1064
removeNotifyO; 1065
setHel pMenuO: 1065
shortcutsO: 1066
MenuBar (),
MenuBar; 1064
MenuBarPeer:1067
addHel pMenuO: 1068
addMenuO; 1068
delMenu():1068
MenuComponent:1069
di spatchEvent O:1072
getFontO: 1074
getNameO; 1074
getParent():1076
getPeer(): 1076
paramStringO: 1076
postEventO- replaced by
MenuComponent. di spatchEventO; 1077
processEventO: 1077
removeNotifyO: 1077
set Font О: 1078
setNameO: 1079
toStringO; 1079
MenuComponentPeer; 1080
disposeO: 1081
MenuContainer:1082
getFontO; 1086
postEventO. replaced by
MenuComponent.di spatchEventO; 1086
remove 0: 1087
Menuitem;1088
addActionListenerO:1091
addNotifyO; 1092
del eteShortcutO; 1092
disable(). replaced by setFnabledO: 1093
disableEvents();1093
enableQ. replaced by setEnabledO: 1095
enab 1eFvents 0: 1095
getActionCommandO: 1096
getLabel(): 1096
getShortcutO: 1096
isFnabledO; 1097
MenuItemO; 1097
paramStringO; 1098
processActionFventО:1098
processEvent 0: 1099
rerroveActi onLi stenerO; 1100
setActionCommandO: 1100
setl nabledO: 1102
settabel(): 1103
setShortcutО:1104
MenuItemO.
Menu Item; <097
MenuItemPeer;1107
di sable(). replaced by setEnabledO: II08
enable(). replaced by setEnabledO: 1108
setEnabledO: 1108*
setLabel0:1108
MenuPeer:1109
addltemO. 1110
addSeparatorO;1110
delltemO. 1110
menus.
Sec Aho bullous: containers; linines: text; window
adding. MenuBarPeer.addMenuO: 1068
adding menu items from. MenuPeer.addltem();
1110
adding to menu burs. MenuBar. addO; 1057
background color. SystemColor.menu; 1397
bars. menu bars;
components. .See menu components:
containers.
classes which аге. Arc Frame; Menu; MenuBar
MenuContainer: 1082
fonts. Menut ontainer,getFontO; 1086
Help.
MenuBar. getHei pMenuO: 1061
MenuBar. setHelpMenuO; 1065
MenuBarPeer. addMenuO: 1068
term definition. MenuBar; 1054
items, .Sec menu items;
keyboard shortcuts.
equality testing.
MenuShortcut. equal sO: 1113
term definition. Menu; 104!
labels, icon definition, Menu; 1040
1634
Menu:1040
peers.
creating. Menu. addNotifyO: 1045
destroying. Menu. removeNotifyO; 1053
MenuPeer: 1109
Toolkit. createMenuO: 14S4
popup.
Component.add(): 319
Component.remove(); 376
peers, creating. PopupMenu. addNoti fyO;
1196
term definition. Component: 307
properties, term definition. Menu; 1040
removing, MenuBar.removeО; 1064
removing menu items from.
MenuPeer .delltemO; 1110
retrieving, MenuBar .getMenu0: 1061
shortcut.
string representation,
MenuShortcut. paramStri ng(): 1115
MenuShortcut. toStri ngO: 1115
testing for Shift key requirement. MenuShort-
cut. usesShiftModi fi er(): 1115
shortcuts.
term definition. MenuShortcut; 1111
Tool ki t.getMenuShortcutKeyMaskO: 1491
tear-off.
term definition. Menu: 1040
testing for. Menu, i sTearOff (): 1049
term definition. Menu; 1040
test color. SystemColor .menuText: 1398
MenuShortcut: 1111
equals(); 1113
getKeyO; 1113
MenuShortcutO: 1113
paramStri ng();1115
toStringO, 1115
usesShiftModifier();1115
MenuShortcutO,
MenuShortcut;1113
menuText,
SystemColor:1398
message,
status.
Applet.showStatusf): 90
AppletContext.showStatus(); 97
message digest algorithm,
term definition. Applet; 76
Meta key,
InputEvent.MF1A_MASK;880
testing, InputEvent. isMetaDownO: 879
META-MASK,
Fvent. replaced by InputEvent .META_MASK: 563
ActionEvent;38
InputEvent;880
metaDownf),
Fvent. replaced by InputEvent. isMetaDownO:
563
method descriptors,
See Also event sets, descriptor: introspection
explicit, term definition. MethodDescri ptor: 1116
implicit, term definition, MethodDescri ptor: 1116
listener. EventSetDescriptor.getl.istener-
MethodDescriptorsO: 587
Method object. MethodDescriptor. get
MethodO; 1119
MethodDescriptor; J116
parameter descriptors. MethodDescri ptor,get -
ParameterDescriptorsO: 1119
term definition. MethodDescri ptor: 1116
MethodDescriptor: 1116
getMethodO: 1119
getParameterDescriptorsQ: Ш9
MethodDescri ptorO: 1119
MethodDescri ptorQ*
MethodDescriptor:1119
methods,
bean-info.
Beaninfo.getMethodDescri ptors(): 165
SimpleBeanlnfo.getMethodDescrip
tors():1372
callback.
ActionLi stener.act ionPerformed(): 43
AdjustmentL istener.adjustmentVal-
ueChangedO: 73
Cl ipboardOwner. lostOwnershipO: 277
ComponentAdapter.componentHi dden О:
399
ComponentAdapter.componentMoved О;399
Component Adapt er .component Res i zedO;
.399
ComponentAdapter.componentShown 0:
ComponentL i stener.componentHi ddenО:
409
ComponentLi stener.componentMovedO:
409
LXDFX
methods fcoiifinneih
callback.
ComponentLi stener.component-
Resi zed(): 410
Component! i stener.componentShown О:
410
ComponentPeer. handleFvent О: 416
ContainerAdapter.componentAddedC): 459
Contai nerAdapter,componentRemovedO:
459
Contai nerLi stener.componentAddedC):
467
Containerl istener.component-
RemovedO: 467
FocusAdapter.focusGai nedО: 6V)
FocusAdapter. focusLostO: 610
FocusLi stener. focusGai nedO; 638
Focusl i stener.focusl ost(): 638
ItemLi stener.itemStateChanged(): 913
KeyAdapter.keyPressedO: 924
KeyAdapter. keyReleasedO: 924
KeyAdapter. keyTypedO; 924
Keyl i stener. keyPressedO: 953
KeyLi stener. keyRe 1 easedO: 953
KeyListener. keyTypedO: 954
MouseAdapter.moused ickedO: 1123
MouseAdapter.mouseEntered О: 1123
MouseAdapter .mouseExi tedO: 1124
MouseAdapter.mousePressedO:1124
MouseAdapter.mouseRe1 easedQ: 1128
MouseLi stener.moused icked(): 1147
MouseListener.mouseEntered(): 1147
MouseLi stener.mousetx i ted(): 1148
MouseLi stener.mousePressedO: 1148
MouseListener.mouseReleasedO: 1148
MouseMotionAdapter.mouseDraggedО:
1153
MouseMot ionAdapt er. mouseMovedO: 1 153
MouseMotionl istener .mouseDraggedO:
1156
MouseMotionl istener.mouseMovedO: 115 7
PropertyChangeLi s~
tener.propertyChangeC): 1224
StringSelection.lostOwnership(): 137ч
Textl istener. textVa 1 ueChangedO: 1474
VetoableChangeLi stener.vetoable
ChangeC):1508
Wi ndowAdapter.wi ndowAct i vatedO:1536
Wi n dowAdap t e r.wi ndowC.Ioscd(): 1536
Wi ndowAdapter,wi ndowClosi ng0: 1516
Wi ndowAdapter.wi ndowDeact ivatedO:
1537
WindowAdapter.wi ndowDei coni fi ed().
1537
Wi ndowAdapter.wi ndowlconi fi ed(): I sxg
WindowAdapter.windowOpenedO: 038
Wi ndowLi stener .wi ndowActi vatedO: 155'
Windowl istener.windowC 1 osedO: 155’
WindowLi stoner.windowClosi ng(): 155?
Wi ndowL i stener.wi ndowDeac t i vatec():
1552
Wi ndowLi stener.wi ndowDeiconi fi ed():
1552
WindowL istener.windowlconi t ied():155.
Wi ndowLi stener.wi ndowOpenedO:1554
metrics,
font. See tonus к metrics
MIME content tjpe,
dal;i fla\ or use. DataFl avor. 500
equahty. testing for.
DataFlavor.i sMimeTypeEquaI 0: 505
пот mali/ing.
DataFlavor.normal izeMimeTypeO: 506
DataFlavor.normali zeMimeTypeParare
ter O: 506
retriesing. DataFlavor .getMimeTypeO; 505
{L Rl. specification). DataFlavor: 500
minimumLayoutSize(),
BorderLayout: 185
Cardl ayout: 217
FlowLayout: 625
Gri dBagLayout:777
GridLayout:787
1 ayoutMarager:970
minimumSizeO,
Component, replaced h\ getMinimumSizeO: 15h
ComponentPeer. replaced by
getMi nimumSi ze():416
Contai ner. replaced by getMi ni mumSi zeO: 446
List, replaced by getMinimumSizeO: 1001
List Peer, replaced by getMinimumSizeO: 101 1
TextArea. replaced by getMinimumSizeO: 1415
I ext AreaPeer. replaced by getvi nimumSizeO
1425
lext Fi eld. replaced by getMinirruriSi ze();
1462
Text rieldPeer. replaced by
getMinimumSizeO: 1469
1636
MINSIZE.
GridBagl ayout: 777
modal dialog,
term definition. Dialog: 509
modal property,
dialog. Dialog. setModal 0:516
mode,
file dialog,
Fi leDialog.getModeO: 607
Fi TeDialog.setModeO: 609
file dialogs,
FileDialog;601
term definition, Fi 1 eDi alog; 601
paint,
Graphics;686
Graphics, set Pai ntModeO: 733
Graphics. setXORModeO: 733
model,
color.
convened, RGBImageTiIter.newmode1; 1318
IndexColorModel .getRGBO: 851
dialog, testing for. Dialog.i sModa 10:514
models.
color,
ColorModel:295
ColorModel . getRGBdefaultO; 301
Component.getColorModelО; 337
ComponentPeer.getColorModel0:414
converting pixel values to.
ColorModel.getRGBO; 301
default, term definition. ColorModel; 296
direct, term definition. ColorModel; 296
Di rectColorModel;527
ImageConsumer.setColorModelO;817
ImageFi1 ter.setColorMode1 0: 828
IndexColorvodel: 845
indexed, term definition. ColorModel; 295
original, RGBImageFi 1 ter.origmodel: 1319
PixelGrabber.getColorModelQ; 1170
PixelGrabber.setColorModel(); 1175
replacing, RGBImageFi 1 ter. subst itute
ColorModelО;1320
RGBImageFi1 ter.setColorModel();1319
Toolkit.getColorModel();1487
component. Ser beans
event, AWTEvent; 110
modifier keys.
action events,
ActionEvent.getModifiers();37
ActionEvent:32
A It key.
InputEvent. AL Г .MASK: 874
modifier mask. ActionEvent .ALT .MASK: 36
testing. InputEvent. i sAltDownf): 87x
Control key.
InputEvent.C TRI. MASK: 876
InputEvent. isControlDownO: 879
modifier mask.Act ion Event. CTRL_MASK: 3h
effect on mouse buttons. MouseEvent; 1131
input events. InputEvent; 872
key events. KeyEvent.setModif iers(): 950
Meta key.
InputEvent, i sMetaDownQ: 879
InputEvent.META .MASK: 8K0
modifier mask. Act ionFvent ,META_MASK: 18
retrieving state of.
Acti onEvent.getMod i fi ers():37
Shift key.
InputFvent. i sShi ftDownO: 879
InputEvent.SHIFT-MASK:880
modifier maskActionEvent. SHIFT MASK: 39
state, retrieving.
InputEvent. getModi fiersO: 876
string representation.
KeyEvent.getKeyModi fiersText ():938
modifiers,
Event, replaced by
InputEvent.getModifi ersO; 563
mouse.
adapter, term definition. Mo us eAda pt er; 1121
buttons. MouseEvent: 1131
callback methods.
Mousel istener .nouseCI ickedQ: 1147
MouseListener.mouse£ntered(): 1147
MouseLi stener.mouseExi ted():1148
Mouse! istener.mousePressedf); 1148
MouseLi stener. mouseReleasedO: 1148
coordinates. MouseEvent: 1132
listener, MouseLi stener; 1143
motion,
callback methods,
MouseMot ionAdapter.mouseDraggedO;
1151
MouseMoti onAdapter.mouseMoved ();
1153
MouseMotionLi stener .mouseDraggedO
: 1156
MouseMotionLi stener.mouseMovedO;
1157
м
INDEX
mouse tcanriiiHctb
motion,
events.
MouseMotionAdapter: 1149
MouseMotionListener:1154
MOUSE-CLICKED,
MouseFvent: 1137
MOUSE—DOWN,
Event, replaced by
MouseFvent.MOUSE PRESSED:563
MOUSE-DRAG,
Event, replaced by
MouseEvent.MOUSE-DRAGGED: 564
MOUSE-DRAGGED,
MouseEvent:1138
MOUSE-ENTER,
Event, replaced by
MouseEvent.MOUSE_ENTERFD;564
MOUSE-ENTERED,
MouseEvent; I I 38
MOUSE_EVENT_MASK,
AWTEvent: 124
mouse events,
adapter class, MouseAdapter: 1121
button press.
MouseAdapter.mousePressedO: 11 24
MouseEvent.MOUSE-PRESSED: 1140
button release,
MouseAdapter.mouseReleased 0:1128
MouseEvent.MOUSF.RH EASED: 1140
clicks,
count. MouseEvent. getCl i ckCount Q: 1136
count, term definition MouseEvent; 1132
MouseAdapter .moused i ckedO: 11 23
MouseEvent.MOUSE CLICKED: 1137
components that fire. Table, AWTEvent; 115
coordinates. MouseEvent .trans latePoint();
1142
dispatching,
AWTEventMu1ti caster.mouseC1i ckedO:
142
AWTEventMulti caster.mouseDraggedO:
143
AWTEventMulti caster.mouseEntered():
143
AWTEventMulti caster.mouseExitedO: 144
AWT EventMuIti caster.mouseMovedO:144
AWTEventMult i caster.mousePressedO;
144
AWTFventMult i caster.mouseReleasedO:
145
event id.
MouseEvent.MOUSE CLICKED; 1137
MouseEvent.MOUSE DRAGGED: 1138
MouseEvent.MOUSE-ENTERED; 1138
MouseEvent.MOUSF-FXTTFD:1139
MouseFvent.MOUSF_FIRST: 1139
MouseEvent.MOUSE_LAST: 1139
MouseEvent.MOUSE-MOVED:1140
MouseEvent.MOUSE PRESSED:1140
MouseEvent.MOUSE RELEASED: 1140
flow. MouseEvent: 1130
guaranteed sequences. MouseEvent: 1132
listener.
Component.addMouseListenerO: 321
Component.removeMouseListener0: 378
location. MouseEvent- getPoi nt О: 1136
mask for. AWTEvent.MOUSF-FVFNT-MASK: 124
modifier key encoding. InputEvent: 872
mouse button modifier mask.
Alt key. InputEvent . BUTT0N1 MASK; 875
Ah key. InputEvent. BUT T0N2 MASK: 875
A It key. Input Event. BUTT0N3_MASK; 875
movement.
MouseAdapter.mouseFnteredO: 1123
MouseAdapter.mouseExited(): 1124
MouseEvent.MOUSE-DRAGGED; 11 *8
MouseFvent.MOUSF-FNTFRFD; 1138
MouseEvent.MOUSE-EXITED: 1139
MouseEvent.MOUSE_MOVED: 1140
popup trigger property. MouseEvent: 1132
processing. Component. processMouseFvent():
375
simulating. MouseEvent: 11 30
state. MouseEvent. paramStrinqC): 1142
г-coordinate. MouseFvent . getXQ; 1136
v coordinate. MouseEvent.getY(): 1137
MOUSE-EXIT,
Event, replaced by MouseEvent .MOUSE-EXITED:
564
MOUSE-EXITED,
MouseEvent:1139
MOUSE-FIRST,
MouseEvent: 1139
MOUSE-LAST,
MouseEvent: 1139
MOUSE_MOTION_EVENT-MASK,
AWTEvent: 125
1638
mouse motion events,
adapter class. MouseMot ionAdapter; 1149
listener.
Component.addMouseMotionListenerO;
322
Component >removeMouseMotion-
ListenerO: 378
mask for,
AWTEvent,MOUSE-MOriON_FVFNT_MASK: 125
processing. Component. processMouse-
MotionEventО:375
MOUSE-MOVE,
Event, replaced by MouseEvent .MOUSE-MOVED;
564
MOUSE-MOVED,
MouseEvent;1140
MOUSE-PRESSED,
MouseFvent;1140
MOUSE-RELEASED,
MouseEvent; 1140
MOUSE_UP,
tvent. replaced by
MouseEvent.MOUSE-RELEASED; 565
MouseAdapter: 1121
moused ieked(); 1123
mouseEnteredO; 1123
mouseExited(): 1124
mousePressedQ; 1124
mouseReleasedO: 1128
moused ieked О,
AWTEventMul t i caster; 142
MouseAdapter: 1123
MouseLi stener; 1147
mouseDownО,
Component, replaced by MouseLi stener; 358
mowseDragО,
Component, replaced by
MouseMotionListener;359
той seDragged(),
AWTEventMulticaster: 143
MouseMotionAdapter;1153
MouseMotionListener;1156
mouseEnterO,
Component, replaced by MouseListener; 361
mouseEnteredO,
AWTEventMulticaster;143
MouseAdapter; 1123
MouseLi stener; 1147
MouseEvent;1129
getClickCountO: 1136
getPointO; 1136
getXO; I 136
getYO; 1137
isPopupTriggerО;1137
MOUSE-CLICKED;1137
MOUSE-DRAGGED:1138
MOUSE-ENTERED;II38
MOUSE_EXITFD:1139
MOUSE-FIRST: 1139
MOUSE-LAST; 1139
MOUSE-MOVED; 1140
MOUSE_PRFSSED; 1140
MOUSF-RFLEASED: 1140
MouseEvent(); 1141
paramStringO: 1142
translatePointO: 1142
MouseEvent(),
MouseEvent:1141
mouseExit(),
Component, replaced by MouseLi stener; 361
mouseExi tedQ,
AWTEventMu1ticaster:144
MouseAdapter: 1124
MouseL istener; 1148
MouseListener:1143
mouseCli ckedO; 1147
mouseEnteredO: 1147
mouseExi ted():1148
mousePressed():1148
mouseReleasedO; 1148
MouseMotionAdapter;1149
mouseDraggedO; 1153
mouseMovedO;1153
MouseMotionListener; 1154
mouseDraggedO; 1156
mouseMovedO: 1157
mouseMoveO,
Component, replaced by
MouseMotionListener; 162
mouseMovedO,
AWTEventMuIticaster; 144
MouseMotionAdapter: 1153
MouseMotionListener; И57
mousePressedO,
AWTEventMulticaster; 144
MouseAdapter; 1124
MouseLi stener; 1148
INDEX
mouseReleased(),
AWTEventMulticaster:I45
MouseAdapter:1128
Mousel istener; 1148
mouseUpO,
Component, replaced by MouseLi stener: 362
move О,
Component, replaced by set Locat ionQ; 363
Poi nt. replaced by set Loc at ionQ: 1181
Rectangl e. replaced by setLocationQ: 1297
MOVE-CURSOR,
I-rame. replaced by Cursor.MOVE CURSOR; 674
Cursor; 483
moving,
components.
Component. setBoundsQ; 384
Component.set! ocationQ;386
ComponentAdapter.componentMoved О - 399
ComponentEvent.COMPONENT-MOVED;405
Component Li stener.componentMovedQ:
409
ComponentPeer.setBoundsQ;419
cursors. Cursor.MOVF_CURSOR; 483
locus, to focus traversable component.
Component.transferFocusQ; 391
origin. Graphi cs . trans lateQ; 735
points. Poi nt. set Local ionQ; I 182
reel angles.
Rectangl e. setBoundsQ: 1299
Rectangle. setLocationQ: 1300
Rectangl e. toSt ringQ; 1301
multicasting,
AWTEventMulticaster: 128
creating a multicaster.
AWILventMul ticaster. addQ; 134
AWTEventMul ticaster.addinternal (): 135
event set signature pattern. Introspector: 892
event seis, term definition.
FventSetDescriptor: 578
term definition. AWTEventMulticaster: 128
writing multicaster. to output stream.
AWTEventMult i caster.save Internal();
148
N
N_RESIZE_CURSOR.
Frame, replaced by
Cursor.N RESIZE-CURSOR:674
Cursor: 483
name,
action events, retrieving.
Menuitem .getActi onCommandQ; 1096
bean, as bean descriptor attribute. Table\ 155
changed property, PropertyChange-
Event .getPropertyName();1220
component.
CardLayout.addLayoutComponentQ: 211
Component.getNameO: 343
Component. setNameO: 387
term definition. Component: 105
display, as bean descriptor attribute. Table: 155
feature.
FeatureDescri ptor. getDi splayNameQ,
596
FeatureDescriptor.getNameO:596
feature descriptor aliributes.
FeatureDescriptor.attri buteNamesQ:
596
feature descriptors. FeatureDescrip-
tor. set Name Q: 599
features.
FeatureDescriptor. setDi spl ayNameQ:
598
FeatureDescriptor. setNameO: 599
font. Font .getNameO: 646
font family. Font. getFami 1 yO: 645
human presentable.
DataFl avor.get HumanPresentable-
NameQ: 504
DataFlavor.setHumanPresentable
NameО:507
term definition. DataFlavor: 501
key codes. Table. KeyEvent; 938
logical.
as font property. Font: 639
Font .getFontO: 646
Font.name;650
menu com pone nts.
MenuComponent.getNameO:1074
MenuComponent.setNameO:1079
MenuComponent:1070
properly.
Fi 1 eDialog.getFilenameFi1 terQ: 607
1640
FileDialog.setl ilenareFi1ter().609
F ileDialogPeer.set I ilenameFi1ter():
612
PropertyChangeEvent.I?17
name,
Font:650
native,
components
color. SystemColor; 13X1
lightweight components compared with.
Component: 308
term definition. Component: 31)8
container. Tool ki t . getNati veContai ner():
1491
containers, lightweight containers compared with.
Container; 424
NE_RESIZE_CURSOR,
Frame, replaced by
Cursor.NL RFSIZE .CURSOR; 675
Cursor; 4X4
needsCui O,
Vi si bi 1 i ty: 1517
newlines,
TextArea;1406
newmodel,
RGBImageFi 1 ter; 131X
newPixelsO.
v.enorylmageSourte: КНЗ
next(),
Cardl ayout; 217
nextFocusO,
Component, replaced by t ransferFocusO; 363
no-ops.
Fl owlayout.addLayoutComponent();621
FlowLayout .removeLayoutComponent(): 626
GridBaglayout.removeLayoutComponent():
77X
ScrolIPane.setLayout():1359
NONE.
GridBagConstraints;753
normal inode.
graphics context. Graphics: 6X6
normal izeMimeTypeO,
Dat aFlavor; 506
normalizeMimeTypeParameterO,
DataFlavor; 506
normalizing,
MIME tvpe.
DataFl avor, normal i zeMimelypeO 506
DataFlavor.normali zeMimeType-
Parameter():506
north,
resizing cursor. Cursor,N RESIZE-CURSOR; 48"
NORTH,
BorderLayout:1X5
Gri dBagConst raints;753
northeast.
resizing cursor. Cursor.NE-REST7E-CURS0R: 4X4
NORTHEAST,
GridBagConstrai nts:753
northwest,
resizing cursor. Cursor. NW_RESIZE_CLRSOR: 484
NORTHWEST.
GridBagConstraints: 753
notification.
change. Adjustment-
Event. ADJUSTMENT.VALuL CHANGED;66
event,
AWTEvent; 112
AWTEventMulticaster;128
npoints,
Polygon;1189
NW-RESIZEJ2URS0R,
F rame. replaced by
Cursor,NW_RESIZF_CURSOR; 675
Cursor; 4X4
О
observers.
ImageObserver; 831
loading images.
ImageObserver.imageUpdateO:836
status flags.
ImageObserver.ABORT; X34
ImageObserver.ALLBTTS:834
ImageObserver.ERROR: 834
ImageObserver. FRAMFBHS; 835
ImageObserver.HEIGHT: 835
ImageObserver.PROPERTIES:837
ImageObserver.SO^EBI1S:837
ImageObserver.WIDTH; 837
term definitinn. Image; 795
okTollseGui (),
Visibility:1517
р
INDEX
orange,
Color.orange: 293
orange.
Color: 293
orientation,
of adj ust able coni ponents.
Adjustable.getOrientationO: 57
Adjustable.HORIZONFAL: 59
Adjustable.VERTICAL:61
scrollbar.
retrieving. Scrol 1 bar.getOrientation():
1328
retrieving. Scrol 1 bar.HORIZONTAL: 1330
ScrolIbar.VERTICAL:1340
scrollbars. Sc rol 1 bar. setOri entati on (): 1337
origin,
graphics context. Graphics: 686
popup menu, term definition. PopupMenu; 1192
origmodel,
RGBImageFilter; 1319
outline,
3 I). Graphics .draw3DRect(): 695
3D.
painting filled rectangle with,
Graphics.fi 1 1 3DRectO: 714
SystemColor:1382
SystemColor,controlDkShadow:1394
SystemColor.controlHighlight:1394
Sys t emCo1 or.cont го 1LtHi ghli ght: 1394
SystemColor.cont rolShadow: 1394
circle. Graphi cs.drawOval (): 704
in al. Graph ics. drawOval (); 704
rectangle. Graphi cs .drawRectO: 708
rounded rectangle. Graphics .drawRoundRect О•
710
outpixbuf,
ReplicateScaleFilter:1305
output,
streams.
writing multicaster to.
AWI EventMul t i caster. saveO:147
AWTEventMulti caster.save-
InternalO: 148
ovals,
filled, painting. Graphi cs . fi 1 lOval (): 717
outline. Graphics .drawOval O; 704
owner.
Clipboard; 275
p
pack().
Window: 1528
packages.
java.applet, description: I
java.awt. description: *
java.beans. description: 26
padding,
internal.
as gridbag constraint, term definition.
GridBagConstraints: 738
height. GridBagConstraints. ipady; 752
width. GridBagConstraints. ipadx: 751
page,
dimensions. Pri nt Job, get PageDi mensi on О;
1214
HTML. Appl etContext. showDocument (): 96
resolution, Pri nt Job. get PageResol utionQ:
1214
paintO,
Canvas; 206
Component;363
ComponentPeer:417
Contai ner: 447
PAINT,
Pai nt Fvont: 1159
paint events,
event id.
Pai ntEvent. PAINTO: И59
PaintFvent .UPDATEO; H6l
Pai ntEvent: 1158
state. PaintEvent-paramString(): 116]
update area.
Paintlvent.getUpdateRect():1159
Pai ntEvent.setUpdateRect О: 1161
PAINT-FIRST,
Pai ntEvent: 1160
PAINT_LAST,
Pai ntEvent; 1160
paint modes,
graphics context. Graphics: 686
setting.
Graphics, set Pai ntModeO: 733
Graphics.setXORModeO: 733
paintahle area,
propertv editor. PropertyEdi tor: 1251
paintAll(),
Component:364
1642
pa i ntComponent sО*
Container; 450
PaintEvent: 1158
getUpdateRectO: 1154
PAINT; 1159
PAINT.FIRST; 1160
PAINI.LAST; 1160
Pai ntEvent ():1160
paramStringO: 1161
setUpdateRectО:1161
UPDATE; 1161
PaintEventO,
Pai ntEvent: 1160
painting.
3 D outline. Graphics.drawBDRectО: 695
applet.
Also components
Applet: 74
byte arrays, as characters,
Graphics .drawBytesO; 699
canvases. Canvas - pai nt(); 206
characters.
Graphics.drawBytesO: 699
Graphi cs.drawCharsО;699
components.
Component.paintО; 363
Component.paintAl1O:364
Component.repaint 0: 379
Component.updateO; 391
ComponentPeer.pai nt 0:417
ComponentPeer.repai nt():418
container components, on graphics context.
Container, pai ntComponentsO; 450
containers. Contai ner. pai nt O; 447
filled figures.
Graphi cs.fi113DRect(); 714
Graphic s.fillArcO: 715
Graphics.fi1lOvalО;717
Graphics, fill Pol ygon О; 718
Graphics . fillRectO. 720
Graphics . filIRoundRectO; 721
images. Graphi cs. drawImageО: 700
lines. Graphics.drawLine(): 702
outline figures,
Graphics.clearRectО: 689
Graphics .drawArcO; 697
Graphics.drawOvalO; 704
Graphi cs.drawPolygon O:705
Graphi cs.drawPolyli ne О;707
Graphics.drawRectO: 708
Graphics.drawRoundRect(); 710
properties.
PropertyEdi tor.pai ntValue(); 1258
PropertyEdi torSupport.pai ntValue()
1280
strings. Graphics.drawStringO; 712
term definition. Component: 308
updating compared with. Component; 308
paintValueQ*
PropertyEditor:1258
PropertyEditorSupport:1280
panel,
term description. Panel: 116?
Panel;1162
addNoti fyO: 1164
Panel O: 1164
Panel Q,
Panel;1164
panel events,
Sec component exents
Panel Peer; 1165
panels,
event type< iked by. Table, AWTEvent; 115
peers,
creating. Panel. addNotifyO; П64
Panel Peer: 1165
Tool kit.createPanel О;1485
parameter descriptor,
See AL\(f feature descriptor
term definition. ParameterDescri ptor: 1166
ParameterDescriptor; 1166
parameters,
applet.
Applet: 77
Applet.getParameterO: 86
Appletstub.getParaneterO;100
applets. Applet. qetParameterlnfoO: 86
parameter descriptors,
method descriptor ret lie val of.
MethodDescri ptor.getParameter-
Descriptors(); H 19
paramStringO.
Event, replaced by
AWTEvent.paramStringO: 565
ActionEvent:38
AdjustmentEvent; 68
AWTEvent; 125
Button: 195
р
IX DEX
paramStringO leoHihiueih
Checkbox: 227
CheckboxMenuItem:243
Choice: 259
Component:36К
ComponentEvent:407
Container: 451
Contai nerFvent:465
Dialog; 515
Fi 1 eDialog: 607
FocusEvent: 616
Frame; 675
ItemEvent:90#
KeyEvent;94X
Label:95X
List: 1002
Menu:1051
MenuComponent;1076
Menuitem; I09X
MenuShortcut: 1115
MouseEvent: 114?
Pai ntEvent; 1161
Scro 1 1 bar: 1110
ScrollPane: 1355
TextArea:1415
TextComponent;14^7
TextLvent:1453
TextField:1463
WindowEvent:1545
parent.
component. Component. got Parent (): 145
component locution relative to.
Component .getl ocationO; 340
menu component.
MenuComponent.get Parent(): 1076
popup menu, term definiiion. PopupMenu: 1192
patterns.
signature. Xer signature patterns
peekEventO,
FventQueue:575
peers,
classes.
ButtonPeer: 2()0
CanvasPeer: ?07
CheckboxMenuItemPeer:247
Chee kboxPeer;249
ChoicePeer: 265
ComponentPeer: 411
Contai nerPeer: 46X
Di alogPeer; 519
FileDi alogPeer: 611
FontPeer: 652
I ramePee r: 6X3
Label Peer: 962
Li ghtweightPeer:9X2
1 i stPeer: HHO
MenuBarPeer: 1067
MenuComponentPeer: ЮХ0
MenuitemPeer:1107
MenuPeer. 1109
PanelPeer: 1165
PopupMenuPeer: I 199
Scrol IbarPeer: 1 34 I
Scrol 1 PanePeer: 13(>O
TextAreaPeer:1421
TextComponentPeer; 1447
TextF i eldPeer: 146#
WindowPeer: 1555
creating.
Sec addkot i fyO
Tool kit: I T75
dcstros mg. V c removeNot i f у О
term definition. Component: 306
PGDN.
Event, replaced by KE YE vent. VK_PAGE_DOWN:
5<)5
PGP encryption.
MR support for. Applet: 76
PGUP.
Event, replaced h\ Key! vent .VK PAGE UP: ^6:
pink.
Color.pink: 293
pink.
Co 1 or: 29 *
pixel_bits.
ColorModel:302
PixelGrabber:1167
abortCrabbinq():1170
get(olorModel O: 1170
getHeightO: 1171
get Pi xels(): 1171
getStatusO: I 172
getWidth(): 1172
grabPi xels():1173
imageCompleteО:1173
PixelGrabberO: 1174
setColorMode1 ():1175
setDimensionsO: 1175
1644
setHi ntsO; 1175
setPi xels();1176
setPropertiesO; 1176
startGrabbi ngO: 1177
statusO. replaced by getStatusO; 1177
PixelGrabberO,
PixelGrabber; 1174
pixels.
See Also images
alpha component.
ColorModel .getAlphaO; 299
Di rectColorModel .getAlphaO; 531
IndexColorModel .getAlphaO; 848
IndexColorModel.getAlphas(); 849
bit si/e,
ColorModel .getPixelSizeO; 3(X>
ColorModel.pixel„bi ts(); 302
blue component.
ColorModel .getBlueO; 300
Di rectColorModel .getBlueO; 531
IndexColorModel .getBlueO; 849
IndexColorModel.getBlues(); 849
butter,
PixelGrabber. getHeightO; 1171
Pi xelGrabber. getPixel sO; 1171
PixelGrabber. getWidthO: 1172
convening, IndexColorModel .getRGBO; 851
converting to RGB,
Di rectColorModel. getRGBO; 533
delivery,
ImageConsumer.COMPLETESCANLINES; 816
ImageConsumer.RANDOMPIXELORDER; 817
ImageConsumer.SINGLEPASS; 821
ImageFi1 ter,resendTopDownLeft-
Right();828
ImageObserver.SOMEBITS; 837
ImageProducer.requestTopDown-
LeftRightResendO; 844
ImageProducer.startProduct ion О; 844
MemorylmageSource.newPixelsО; 1033
MemorylmageSource.requestTopDown-
Lef tRightResendO; 1035
Memorylmage-
Source . set Ful 1 BufferUpdatesO; 1038
MemorylmageSource.startProduct ionO:
1038
Pi xelGrabber; 1167
Pi xelGrabber .abortGrabbi ng(); 1170
Pi xelGrabber .grabPi xel sO; 1173
Pi xelGrabber.startGrabbi ngO; 1177
green component.
ColorModel. getGreenO: 300
Di rectColorModel.getGreenO: 532
IndexColorModel .getGreenO; 850
IndexColorModel .getGreensO: 850
image.
AreaAveragi ngScaleFiIter.set-
Pixel sO: 104
CropImageTi1 ter.setPi xels():475
ImageConsumer.setPixelsO; 819
ImageFilter. setPi xel sO; 830
Pi xelGrabber. setPi хе I s(): 1176
ReplicateScaleFiI ter.setPiхе 1s();1306
RGBImageFi1 ter.setPi xels(): 1319
red component.
ColorModel. getRedO; 301
Di rectColorModel.getRedO; 533
IndexColorModel .getRedO; 851
IndexColorModel .getRedsQ; 851
row,Repli cateScaleFi1 ter.outpi xbuf: 1305
state. PixelGrabber.getStatusO; H72
transmission request, by image consumer.
Fil teredlmageSource.request TopDown-
l eftRightResendO; 616
transparent. IndexColorModel .getTrans-
parentPi xel():852
values, converting to default color model,
ColorModel .getRGBO; 302
width, FontMetrics . st ri ngWidthO; 666
PLAIN,
Font;650
pl ai nTextFlavor.
DataFlavor;507
platform.
-specific peers, Toolkit: 1475
playO,
Applet: 89
AudioClip:106
playing.
audio clips.
Applet.playO; 89
AudioCi i p. 1 oopO. 106
AudioCi ip.playO; 106
р
INDEX
Point; 1178
equals(): 11X0
get LocationO; 1180
hashCodef);1181
move(). replaced by sett oration(); 1181
PointQ: 1181
setLocati on(); 1182
toStringO; 1182
translateO: 1183
x: 1183
y;1183
PointO,
Point: 1181
point(s).
adding to a polygon, Polygon .addPoint(): 1187
alignment,
Contai ner: 422
term definition, LayoutManager?; 972. 973
copying, Point.getLocationO: 1180
equality, testing for. Point.equals(): 1180
hash code, calculating. Point.hashCode()t 1181
location,
Component.contains 0: 326
Poi nt .getLocationO; 1180
inoxing, Poi nt. setLocationO: 1182
polygons, number of. Polygon. npoi nts: 1189
retrieving component containing.
Component.getComponentAt О; 337
Contai ner.getComponentAt 0:437
si/e,
as font property, Font: 640
Font, size; 651
string representation. Point. toString(): 1182
term definition, Point: 1178
testing for inclusion in a rectangle.
Rectangle.contains О; 1292
translating, Point.translateO; 1183
v-coordinate, Point .x; 1183
v-coordinate. Poi nt. y: 1183
Pol ygon; 1184
addPoi nt();1187
bounds; 1187
contai nsO: 1188
get Bound! ngBoxf). replaced by
getBoundsO: 1188
getBoundsO; 1188
insideO, replaced by contains(): 1189
npoints:1189
PolygonО;1189
trans 1ate(): 1190
xpoints: 1190
ypoints; 1110
Pol ygon O,
Polygon;1189
polygons,
See Also rectangles
bounding box.
Polygon.bounds:1187
Polygon .getBoundsO: 1188
bounds. Polygon.getBoundsO: 1188
filled, painting. Graphics.fi! 1 PolygonО; 718
painting, Graphics.drawPolygon(); 705
points in.
number of. Polygon .npoints: 1189
Pol ygon.addPoint(); 1187
testing membership. Polygon.contains():
1188
term definition.
Graphi cs.drawPolygon();705
Polygon: 1184
translating. Polygon, translateO: 1190
i coordinates. Polygon,xpoints: 1190
y-coordinates, Pol ygon. уpoi nts: 1110
polylines.
painting. G raph i c s. d rawPo 1 у 1 i ne (): 707
popup menus.
adding. Component. add0:319
events. See menu events
frame, F rame. remove (); 676
gesture, term definition. PopupMenu; 1192
peers.
creating. PopupMenu. addNotifyO: 1196
PopupMenuPeer; 1199
Toolkit.createPopupMenuО: 1485
popup trigger property,
MouseFvent:1132
testing for. MouseEvent. isPopupT rigger():
1137
removing. Component, removeО: 376
term definition.
Component; 307
PopupMenu:1192
trigger property,
term definition. MouseEvent: 1132
tenn definition. PopupMenu; 1191
testing for.
MouseEvent.i sPopupTriggerО - 113 7
1646
PopupMenu; 1192
addNotifyO; 1196
PopupMenuO: I 196
showO: J196
PopupMenuO,
PopupMenu; 1196
PopupMenuPeer: 1199
ShowO; 1200
position,
component, GridBagLayout.AdjustForGrav
i ty();764
as gridbag constraint, term definition.
Gri dBagConstraints; 739
posted,
terrn definition. FventQueue; 573
postEventO,
Component, replaced by di spatchEvent О; 369
MenuComponent, replaced by
MenuComponent.dispatchEventO; 1077
MenuContai ner. replaced by
MenuComponent. di spatchEventO: 10X6
Window, replaced by
Component.di spatchEventO; 1528
EventQueue: 575
preferred,
size.
Border! ayout.preferredlayoutSizeO;
186
CardLayout.preferredLayoutSi ze();218
FlowLayout.preferredLayoutSize(); 625
GridBagLayout. preferredLayoutSizeO;
777
GridBagLayout.PREFERREDSIZE; 778
Layou tManager.preferredLayoutSi zeO;
970
preferredLayoutSi zeO,
BorderLayout;186
CardLayout; 218
FlowLayout;625
Gri dBagl ayout: 777
GridLayout;788
LayoutManager;970
preferredSi zeO,
Component, replaced by
getPreferredSizeO; 369
ComponentPeer. replaced by
getPreferredSizeO; 417
Container, replaced by
getPreferredSizeO; 451
Li st. replaced by get Prefer r edS i ze О: I Off
ListPeer. replaced by
getPreferredSizeO: 1014
TextArea. replaced by
getPreferredSize(); 1416
TextAreaPeer. replaced b>
getPreferredSi zeO; 1425
TextField. replaced by
getPreferredSizeO: 1463
PREFERREDSIZE,
GridBagLayout:778
preferredSizeO<
TextFieldPeer; 1470
preparelmageО<
Component;369
ComponentPeer;417
Toolkit:1495
previousO,
CardLayout:218
print,
graphics context. PrintGraphics: 1201
job, PrintGraphics.getPrint]ob(): 1202
printC),
Component;370
ComponentPeer; 417
Contai ner; 451
print joh.
class. Pri nt Job; 1203
creating. Toolki t. getPr i nt Job 0: 1491
finishing.
Pri ntJob.end();1211
PrintJob.fi nalizeO; 1211
graphics context, creating.
Pri ntlob.getGraphicsO: 1211
page dimensions.
PrintJob.getPageDimens ion(); 1214
page resolution.
Pri ntJob.getPageResolution(): 1214
printing backwards.
PrintJob. lastPageFirstO: 1214
printAll()<
Component; 370
printComponents() „
Container: 451
ScrollPane: 1355
PrintGraphics;1201
getPrintJob();1202
INDEX
printing,
Ser A Eft painting
component information. Component. li st(): 356
components, on a graphics context,
ComponentPeer.print О: 417
container,
component hierarchy Contai ner. 11 st О : 444
components on a graphics context.
Container .printO: 451
components on a graphics context.
Container.pri ntComponent sО:451
limitations and bugs. Printjob; 1203
scroll pane. Scrol iPane: 1355
steps for. PrintJob: 1203
PrintJob:1203
end():1211
f1nali ze(): 1211
getCraphi csO;1211
getPageDimensionO; 1214
getPageResolutionO: 1214
lastPageFir$tO: 1214
processActionEventO,
Button:196
List: 1002
Menult em:1098
TextField; 1464
processAdjustmentEventO,
Scrollbar; 1331
processComponentEventO,
Component: 371
processContainerEventO,
Contai ner; 452
processEventO,
Button:196
Checkbox; 22k
CheckboxMenuItem: 243
Choi ce;259
Component: 371
Contai ner;45?
List: 1003
MenuComponent: 1077
Menuitem;1099
Scrol 1 bar: I 332
TextComponcnt:1438
Tex tri eld: 1464
Window: 1529
processFocusEventO,
Component;373
processItemEventO,
Checkbox;22K
CheckboxMenuItem:244
Choice;260
List: 1004
processKeyEvent О,
Component;374
processMouseEvent(),
Component;375
processMouseMotionEventO,
Component;375
processTextEventO,
TextComponent;1438
processWi ndowEvent О,
Window; 1529
producers,
adding consumers,
ImageProducer.addConsumerO; 843
destroying consumers.
ImageProducer.removeConsumerO:843
image.
Image.getSourceO; 806
ImageProducer; 838
MemorylmageSource:1029
scaling requirements for.
AreaAveragingScaleFi1 ter; |01
term definition. Image: 795
Image.getSourceO; 806
ImageProducer.requestTopDownLeftRight-
ResendO: 844
ImageProducer.startProduct ion 0:844
pixel delivers,
MemorylmageSource. newPi xel sO: 1033
MemorylmageSource.requestTopDown
LeftRightResendO: 1035
MemorylmageSource.setfulIBuffer
UpdatesO; 1038
MemorylmageSource,startProductionO:
1038
properties. ImageConsumer.setPropertiesO:
819
registering image consumers with.
Fi 1 teredlmageSource.addConsumerO;615
ImageProducer.addConsumerO; 843
MemorylmageSource,addConsumerО: 1032
removing register image consumers.
MemorylmageSource.removeConsumerO;
1033
1648
term det in ttton.
Image;795
ImageConsumer;X11
testing for consumers.
ImageProducer. isConsumerO: X43
testing image consumer registration.
MemorylrageSourc e. addConsumerO; |(K2
propagation id,
changed property.
PropertyChangeEvent.getPropaga *
tionldO; 1220
PropertyChangeEvent.setPropaga
tionldO; 1222
term definition. PropertyChangeEvent: 1217
properties.
alignment.
Container; 42?
let in definition. Component; 104
term definition. I ayoutvanager2: 972
bean, editing. Customi zer; 4X6
bean def unit,
Beanlnfo.getDefaultPropertyTndexO;
164
SimpleBeanTnfo.getDefaul t Fvent-
IndexQ; 1370
term definition; 16?
bean-info.
Beaninfo.getPropertyDescriptors0: 166
SimpleBeaninfo.getPropertyDescri p-
torsQ; I 372
beans.
PropertyChangeEvent; 1215
PropertyChangeListener;1223
bound. hound properties
change events, PropertyChangeL i stener; 1224
constrained. Srr consti dined properties
cursor. Frame: 667
custom editor.
testing support for.
PropertyEdi tor. supportsCustorr
EditorQ: 1261
PropertyEdi torSupport - supports
CustorFdi torQ: 1
custom editors.
PropertyEdi tor: 1259
PropertyEdi tor.getCustomEd i torQ: 1256
PropertyEdi torSupport.getCustom
Edi torQ; 1275
data How during editing. PropertyEditor: 1251
director.
FileDia log. getDi rectoryO: 606
FileDialog. setDi rectoryO: 60X
FileDialogPeer. setDi rectoryO: 61?
term definition. Fi leDialog; 601
echo. TextFi eld: 1456
editing. PropertyEdi torManager: 1262
enabled, term definition. Component; 305
event Him during editing. PropertyFdi tor; 1251
feature desci ipiors. signature pattern characteiistics
Introspector; X91
file.
FileDialog. getFileO. 606
Fi 1 eDialog. setFi 1 eQ: 60S
Гi 1 eDialogPeer. setFi 1 eQ: 612
term definition, Fi leDialog: 61 Ji
filename.
Г ileDi a log.get FilenameFi 1 terQ; 607
FileDi alog.setFilenameFi11er();609
Ti1eDi alogPeer.setГ ilenameF i1 terО:
612
filter.
F i leDialog. дет Fi 1 enamel i IterQ; 607
Гi 1 eDi a log. setFi 1 enameFi IterQ: 609
Fi 1 eDialogPeer.set Fi1enareF iI ter().
61?
term definition. Fi 1 eDialog: 601
fonts. Font; 639
icon image, f rame; 667
image.
CropImageF i1 ter.setPropert i es():476
Image.Undef i nedProperty;X10
ImageConsurer.setPropert iesQ:X19
ImageFi Iter. setPropertiesO; X30
PixelGrabber. setPropertiesO; 1176
ReplicateScaleF i1 -
ter. setPropertiesO; !307
images.
Image.getPropertyO; X04
ImageObserver. PROPER! IE-S: K37
term definition. Image; 796
indexed.
attributes luhle. I ndexedProperty
Descriptor: K55
IndexedPropertyDescriptor;X54
IndexedPropertyDescri ptor.get -
IndexedPropertyTypeQ: X6I
P INDEX
properties icofiiitiued)
indexed.
IndexedPropertyDescri ptor.get
IndexedReadMethodO: 861
IndexedPropertyDescri ptor.get-
Indexedwri teMethodO; 865
item, ItemEvent; c>03
key code names. Table. KeyEvent; 938
menu, term definition. Menu; 1040
modal. Di al og. setModal О; 516
mode, terrn definition. FileDialog: 601
model, testing for. Dialog, i sModal (): 514
name.
PropertyChangeEvent:1217
PropertyChangeEvent.getProperty
KameO‘« 1 220
paintability.
testing, PropertyEdi tor. i sPai ntableQ:
1258
testing, PropertyEdi torSupport. isPaint-
ableC): 1279
paintable area, PropertyEditor: 1251
painting.
PropertyEdi tor. pai ntValueO: 1258
PropertyEdi torSupport.pai ntValue О:
1280
popup trigger.
term definition, MouseEvent: 1132
term definition. PopupMenu: 1193
testing for. Mousel vent. i sPopupTriggerO:
1137
propagation id.
PropertyChangeEvent.getPropaga-
tionldO: 1^70
PropertyChageEvent.setPropaga-
tionldO; 1222
property editor.
default. PropertyEditor; 1249
kinds of, PropertyEditor; 1249
locating. PropertyEditor; 1249
locating, PropertyEditorManager; 1262
locating, PropertyEditorManager.f indEd-
itor(); 1265
PropertyDescri ptor.getProperty-
EditorC1ass():1235
PropertyDescri ptor.setProperty-
Edi torCl assO:1247
PropertyEditor: 1248
purpose and characteristics. PropertyEditor:
1249
term definition. PropertyEdi tor; 1248
term definition. PropertyEdi torSupport:
1267
property types.
associating a property editor with. Property Ed
i torManager.regi sterFdi tor(); 1266
property t'ditor conversion. PropertyEditor:
1250
PropertyDescriptor.getProperty-
Type (): 1237
read accessor method. PropertyDescri p
tor .getReadMethodO: 1238
resizable.
Dialog.setResizable():516
DialogPeer.setResizableO: 520
Frame:667
Frame.setResizable():680
FramePeer.setResizable(); 684
term definition. Di a 1 og: 509
testing for. Dialog, is Res izableO: 515
testing for. Frame, i sResizable(); 674
retrieving. Toolkit . getProperty0: 1492
search path.
locating. PropertyEdi torManager.getEdi
torSearchPath();1265
setting. PropertyEditorMan-
ager. regi sterEdi tor(): 1266
sheet, term definiiion, Customi zer: 486
state change.
ItemEvent;903
ItemEvent.getStateChangeO:906
tags.
property editor handling.
PropertyEdi tor; 1250
retrieving.
PropertyEditor. getTagsO; 1257
retrieving. PropertyEdi torSupport .get-
TagsO: 1278
title.
Dialog.getTi tle();514
Dialog.setTitle();517
DialogPeer.setTi tle();520
Frame:667
Frame.getTi tle(); 674
Frame.setTi tle():681
term definiiion. Dialog: 509
toolkit. Wi ndow: 1519
1650
value.
PropertyChangeEvent.getNewValue():
1219
PropertyChangeEvent.getOldValueO:
1220
PropertyEdi torSupport. getVal ue(); 1 279
setting.
PropertyEdi tor.setValue(): 1260
PropertyEdi torSupport. setValueO:
12X4
string representation,
PropertyEditor.getAsTextO: 1255
PropertyEditor.setAsTextO: 1260
PropertyEdi torSupport.getAsText O;
1273
PropertyEditorSupport. setAsTextO;
1281
values.
ret hex ing.
PropertyEdi tor. getTagsO: 1257
PropertyEdi torSupport .getTagsO:
1278
visible, term definition. Component; 305
wanting message. Wi ndow: 1518
write accessor method. PropertyDescrip-
tor .getwri teMethodO; 1240
PROPERTIES,
ImageObserver: 837
property change events,
Customizer; 486
listeners.
Customi zer.addPropertyChange
ListenerO; 498
Customi zer.removePropertyChange-
ListenerO; 498
PropertyChangeSupport.addProperty-
ChangeListenerO; 1227
PropertyChangeSupport.removeProper-
tyChangeLi stenerO; 1228
PropertyEdi tor.addPropertyChange
Li stenerO; 1255
PropertyEditor.removePropertychange
Li stenerO; 1259
PropertyFditorSupport.addProperty
Changel istenerO. 1272
PropertyEdi torSupport.fi reProperty
ChangeO; 1272
PropertyEdi torSupport.removeProper-
tyChangeLi stenerO; 1281
PropertyChangeEvent;1216
PropertyChangeListener:1224
PropertyChangeSupport:1225
retries ing. PropertyVetoExcept i on . get
PropertyChangeEventO: 1287
veioable.
VetoableChangeSupport.addVeto-
ableChangeLi stenerO; 1511
VetoableChangeSupport.fi reVetoable-
C hangeO: 1512
VetoableChangeSupport.removeVetoable
ChangeLi stenerO; 1513
vetoable properties. PropertyVetoException;
1286
vetoing. VetoableChangeSupport; 1510
property descriptors,
attribute^ fable, PropertyDescr i ptor; 123(1
term definition, PropertyDescriptor: 1229
propertyChangeQ,
PropertyChangeListener: 1224
PropertyChangeEvent;1216
getNewValue(): 1219
getOldValue(): 1220
getPropagationldO: 1220
getPropertyNameO; 1220
PropertyChangeEventO: 1221
setPropagationldO: 1222
PropertyChangeEvent О,
PropertyChangeEvent; 1221
PropertyChangeListener;1223
propertyChangeO; 1224
PropertyChangeSupport;1225
addPropertyChangeL istenerO; 1228
firePropertyChangeO: 1228
PropertyChangeSupport0: 1228
removePropertychangeL i stenerO; 1228
PropertyChangeSupportO,
PropertyChangeSupport;1228
PropertyDescriptor;1229
getPropertyF.di torCl assO; 1235
getPropertyTypeO; 1237
getReadPethodO; 1238
getWri tePethodO: 1240
i sBoundO: 1242
i sConstrai nedO: 124*
PropertyDescriptorO. 1243
setBoundO: 1246
setConstrainedО;1247
setPropertyEditorClassO: 1247
PropertyDescriptorO,
PropertyDescriptor;1243
INDEX
PropertyEditor; 1248
addPropertyChangeLi stenerO: 1255
getAsTextO; 1255
getCustomEdi torO; 1256
get Javalni tializationStringO: 1256
getTagsO; J257
getValueO: 1257
isPaintableO: 1258
paintValue(); 1258
removePropertyChangelistenerO:1259
setAslextO: 1260
setValueO; 1260
supportsCustomEditor():1261
PropertyEdi torManager: 1262
fi ndFdi tor О; 1265
getEditorSearchPath();1265
registerEditor();1266
setEditorSearchPath().1266
PropertyEditorSupport;1267
addPropertyChangeLi stenerO; I?72
f i rePropertyChangeO: 1272
getAsTextO: 1273
getCustomEdi torO; 1275
getJavalniti al izationStringO: 1278
getTagsO: 1278
getValueO; 1279
i sPai ntableO; 1279
paintValueO: 1280
PropertyEditorSupport();1280
removePropertyChangel i stenerO; 1281
setAsTextO; 1281
setValueO: 1284
supportsCustomEdi torO; 1285
PropertyEditorSupport О*
PropertyEditorSupport:1280
PropertyVetoException:1286
getPropertyChangeLvent(): 1287
PropertyVetoException();1287
PropertyVetoExceptionCh
PropertyVetoException:1287
public method signature pattern,
Introspector;892
Q
queues,
event
adding to. EventQueue.postEventO; 575
EventQueue: 573
FventQueue.getNextEvent(); 574
EventQueue.peekFventО; 575
term definition. EventQueue; 573
Tool ki t. getSystemFventQueueO. 149'
Toolkit.getSystemEventQueuelmplO;
1494
R
RANDOMPIXELORDER.
ImageConsumer: 817
reading,
indexed properties. IndexedPropertyDescrip
tor.getlndexedReadMethodO:861
Rectangle:1288
addQ; 1292
contai ns(); 1292
equals();1293
getBoundsO: 1294
getLocation();1294
getSizeO; 1294
grow():1294
hashCodeO; 1295
height;1295
i nside(). replaced by contains(); 1296
i ntersectionO: 1296
i ntersectsO; 1297
isEmptyO; 1297
move(). replaced by setLocat ion(); 1297
RectangleO: 1298
reshapeO. replaced h> setBoundsO; 1298
resizeO. replaced by setSize(): 1299
setBoundsO; 1299
setLocation 0:1300
setSizeO: 1301
toStringO; 1301
translateO: 1301
uni on О;1302
width; 1303
x; 1303
y; 1303
RectangleO,
Rectangle;1298
1652
rectangles»
area, testing for. Rectangle. isEmptyQ: 1297
bounds. Rectangle.getBoundsO; 1204
enlarging. Rectangle.addQ: 1292
equality, testing tor. Rectangle.equalsQ: 1293
filled.
painting.
Graphics.fill3DRect(): 714
Graphics.fi1IRectQ; 720
growing. Rectangle .growQ; 1294
liash code, calculating.
Rectangle.hashCodeO: 1295
height, calculating. Rectangl e. hei ght: I 295
intersection, calculating.
Rectangle.intersect!onQ;1296
intersections, testing for.
Rectangle. intersectsQ; 1297
location, Rectangle.getlocat ionQ; 1294
moving.
Rectangle. setBoundsQ: 1299
Rectangle.setl ocationQ; 1300
outline, Graphi cs . dr aw Rec tO: 708
painting, Graphics. cl earRectQ: 689
Rectangle;12X8
resizing. Rectangle.setBoundsQ: 1299
rounded,
filled, painting,
Graphics.fi 1 IRoundRectQ; 721
outline, Graphics .drawRoundRectQ: 710
size.
increasing. Rectangle.growQ; 1294
Rectangle .getSizeQ; 1294
Rectangl e. setSizeO; 1301
string representation. Rectangle.toStringQ;
1301
testing for point inclusion.
Rectangle.containsQ; 1292
translating. Rectangle. toStringO: 1301
union, calculating. Rectangle.uni onQ; 1302
width. Rectangle.width; 1303
v-coordinate, Rectangle.x; 1303
у coordinate. Rectangle.y; 1303
red,
Color: 293
red component,
bn mask.
Di rectColorModel .getRedMaskQ; 53^
Color.getRedQ; 291
Color, red; 293
ColorModel .getRedQ; 301
pixel.
IndexColorModel .getRedQ; 851
IndexColorModel.getRedsQ: 851
pixels. Di rectColorModel .getRedQ; 533
reference.
applet. AppletContext.getAppletQ: 94
regi sterEdi torQ.
PropertyEditorManager;1266
RELATIVE.
GridBagConstraints: 754
REMAINDER.
GridBagConstraints: 754
removeO.
AWTEventMulticaster;145
Choi ce;260
Choi cePeer; 267
Component;376
Container; 453
Frame;676
list: 1004
Menu:1051
MenuBar; 1064
MenuContainer; 1087
removeAction Li stenerO.
Button:197
List;1005
MenuTtem; 1100
Textr ield: 1465
removeAdjustmentLi stener О.
Adjustable: 59
Scrollbar; 1332
removeAl1O.
Choi ce;262
Container; 453
I ist;1005
ListPeer; 1014
Menu:1052
removeComponent Li stenerO.
Component;376
removeCon s ume г О •
Fi 1 teredlmageSource; 616
ImageProducer:843
MemorylmageSource;1033
removeContai nerLi stenerO,
Contai ner:454
removeFocusListenerО.
Component: 377
R
INDEX
removeimage(),
MediaTracker:1025
removeinternal()•
AWTEventMul ticaster; 146
removeltemLi stener О •
Checkbox:229
CheckboxMenuItem:245
Choice; 262
ItemSelectable:918
List; 1007
removeKey Li stenerO*
Component;377
removeLayoutComponent О.
BorderLayout; i86
CardLayout;219
FlowLayout;626
GridBagLayout:778
GridLayout; 788
LayoutManager;971
removeMouseLi stenerO,
Component;378
removeMouseMotionListener().
Component;378
removeNot i f у (),
Component:379
Contai ner; 454
List; 1007
Menu:1053
MenuBar;1065
MenuComponent;1077
TextComponent:1439
removePropertyChangeListenerO,
Customizer; 498
PropertyChangeSupport: 1228
PropertyEditor;1259
PropertyEditorSupport;1281
removeTextLi stenerO,
TextComponent;1439
removeVetoabl eChangeLi stener О,
VetoableChangeSupport: 1513
removeWi ndowLi stenerO,
Window: 1530
repaintO,
Component:379
ComponentPeer;418
replaceltemO,
List:1004
repl aceRangeO,
TextArea;1416
TextAreaPeer:1426
repl aceTextO,
TextArea. replaced hv replaceRangeC): 1418
TextAreaPeer. replaced tn
replaceRangeC);1426
replicate scale filter,
area averaging scale 1'iltei compared nith.
AreaAveragingScaleFiIter: 101
term definition. ReplicateScaleFi 1 ter: 1304
ReplicateScaleFilter;1304
destHeight;1305
destWidth; 1 305
outpixbuf: 1305
ReplicateScaleri1 ter(): 1306
set Dimensions():1306
setPi xel s():1306
setPropertiesO: 1307
srccohll; 1307
srcHeight:I3U8
M-ciousJ: 1308
sreWidth:1308
ReplicateScaleFilter(),
ReplicateScaleFilter; 1305
representation class,
relriexing. DataFlavor.getRepresentation-
Class():505
term definition. DataFlavor; 501
requestFocusO,
Component;381
ComponentPeer;418
reques tTopDownLeft Ri ghtResend О,
Fi1teredlmageSource:616
ImageProducer;844
MemorylmageSource:1035
resendTopDownLeft RightO,
ImageFi1 ter;828
RESERVED_ID_MAX,
AWTEvent: 126
reshapeO*
Component, repl need
Component.setBounds();382
ComponentPeer. replaced bs set Bounds (): 41S
Rectangle, replaced Ik setBoundsO: 1398
resizable property,
dialog.
Dialog.setResizable();516
DialogPeer.setResizable():520
1654
testing tor.
Dialog, i sResizableO; 515
Frame, i sResizableO; 674
setting.
Frame. setResizableO; 680
FramePeer. setResizableO; 684
term definition.
Dialog: 509
Frame;667
resizeO,
Applet; 89
Component, replaced by
Component.setSize(); 382
Rectangle, replaced by setSize(); 1299
resizing,
See Also .size
applet, bounds,
AppletStub.appletResizeО: 98
components.
Component.setBounds О;384
ComponentAdapter.componentResi zed О:
399
ComponentEvent.COMPONENT-RESIZED; 4U5
ComponentLi stener.component-
ResizedO;410
ComponentPeer. setBoundsO: 419
cursor.
Cursor.E„RESIZE-CURSOR; 481
Cursor.N„RESIZE_CURSOR; 483
Cursor.NE„RESIZE-CURSOR: 484
Cursor.NW_RESIZE_CURSOR;484
Cursor.S.RESIZE-CURSOR; 484
Cursor.SE_RESIZE_CURSOR; 484
Cursor.SW_RESIZE_CURSOR; 485
Cursor.W„RESIZE-CURSOR; 485
rectangles. Rectangle. setBoundsO; 1299
scroll panes.
ScrollPanePeer.chiIdResi zed(); 1361
windows, Window.pack О: 1528
resolution,
page. Printlob.getPageResolutionO; 1214
screen.
Tool ki t .getScreenResolutionO: 1493
resource sharing,
See lucks
RGB (red, green, blue 1 color system,
See Also colors
24-bit representation, Color .getRGBO; 291
converting HSB to. Color .HSBtoRCBQ: 292
converting pixels to.
Di rectColorModel .getRGBO; 533
converting to HSB. Co lor .RGBtoHSBO; 293
creating color from. Color. getColorQ: 288
decoding. Color.decodeO; 285
filter,
override,
RGBImageFiIter.filterRGB0: 1316
RGBImageFi 1 ter. f i 1 terRGBPixel sO;
1316
filters, testing, RGBImageFi Iter. canFi 1 terIn-
dexColorModel;1311
image filter, RGBImageFi 1 teг: 1309
IndexColorModel .getRGBO; 851
retrieving. SystemColor.getRGBO; 1395
term definition, Color; 278
RGBImageFi1 ter;1309
canFilterlndexColorModel; 1311
fil terlndexCol orModel (); 1313
filterRGBO; 1316
fi1terRGBPixels();1316
newmodel;1318
ori gmodel;1319
setColorModelО;1319
set Pixels O'. 1319
substituteColorModel O; 1320
RGBtoHSBO,
Color: 293
right,
alignment.
Component.RIGHT-ALIGNMENT; 382
F1owLayou t.RIGHT; 626
Label. RIGHT: 959
value. Insets. right; 885
right,
Insets;885
RIGHT,
Event, replaced by KeyEvent .VK_RIGHT: 566
FlowLayout: 626
Label;959
RIGHT-ALIGNMENT,
Component;382
rounded rectangle,
filled, painting,
Graphi cs. f i 11 RoundRectO; 721
outline. Graphics.drawRoundRect О; 710
rowHeights,
Gri dBagLayout:778
INDEX
rows,
grid.
GridLayout: 7X1
Gridl ayout .getRowsO: 785
GridLayout. setRowsO; 791
gridbag,
GridBagConst rai nts. wei ghty: 758
GridBagLayout. rowHeights: 778
GridBagLayout. rowWeights: 779
list. list.getRowsO: 995
of pixels.
ReplicateScaleFiIter.outpixbuf: 1305
text area,
TextArea.getRowsO; 1412
TextArea.setRowsО:1420
rowWeights,
GridBagLayout: 779
RS A encryption,
JAR support for. Applet: 76
s
S_RESIZE_CURSOR.
Frame, replaced by
Cursor.S RESIZE CURSOR; 677
Cursor; 484
save(),
AWTEventMulticaster: 147
SAVE,
Fi 1 eDialog;608
SAVE_FILE,
Event:566
save file dialog,
Fi 1 el)ialog.SAVE; 608
term definition. FileDialog; 601
savelnternal O,
AWTEventMulticaster: 148
SCA LE-AREA-AVERAGING.
Image:808
SCALE-DEFAULT,
Image;809
SCALE-FAST,
Image; 809
SCALE_REPLICATE,
Image: 809
SCALE-SMOOTH,
Image:810
scaling.
algorithms.
Image. SCALE_AREA_AVERAGING specification
of: 808
Image. SCALE REPLICATE specification of; 809
ReplicateScaleFi Iter: 1304
specification of.
Image.SCAL F.DEFAULT: 809
Image.SCALE,FAST; 809
Image.SCALE-SMOOTH: 810
\aluex used In.
ReplicateScaleFiIter.srccols[J:
1307
Repli cateScaleTiIter.srcrows L ?:
1308
images.
AreaAveragingScaleFiIter;101
Image.getScaledlnstanceQ; 804
Medial racker. addlmageQ: Ю21
scanlines.
pixel delivery
ImageConsumer.COMPL1 II SCANLINES: 816
screen,
component location on.
Component.getLocati on0nScreen():341
resolution. Tool kit. getSc reenResol ut ion();
1493
si/e. Toolki t .getScreenSize(): 1493
SCROLL-ABSOLUTE,
Event, replaced by AdjustmentEvent.TRACK:
566
SCROLL_LINE_DOWN,
Event, replaced by Adjustment
Event.UNIT INCREMENT; 567
SCROLL_LINE-UP,
Fvent. replaced by
AdjustmentFvent.UNIT DLCRFMFNT: 567
SCROLL-PAGE_D0WN.
Event, replaced by
AdjustmentEvent.BLOCK_DFCRFMENT; 567
SCROLL_P AGE_UP,
Fvent, replaced by Adjustment-
Event.BLOCICDFCREMENT: 567
scroll panes,
adding components to. Scroll Pane.addlmpl():
1 M9
child component preparation. Scrol 1 Pane: 1344
child resize notification.
Scrol1PanePeer.chiIdResized();1361
1656
peers,
creating. ScrollPane. addNotifyO: 1349
Scrol 1 PanePeer: 1360
Toolkit.createScrol 1 PaneC): i486
scroll position.
moving,
Scrol1 Pane.setScroll Position():
1359
Scrol1PanePeer.setScrol1Posi ti on()
; 1361
Scroll Pane. getSc rol IPositionQ: 1352
sc roll bars,
display policy. Scroll Pane.getScrol IbarD
isplayPolicy();1352
horizontal.
Scrol1 Pane.getHAdjustable():1350
Scrol1 Pane.getScrol1Posi ti on О:
1352
vertical, Scrol 1 Pane.getVAdjustableO;
1353
ScrollPane; 1343
term definition. Scroll Pane; 1343
viewports, size,
Scrol 1 Pane. getVi ewportSizeO; 1353
scroll position,
term definition, Scroll Pane; 1344
ScrolIbar;1321
addAdjustmentLi stenerO; 1326
addNotifyO: 1327
getBlocklncrementO; 1327
getLinelncrementO. replaced by
getUni tlncrementO; 1327
getMaximumO; 1328
getMinimumO: 1328
getOrientationO; 1328
getPagelncrementO. replaced by
getBlocklncrementO; 1329
getUni tlncrementO: 1329
getValueO: 1329
getVi si bl e(). replaced by
getVi si bleAmountO: 1330
getVisi bl eAmount О; 1330
HORIZONTAL: 1330
paramStringO: I 330
processAdjustmentEventO;1331
processEventO; 1332
removeAdjustmentListenerO:1332
Scroll barО; 1332
setBlocklncrementO: 1334
set I i nelncrement О. replaced by
setUnitlncrement(): HU
setMaximumO: 13 U
setMi nimumO; 1335
setOrientationO: 1337
setPageTncrementO. replaced by
setBlocklncre'rentO; 1338
setUnitlncrementO: 1338
setValueO; 1339
setValuesO; 1 339
setVi si bleAmountO: 1340
VERTICAL;1340
Scrollbar(),
Scro 1 Ibar; 1332
scrollbar,
SystemColor:1398
ScrollbarPeer:1341
setLinelncrementO; 1342
setPagelncrementO:1342
setVa1ues();1342
scroll bars,
background color, SystemColor. scrol Ibar:
1398
display policies.
Scrol1 Pane: 1345
Scrol1Pane.getScrol1barDi splay
PolicyO: 1352
displaying.
Sc roll Pane.SCROLLBARS ALWAYS: 1356
Scroll Pane.SCROLLBARS AS.NFFDFD; 1358
Scroll Pane.SCROL t BARS.NEVER: 1358
TextArea.SCROLLBARS_BOTH: 1418
TextArea.SCROLLBARS_HORIZONIAL;1419
TextArea.SCROLLBARS_NONE; 1419
Tex tArea. SCROL LBARS.VERI ICAL.ONLY:
1419
even! types fired by. Table. AWTEvent: 115
events,
ScrolIbar.processAdjustmentFventО;
1331
ScrolIbar,processEvent():1332
horizontal.
height.
Sc rol1 Pane,getHSc ro11barHe i ght():
1352
Sc rollPanePeer.getHScrol1barHe ight
O:1361
retrieving.
Scrol1 Pane.getHAdjustable(): 1350
s
INDEX
scroll bars (ctnifintu'ih
increments.
retrieving.
Scrol1 bar.getBloc klncrementQ: 1327
Scrol1 bar.getUni tinerementQ; 1320
Scrollbar; 1322
Scrol1 bar.setBlockTnc rement(); 1334
Scrol1 bar.setLinelncrement О; 1142
Scrol Ibar. setMaximurrQ: 1334
Scrol 1 bar. setMi nirrumQ: 1 135
ScrolIbar.set PagelncrementQ: 1142
Scrol1 bar.setUni tinerementQ; 1338
Scrol1PanePeer.setUni tinerement():
136?
orientation.
retries ing.
Scroll bar.getOrientation(): I*28
Scrollbar.HORIZONTAL : 1330
Scrol1 bar.setOri entat ion(); 1337
ScrolIbar.VERTICAL: 1340
peers.
creating. Scrol 1 bar. addNoti fуQ: 1 *27
Scrol IbarPeer: 1341
Too Iki t.createScrol1 bar Q: I486
proportional indicator. ScrolIbar. 1322
scroll pane relationship. ScrollPane; 1345
Scrol 1 bar; 1321
lexi area.
TextArea: 1405
TextArea.getScrolIbarVi si bi 1i tyO:
1412
x alues.
retrieving,
Scrol 1 bar. getMax imumQ; 1328
crol Ibar.getMi nirrumQ: 1328
Scrol 1 bar.getVa1ue():I*29
ScrolIbar. setValueO; 1339
ScrolIbar.setValuesQ; 1339. 1342
Scrol 1 PanePeer. setVal uesQ: 1362
vertical,
Scrol1 Pane.getVAdjustableО:I 353
w idth.
Scroll Pane.getVScrol1barWidthQ:
1355
ScrollPanePeer.getVSc rolIbar
Width 0: 1361
v isibte amount,
relriev ing.
Scroll bar.getvi si bl eAmount О; 1330
Scroll bar. setVi si Ы eAmount О; 1 *•
SCROLLBARS_ALWAYS.
Scrol1 Pane; 1356
SCROLLBARS_AS_NEEDED<
Scrol1 Pane:1358
SCROLL BAR S_B0TH,
TextArea;1418
SCROLLBARS_HORIZONTAL_ONLY,
TextArea:1419
SCROLLBARS.NEVER.
Scrol1 Pane: I*58
SCROLLBARS_NONE.
TextArea:1419
SCROLLBARS_VERTICAL_ONLY.
TextArea: 1419
scrolling,
lists.
Li st.makeVisible(X 1000
Li stPeer. makeVi sibleQ; 101*
ScrollPane;1343
addlmpl0:1349
addNoti fy(); I*49
doLayoutQ: 1350
getHAdjustableQ: 1350
getHScrollbarHeightQ:1352
getScrollbarDi splayPoli CyQ:1352
getScrol IPositionQ; 135?
getVAdjustable();1353
getvi ewportSi zeO; 1*53
getVSc rol IbarwidthO: 1355
layoutO. replaced bv doLayoutQ; 1 *5>
pararrStr i ngQ: 1355
pri ntComponentsO; 1355
SCROLLBARS_ALWAYS: 1356
SCROL I BARS_AS_NEEDED: 1358
SCROLI BARS NEVER; 1358
Scrol iPaneQ; 1358
set LayoutQ: 1359
set Sc rol1Pos i t ion();1*59
Scrol IPaneO.
Scroll Pane:1358
ScrollPanePeer:1360
chi IdResizedQ: 1 *61
getHScrollbarHeightQ; 1*61
getVScrol IbarWidthQ; 1*61
set Sc rol 1 Posi tionQ: 1361
setUnitinerementQ:1362
setValueO; 1362
1658
SE_RESIZE_CURSOR,
Frame, replaced h\
Cursor.SE_RESIZE.CURSOR:677
Cursor: 484
search path.
bean-info.
Introspector.getBeanlnfoSearch-
PathO: 901
Introspector.setBeanlnfoSearch
Path();90]
Introspector: 892
property editor manager use.
PropertyEditorManager:1262
term definition and default.
PropertyEditorManager:1262
selectO.
Choi ce;263
ChoicePeer: 267
Li st:1007
Li stPeer; 1015
TextComponent:1440
TextComponentPeer:1449
seiectAl1Q.
TextComponent:1441
SELECTED.
ItemEvent: 908
selected item.
term definition. Choi ce: 251
semantic.
c^ent. term definition. AWTFvent: 111
ечепь.
processing of. AWTEvent: 113
types. Scc action events: adjustment events: item
events: text events
separator.
menu item.
MenuPeer.addSeparator(); 1110
term definition. Menu I tem: 1089
serialization.
of applets. Appl et: 75
event. EventQueue: 573
setActi onCommandQ.
But ton:197
Menuitem;1100
setAlignmentО«
FlowLayout:626
Label:959
Labe 1 Peer: 963
setAnimatedQ.
MemorylmageSource:1015
setAsTextQ.
PropertyEdi tor: 1260
PropertyEditorSupport:1281
setBackgroundO.
Component:383
ComponentPeer:419
setBeanlnfoSearchPathQ.
Introspector:901
setBl ocklncrementQ.
Adjustable:59
Scroll bar: 1334
setBoundQ.
PropertyDescriptor: 1246
setBoundsQ.
Component:384
ComponentPeer:419
Rectangle:1299
setCaretPositionО.
TextComponent:1442
TextComponentPeer:1449
setCheckboxGroupO.
Checkbox: 229
CheckboxPeer: 250
setClipO,
Graphics: 728
setColorQ,
Graphics: 731
setColorModelQ.
ImageConsumer; 817
imageE i 1 ter: 828
Pi xelGrabber: 1175
RGBImageFi Iter: 1319
setCol umnsQ,
Gri dLayout:788
TextArea;1420
TextField: 1465
setConstrainedQ,
PropertyDescriptor:1247
setConst rain tsQ.
Gri dBagLayout:779
setContentsQ,
Cli pboard:275
setCurrentO,
CheckboxGroup. replaced by
setSelectedCheckbox().23-
s INDEX
setCursorQ, Гrame, replaced bx Component. setCursor(); 677 Component;3X4 ComponentPeer;419 setDesignTimeQ, Beans;174 setDimensionsO, CropImageFi 1 ter; 475 ImageConsumer:818 ImageFi 1 ter: 829 Pi xelGrabber; 1 175 ReplicateScaleFilter:1305 setDirectoryО< FileDialog;608 F i 1 eDi alogPeer; 612 setDi splayName О, FeatureDescriptor: 598 setEchoCharO, TextField; 1465 TextrieldPeer; 1470 setEchoCharacte гО * TextField, replaced by setlchoChar(); 1467 TextFi eldPeer. replaced by setEchoCharO:1470 setEditableO* TextComponent;1443 TextComponentPeer:1449 setEditorSearchPath(), PropertyEditorManager:1266 setEnabledO, Component;384 ComponentPeer; 419 Menuitem: 110? MenuItemPeer;1108 setExpertO, FeatureDescriptor;599 setFileO, Fi 1 eDialog; 608 FileDialogPeer; 612 setFil enameFil terO, Fi ToDialog; 609 Fi leDialogPeer; 612 setFontO, Component:385 ComponentPeer; 420 Graphics; 732 MenuComponent;1078 setForegroundO, Component:385 ComponentPeer;420 setFul1BufferUpdates О < MemorylmageSource;1038 se tGui Ava i1able О * Beans; 174 setHelpMenuO, MenuBar: 1065 setHgapO, BorderLayout: 187 CardLayout;219 FlowLayout: 626 Gri dl ayout: 790 setHiddenO, FeatureDescriptor:599 setHintsO, AreaAveragi ngScaleT i1 ter: ImageConsumer: 818 ImageFi 1 ter: 829 Pi xelGrabber: 1175 setHumanPresentableNameO, DataFlavor; 507 setlconlmageO, Frame;678 FramePeer: 684 setlnDefaultEventSetO, EventSetDescriptor:590 setKeyCharO, KeyEvent;949 setKeyCodeO, KeyEvent;949 setLabel(), Button:198 ButtonPeer. 201 Checkbox;230 CheckboxPeer;250 Menuitem;1103 MenuItemPeer;1108 setLayoutO, Contai ner; 454 ScrollPane;1359 setLinelncrementO, Scrol Ibar. replaced bx setUni tlncrementO: 1334 Scrol 1 barPeer: 1342 setLocaleO, Component; 386
1660
setLocationO.
Component: 386
Point:1182
Rectangle: 1300
setMaximumO,
Adjustable: 60
Scrollbar: 1334
setMenuBarO.
Frame: 679
FramePeer: 684
setMinimumO,
Adjustable:60
Scrol Ibar: 1335
setModalO,
Dialog; 516
setModeO,
Fi1 eDialog;609
se t Modi fi ers(),
KeyEvent:950
setMuit i pl eMode О.
List; 11)08
Li st Peer: 1015
setMultipleSelect ionsО.
Li st. replaced by set Mui ti pleModeQ; 1009
ListPeer. replaced by
setMul t ipleModeO; 1015
setNameO.
Component:387
Г eatu reDesc r i ptor;599
MenuComponent:1079
setObjectO.
Customizer: 499
setOri entation O.
Scrol Ibar: 1337
setPagelncrementO,
Scrol Ibar, replaced h>
setBlocklncrement(); 1338
Scrol 1 barPeer: 1342
setPaintModeO.
Graphics;733
setPixel sO,
AreaAveragingScaleFi1 ter:104
CropImageFi 1 ter: 475
ImageConsumer;819
ImageFi 1 ter; 830
PixelGrabber:1176
Repl icateScaleF i Iter: 1 <06
RGBImageFilter; HI9
setPropagationldO.
PropertyChangeEvent:1222
setPropertiesO*
CropImageF i 1 ter; 476
ImageConsumer; 819
ImageFil ter: 830
Pi xelGrabber; 11 76
Repli cateScalеГ i1 ter;1307
setProperty Edi torCl assO.
PropertyDescriptor; 1247
setResizableO,
Dialog:516
DialogPeer; 520
Г rame:680
FramePeer; 684
setRowsO.
GridLayout: 791
TextArea; 1420
setSc roll Posi tionO,
Scroll Pane:1359
Scrol 1 PanePeer:1361
setSeiectedCheckboxО<
CheckboxGroup:237
setSelectionEndО •
TextComponent:1444
setSelectionStartО.
TextComponent:1444
setShortcutO.
Menuitem: 1104
setShortDescriptionO,
FeatureDescriptor: 600
setSizeO,
Component: 387
Dimension: 525
Rectangle:1301
setStateO.
Checkbox: 232
CheckboxMenuItem;245
CheckboxMenuItemPeer: 248
CheckboxPeer; 250
setStubO,
Applet;90
setTextO,
Label;960
Label Peer: 96 >
TextComponent:1445
TextComponentPeer;1450
INDEX
setTitleO<
Di alog:517
DialogPeer; 520
Г rame; 681
FramePeer: 6X4
setUni cast О<•
EventSetDescriptor; 590
setUni tlncrementO,
Adjustable; 60
Sc rol Ibar: 1338
Scrol 1 PanePeer; 1362
setUpdateRect О,
Pai ntEvent; 1161
setValueO,
Adjustable: 61
FeatureDescriptor; 600
PropertyEdi tor: 1260
PropertyEditorSupport:1284
Scrollbar; 1339
Scroll PanePeer: 1362
setVal uesQ,
Scrol Ibar; 1339
Scrol 1 barPeer; 1342
setVgapO,
BorderLayout; 1X7
CardLayout: 219
FlowLayout;627
GridLayout; 791
setVisibleO,
Component:387
ComponentPeer; 420
setVi si ЫeAmountO,
Adjustable;61
Scrol Ibar; 1340
setXORModeO,
Graphi cs;733
SHA message digest algorithm,
JAR support for, Applet; 76
Shape; 1363
getBoundsQ: 1364
shapes,
bounds» Shape.getBoundsQ: 1364
cursor. Figure. Cursor: 477
Shape;1363
Shift key,
InputEvent.SHIFI.MASK; 880
menu shortcut requirement, testing for,
MenuShortcut. usesShi ftModi fi er(); 1115
testing, InputEvent. i sShi ftDownQ; 879
SHIFT-MASK,
Event, replaced by InputEvent. SHIFT-MASK;
567
ActionEvent:39
InputEvent;880
shi ftDownQ,
Event, replaced by
InputEvent. i sShi ftDownQ; 568
shortcuts,
keyboard,
listing, MenuBar. shortcuts Q: 1066
MenuBar .deleteShortcutQ; 1058
MenuBar.getShortcutMenuItemQ;1061
Menuitem.deleteShortcutQ;1092
Menuitem.getShortcutQ; 1096
Menuitem.setshortcutQ:1104
term definition. Menu; 1041
term definition, MenuBar: 1054
term definition. Menuitem: 1089
term definition, MenuShortcut: 1111
Toolkit.getMenuShortcutKeyMaskQ;1491
shortcutsO,
MenuBar: 1066
showQ,
Component, replaced by setVisibleQ: 389
ComponentPeer, replaced by setVisibleQ; 420
CardLayout;220
Dialog: 518
PopupMenu; 1196
PopupMenuPeer; 1200
Window: 1530
showDocumentQ,
AppletContext:96
showing,
components,
ComponentAdapter.componentShownO;
ComponentEvent.COMPONENT-SHOWN; 406
ComponentLi stener.componentShownO:
410
ComponentPeer. setVi sibleQ; 420
dialog.
Dialog, showQ; 518
PopupMenu. showQ: 1196
PopupMenuPeer. showQ; 1200
Window. showQ; 1530
showStatusО,
Applet;90
AppletContext; 97
1662
signature,
accessor methods,
IndexedPropertyDescriptor;856
ProperlyDescr i ptor; 1231
listener support method, conventions,
EventSetDescriptor; 578
specifications, JAR support for. Applet; 76
signature patterns, Introspector; 891
indexed property pattern, Introspector: 892
introspector use. IntrospectionException; 887
is/gei/set pattern. Introspector: 891
multicast event set pattern. Introspector; 892
public method pattern, Introspector; 892
unicast event set pattern. Introspector; 892
SimpleBeanlnfo;1365
getAddi ti onal BeanlnfoO; 1369
getBeanDescri ptorQ; 1370
getDefaultEventIndex О;1370
getDefaultPropertylndexO: 1371
getFventSetDescriptorsO; 1371
getlconO; 1371
getMethodDescriptorsO; 1372
get PropertyDescr iptorsO; 1372
loadlmageO; 1373
simulating,
input events, InputEvent: 872
mouse events, MouseEvent: 1130
SINGLEFRAME,
ImageConsumer:820
SINGLEFRAMEDONE,
ImageConsumer; 820
SINGLEPASS,
ImageConsumer; 821
size,
.See Also resizing
calculating.
Text AreaPeer .getPreferredSizeO; 1424
color map.
IndexColorModel .getMapSizeO; 850
component.
Component.getSi ze():346
Component. setSizeO; 387
dimensions.
Dimension. getSizeO: 523
Di mensi on.setSi ze():525
term definition. Di mens i on; 521
font. Font.getSizeO; 647
frames. Frame: 667
grid hag.
type,
GridBagConstraints.REL ATIVE; 754
GridBagConst raints.REMAINDER:754
as gridbag constraint, term definition,
GridBagConstraints: 738
layout. Gri dBagl ayout. MINSI7E; 777
maximum.
BorderLayout.maximumLayoutSi ze(); 184
CardLayout.maximumLayoutSizeO; 217
Component.getMaximumSi ze();342
Contai ner.getMax imumSi ze();440
GridBagLayout .maximumLayoutSizeO: 776
LayoutManager2.max imumLayoutSi zeО:
981
minimum.
BorderLayout.minimumLayoutSizeО;185
CardLayout.minimumLayoutSizeО;217
Component .getMinimumSizeO; 342
ComponentPeer .getMinimumSizeO: 415
Container.getMi nimumSi ze();440
FlowLayout.minimumLayoutSizeО;625
GridBagLayout.GetMinSize(); 772
GridBagLayout.mi nimumLayoutSizeO; 777
1 ayoutManager.ininimumLayoutSize(): 970
GridLayout .mi nimumLayoutSi zeO: 787
List.getMin imumSize();994
Li stPeer.getMinimumSizeО;1013
Text Area. getMi nimumSizeO; 1411
Tex tAreaPeer .getMinimumSizeO: 1424
TextField. getMi nimumSi zeO; 1461
TextFi eldPeer .getMi nimumSizeO: 1469
pixels.
ColorModel .get Pixel SizeO; 300
ColorModel .pixel_bitsO: 302
point,
as font proper!}. Font; 640
Font.si ze;651
preferred.
BorderLayout.preferredLayoutSi ze():
186
CardLayout.preferredlayoutSizeO: 218
Component.getPreferredSi ze О;345
ComponentPeer.get PreferredSizeO;415
Contai ner.getPreferredSizeO; 441
FlowLayout. preferredLayoutSizeO; 625
GridBagLayout.preferredLayoutSi zeO:
777
Gri dBagLayout.PREFERRFDSIZF;778
s
INDEX
size icotiihim'd}
preferred.
LayoutManager.pref er redLayoutSi zeO:
970
List .getPreferredSizeO- 995
I istPeer.getPreferredSizeO: ЮВ
TextArea.getPreferredSi ze(); 14It
TextAreaPeer.getPreferredSi ze();1424
TextField. getPreferredSizeO: 1462
T extFi e1dPeer.getPrefe rredSi ze 0:1469
rectangles.
Rectangle. getSi zeO:1294
Rectangle.setSize(): 1 И)1
screen. Tool ki t. get ScreenSi ze(): 1493
text fields.
fext Fi eld;1456
I extri eId.getPreferredSi ze(): 1462
viewport.
Scrol1 Pane.getVi ewportSi ze(): 1353
sizeQ.
Component, replaced bv qetSizeO: 390
size.
Font: 651
sliders.
control I! ng. See Adjustable
SOMEBITS,
ImageObserver; 837
sound.
See Л/w audio clip
Toolkit .beepO: 1478
source component.
term definition. MouseLvent: 1132
sources,
event. term definition. AWTEvent: 111
south,
resizing cursor Cursor.S RLSIZF.CURSOR; 484
SOUTH,
BorderLayout:187
Gr i dBagConst rai nt s;756
southeast,
resizing cursor. Cursor. SE RESIZE_CLRSOR: 484
SOUTHEAST.
GridBagConstraints;756
southwest.
resizing cursor. Cursor. SW_RESIZE_CURSOR; 485
SOUTHWEST,
Gri dBagConstrai nts:756
squares.
See rectangles
srccols[ ],
Repli cateSca1eFiIter: 1307
srcHeight,
Repl icateSca 1 eFi Iter: 1108
src rows! 1,
Repl icateScaleFi Iter: 1308
srcWidth,
ReplicateScaleFi1 ter; 1308
startC).
Applet: 90
startGrabbingO.
PixelGrabber; I 177
starting,
applets. Appl et. start О: 90
audio clips. AudioCi ip; 106
startProductionO.
F i 1 teredlmageSource:617
IrragpProducer: 844
MemorylmageSource; 1038
state.
action events.
Act ionFvent.getModifiers(): 17
ActionEvent.paramStri ng0:38
applet. Applet: 75
applet context.
AppletContext.showSt at us 0:97
applets.
Applet.showStatus(): 90
testing. Applet. i sAct i ve(): 87
testing. AppletStub. i sActiveO: 100
button. Button, paramStri ngO: 195
cheek, term definition. CheckboxMenuItem: 239
checkbox.
Checkbox.getState():226
Checkbox. paramStri ngO: 227
Checkbox. setStateO: 732
CheckboxPeer. setStateO: 250
checkbox group.
CheckboxGroup.toStri ng():238
checkbox menu item.
CheckboxMenuItem.getStateO:243
CheckboxMenuItem.paramStringO: 243
CheckboxMenuItem,setStateO:245
CheckboxMenuItemPeer. setStateO: 2 <8
choice. Choice.paramStringO; 259
component events.
ComponentEvent.paramStringO; 407
components.
Component.paramString О;368
1664
Contaiпег: 421
resting for. Component, i sValidO; 353
testing tor. Component. isVisibleO; 353
container, Contai ner. paramStri ngО: 450
container events.
Contai nerEvent.paramStringO; 465
dialog. Dialog.paramStringО: 515
event set. EventSetDescriptor. isln-
DefaultEventSet():589
events, AWTEvent. paramStri ngO; 125
file dialog. FileDialog.paramStringO; 607
flow layout. FlowLayout. toStri ng О; 627
focus events, FocusEvent.paramStringO; 636
graphics context. Graphi cs . toStr i ng О; 735
grid, GridLayout. toStringO: 792
gridbag, GridBagLayout. toStri ngO; 780
images.
Component.checklmageO; 324
Component. imageUpdateO: 349
ComponentPeer.checklmageO;413
ImageConsumer.IMAGEABORTED: 816
ImageConsumer. imageCompleteO; 816
ImageConsumer.IMAGFFRROR; 817
ImageFi Iter. imageCompleteO; 828
ImageObserver, ABORT; 834
ImageObserver.ERROR; 834
ImageObserver.FRAMEBITS; 835
ImageObserver,HEIGHT; 835
ImageObserver.imageUpdateO:
ImageObserver.PROPERTIES; 837
ImageObserver.SOMFBITS; 837
ImageObserver.WIDTH; 837
MediaTracker .getErrorsIDQ; 1023
MediaTracker. imageUpdateO; 1024
MediaTracker.statusAl1(); 1026
PixelGrabber.imageCompleteO; 1173
Tool ki t. checklmageO; 1479
item change type. ItemEvent. DESELECTED: 905
item events.
ItemEvent.paramStri ng();908
L abel . paramStringO; 958
key events. KeyEvent.paramStringO; 948
layout manager.
BorderLayout. inval idateLayoutO: 184
BorderLayout. toStri ngO; 188
CardLayout.i nvalidateLayout();216
CardLayout.toStri ng();220
GridBagLayout.i nvalidateLayout():772
LayoutManager2.invalidateLayout О; 980
lists, string representation. List. paramStri ng О:
1002
menu. Menu. paramString(): 1051
menu component,
MenuComponent.paramStri ng О; 1076
MenuComponent.toSt ri ng О;1079
menu item. Menu Item, paramStri ng 0: 1098
modifier key’*.
retrieving.
InputEvent.getModifiersO: 876
testing.
InputEvent.getModi fi ers(); 876
InputEvent. i sAl tDownO; 878
InputEvent.i sControlDown(): 879
InputEvent.i sMetaDownf): 879
InputEvent. i sShiftDownO; 879
mouse events.
MouseEvent. paramStri ngO: 114?
paint events. PaintEvent. paraTStringO; 1161
pixel. Pi xelGrabber. getStatusO: 1172
scroll pane, string representation,
Scrol 1 Pane. paramStri ngO: 1355
scrol I bar. Scrol 1 bar. paramStringO: 1330
state change property.
event id, ItemEvent. I LEM STATF_CHANGED:
907
ItemEvent;903
ItemEvent .getStateChangeO; 906
string representation, TextArea. paramStr i ng();
1415
text events. TextEvent. paramStri ng(): 1453
text field, string representation.
TextField.pararStringO: 1463
window events,
Wi ndowEvent.paramSt ri ng(): 1545
STATICIMAGEDONE,
ImageConsumer; 821
status,
Sec state
statusO,
PixelGrabber. replaced by getStatusO: 1177
status flags,
frames, ImageConsumer.SINGLEFRAMEDOME; 820
images.
ImageConsumer.IMAGFABORTED: 816
ImageConsumer.IMACFERROR: 817
ImageConsumer,SINC1 FTRAMEDONE; 820
ImageConsumer.STATICIMAGEDONE; 821
ImageObserver.ABORT; 834
/МЖХ
status flags (combined}
images.
ImageObserver.AIL BITS: 834
ImageObserver.ERROR: 834
ImageObserver.HEIGHT: 835
ImageObserver.PROPERTIES: 837
ImageObserver.SOMEBIIS: 837
ImageObserver.WIDTH: 837
MediaTracker.ABORTED: 1020
MediaTracker.COMPLETE: 1022
MediaTracker.FRRORED; 1023
MediaTracker.LOADING: 1025
statusAlT Q,
MediaTracker;1026
statusIDQ'
MediaTracker:1026
stopO.
Applet;91
AudioClip: 107
stopping.
applets. Applet .stopO: 91
audio clipx. AudioCi ip. stopO: 107
streams.
image filler, l-i 1 teredlmageSource: 613
as image-handling architecture.
ImageConsumer; 811
ImageFiIter: 822
output.
writing event listener to.
AWTEventMulticaster.saveO:147
AWT EventMu1ti caster.save-
InternalO: 148
string representation,
color.
Color. toStri ngO: 294
svstern. SystemColor. toStri ng(); 1403
components. Component .toStringO; 390
dimensions. Dimensi on . toStri ng(): 525
events.
AWT Event. paramStringO: 125
AWTEvent. toStri ngO: 126
flow lavoui. Fl owl ayout. toStringO: 627
font metrics. FontMetri cs. toStri ng 0: 666
tents. Font. toSt ri ng О; 651
grid. GridLayout. toStri ng(); 792
inset. Insets. toString(); 886
ke> codes.
KeyEvent.getKeyText(); 938
Table. KeyEvent: 938
lists. Li st. paramStri ng(); 1002
menu shortcut.
MenuShortcut. paramStringO: 111?
MenuShortcut.toString():1115
modifier kevs.
KeyEvent. getKeyModi fiersTextO: 938
point. Point. toStringO; 1182
ptopem value.
PropertуEditor.getAslext 0: 1255
PropertyEdi tor. setAsTextO; 1260
PropertyEdi torSupport.getAsText():
1273
PropertyEdi torSupport.setAs Г ext О:
1281
rectangles. Rectangle.toString(): 1301
scroll pane state. Scrol 1 Pane.paramSt ring();
1355
scrollbars. Scrol Ibar. paramStri ng О; 1 ?H0
state.
Act ionEvent. paramStri ngO: 38
AdjustmentEvent .paramStringO: 68
Borderl ayout. toSt ri ngO: 188
Button. paramSt ri-ng 0: 195
Cardl ayout. toStringO: 220
Checkbox . paramStri ngO; 227
CheckboxGroup.toStri ng0: 238
CheckboxMenuItem.paramSt ri ng(): 243
Choice.paramString(); 259
Component.paramStringO: 368
ComponentEvent. paramSt ri ngO; 407
Container.paramStri ng():450
Contai nerEvent.paramStri ng(): 465
Dialog.paramStringO: 515
Ti1 eDialog.paramStri ngО; 607
FocusFvent.paramString(); 636
Frame.paramString0: 675
Graphics. toStringO; 735
GridBagLayout.toStringO: 780
ItemEvent.paramStri ng():908
KeyEvent.paramStri ng0: 948
Label .paramStringO; 958
Menu.paramStringO: 1051
MenuComponent .paramStringO: 1076
MenuComponent .toStringO: 1079
Menuitem. paramSt ri ngO: 1098
MouseEvent. paramStringO; 1142
Pai ntEvent. paramStri ngO; 1161
TextArea.paramStringO: 1415
TextEvent.paramString 0:1453
1666
TextFi el d. paramStri ngO • 1463
Wi ndowFvent.paramStri ng(): 1545
stri ngFl avor.
DataFlavor: 508
strings,
Sec Also characters: fonts; text
appending to text areas.
TextArea. appendO: >408
con verting to (ran st era hie objects.
StringSelection; 1.174
data flavor. DataFl avor. st ri ngFl avor; 508
as data flavors. DataFlavor; 500. 501
decapitalizing.
Introspector.decapitaiize():899
inserting in text areas.
TextArea. insertO; 1414
lextAreaPeer.insert();1424
painting. Graphi cs . drawSt ri ng(); 712
pixel width. FontMet ri cs. st ringwidth О; 666
retrieving. StringSelection.getl ransfer-
DataQ; 1376
selection, term definition.
StringSelection: 1374
text area replacement.
TextArea. replaceRangeO: 1416
TextAreaPeer. replaceRangeO: 1426
StringSelection;1374
getTransferDataO; 1376
getTransferDataFlavorsO; 1377
IsDataFlavorSupportedO: 1378
lostOwnership(): 1379
StringSelectionO; 1380
Stri ngSelect ionQ,
StringSelection;1380
stringWidth(),
Fontset ri cs: 666
stub,
applet.
Applet. setStubO; 90
AppletStub: 98
term det ini tion. Applet; 90
style.
font.
Font .BOLD; М2
Font.getStyle():647
Font.ITALIC:651
Font.PLAIN: 6S1
Font.style.651
testing. Font. i sBol d(); 649
testing. I ont. i si tai ic (): 649
testing. Font. i sPlai n(): 649
as font propertv. Font; 639
styl e.
Font:651
substituteColorModel(),
RGBTmageF i 1 ter; 1320
supportsCustomEditorО,
PropertyEditor;1261
PropertyEditorSupport;1285
SW_RESIZE_CURSOR,
Frame, replaced bv
Cursor.SW .RESIZE_CURSOR; 6'
Cursor: 485
syncO,
Tool кi t;1495
SystemColor;1381
activeCaption;1389
activeCaptionBorder;1390
activeCaptionText:1392
control; 1392
controlDkShadow: 1394
controlHigh1ight;1394
controlLtHighlight;1394
control Shadow:1394
control Text: 1395
desktop;1395
getRGBQ: 1395
inactiveCaption; 1396
inactiveCaptionBorder; 1396
inactiveCaptionText: I 396
info; 1397
infoText: 1397
menu:1397
Tenulext: 1398
scrol Ibar; 1 398
text: 14(H)
textHighlight:1402
textHighlightText: 1402
textlnactiveText;1402
text Text: 1403
toStringO; 1403
window;1404
wi ndowBorder; 1404
wi ndowText;1404
INDEX
т
target.
Fvent. replaced by AWT Event. getSourceO; 568
tear-off property.
menu.
term definition. Menu: 1040
testing for. Menu . i sTearOff (); 1049
term definitions,
action events,
ActionEvent: 31
AWTEvent: 110
activated, Wi ndowEvent; 1539
active events. Acti veEvent; 44
adapters, event. AWTEvent: 111
adjustable components,
type. AdjustmentEvent: 62
values. Adjustable; 47
values range. Adjustable: 47
adjustable value.
range. Scrol Ibar; 1321
Sc rol Ibar; 1321
adjustment events, value property.
AdjustmentEvent: 62
algorithms, message digest. Applet: 76
alignment.
point. LayoutManager?: 972
properlv. Component; 303
property. LayoutManager?; 972
anchor, gridbag constraint.
GridBagConst rai nts; 738
applets,
Applet: 74
context, Applet: 74
areas.
clipping. Graphi cs; 687
display component. GridBagLayout: 759
text, TextArea; 1405
arrays, indexed property type,
IndexedPropertyDescriptor;854
ascent, font. FontMetrics; 653
attribines, feature descriptor.
FeatureDescriptor: 591
audio clips, AudioClip; 106
AWT (Abstract Window Toolkit), events.
AWT Event; 110
baseline, fonts. FontMetrics: 653
beans,
default event set, Beans; 168
default property. Beans. 168
descriptor. BeanDescriptor: 154
environment. Beans; 168
block, increment adjustable components.
Adjustable; 48
bounding box. Polygon; 1184
bounds. Component; 304
bounds relative. MouseEvent; 1132
button. Button: 1 89
canvas, components; 202
cascading, menus. Menu; 1040
check state. CheckboxMenuItem; 239
checkbox.
components. Checkbox; 221
current selected.: 233
group. Checkbox; 2? 1
choices. Choi ce: 251
clipboard.
Cli pboard;268
name. Cl ipboard; 268
owner. Cl i pboard; 268
system. Clipboard: 268
clipping area, Graphics;687
color.
HSB. Color: 278
model default. ColorModel; 296
model direct. ColorModel; 296
model direct. Di rectColorModel: 527
model index. ColorModel; 295
RGB. Color: 278
component.
alignment point, LayoutManager?: 972
Component:303
display area. Gri dBagLayout: 759
locale. Component; 306
name. Component; 305
consumers.
Image;795
ImageConsumer; 811
consuming,
events. AWT Event; 113
events. InputEvent: 871
container.
alignment point, LayoutManager?: 973
Contai ner: 421
disabled. Contai ner: 422
gridbag. GridBagLayout; 759
inset. Contai ner; 422
valid state. Container; 421
cursors. Cursor: 477
1668
customi/ет. Customizer; 486
data flavor. DataFlavor; 500
default color model, ColorModel; 296
descent, fonts, FontMetrics; 653
descriptors,
beans. BeanDescriptor: 154
event set. EventSetDescriptor: 576
event set explicit. EventSetDescriptor; 577
event set implicit. EventSetDescriptor: 577
feature. FeatureDescriptor: 591
parameter. ParameterDescriptor: 1166
design-time. Beans: 168
dialog.
Dialog: 509
load file, FileDialog:601
modal. Dialog; 509
save file, Fi 1 eDi alog; 601
digest. Applet; 76
dimensions. Dimension; 521
direct color model. ColorModel; 296
directory property, file dialogs. FileDiaiog: 601
disabled property, menu items. Menuitem: 1088
disabling, containers. Container: 42'2
dispatching, event thread. EventQueue: 573
display area, component. GridBagl ayout: 759
double-buffering. Component: 308
drawing surface. Graphics: 685
element type, indexed property,
IndexedPropertyDescriptor; 854
enabled.
menu items. Menu!tem: 1088
property. Component; 305
enabling,
event types: 112
events. AWIFvent; 113
environment, beans. Beans; 168
event.
adapter. AWTEvent; 111
AWTFvent; 110
bean set default: 162
Component:307
consuming, AWTEvent; 11 3
enabling, AWTEvent; 113
listeners. AWTEvent; 111
masks. AWTEvent: 113
queues. EventQueue; 573
semantics of, AWTEvent; 111
sources. AWTEvent; 111
subtypes, AWTEvent: 110
types action. AWTEvent: 111
types item, AWTEvent: 111
event sets.
descriptor. EventSetDescriptor: 576
fcventSetDesc r i ptor: 576
explicit, bean descriptor. BeanDescriptor: 154
feature descriptors. F eatureDescri ptor: 591
features. FeatureDescriptor.getNameO; 591
file property, file dialogs. Fi 1 eDial og: 601
till, gridbag constraint. GridBagConstraints: 738
filters.
file dialog. Fi 1 eDialog; 601
image. Image Г i 1 ter; 822
image. Repl icateScal efi Iter; 1304
replicate scale. Repl i cateScal eFi 1 ter; 1304
flickering. Component; 308
focus,
adapter. FocusAdapter: 628
Component:305
FocusEvent; 631
levels. FocusEvent; 63?
focus events, FocusEvent: 631
font.
ascent. FontMetrics; 653
baseline. FontMetrics: 653
descent. FontMetrics: 653
Font:639
height, FontMetrics; 654
leading. FontMetrics: 653
frames.
Г rame;667
multi frame images.
Image;796
ImageConsumer; 811
MemorylmageSourceQ; 1029
gesture, popup menu, PopupMenu: 1192
graphics context. Graph i cs; 685
gridbag.
anchor, GridBagConstrai nts: 738
container. GridBagLayout; 759
fill. GridBagConstraints; 738
GridBagConstraints;738
insets, GridBagConstraints: 738
internal padding. Gri dBagConstrai nts; 738
position. GridBagConst raints; 738
size. GridBagConstraints; 738
weight. GridBagConstraints: 738
grids. GridLayout; 781
height, fonts, FontMetrics; 654
I
INDEX
term definitions (combined)
Help menus. MenuBar; 1054
hierarchy, component; 303
hints, images. ImageConsumer; 811
HSB (hue. saturation, brightness) color system.
Color; 278
icon image. Frame: 667
iconified. Wi ndowEvent: 1539
image.
filters. ImageFi Iter; 822
hints. ImageConsumer: 811
Image:795
multi-frame. Image: 796
multi frame. ImageConsumer: 811
observer. Image; 795
off screen. Image: 796
produced. Image: 796
properties. Image; 796
implicit, bean descriptor. BeanDescri ptor: 154
implicit, indexed property descriptor.
IndexedPropertyDescriptor:855
increments.
block adjustable components. Adjustable: 48
unit adjustable components. Adjustable: 48
index color model.
ColorModel;295
IndexColorModel;845
indexed properties.
descriptor.
IndexedPropertyDescriptor:854
IndexedPropertyDescriptor; 854
info-tag’*'. SystemColor; 1382
input events, consuming. InputEvent; 871
insets.
containers. Contai ner; 422
gridbag constraint. GridBagConstraints: 738
Insets:881
interface, event listener. AWTLvent; 111
internal padding, gridbag constraint,
GridBagConstraints; 738
introspection.
Beaninfo; 161
IntrospectionException: 887
Introspector; 890
SimpleBeanlnfo: 1365
item events.
AWTFvent: 111
1temEvent:902
items.
property. ItemEvent; 903
selected. Choice; 251
state change property. ItemEvent: 901
key code, virtual. MenuShortcut; Illi
key events, key characters. KeyEvent: 927
key sequence, MenuShortcut: 1111
keyboard.
focus, FocusEvent: 631
key character. KeyEvent: 927
shortcuts. Menu; 1041
shortcuts. MenuBar: 1054
shortcuts. Menultetr; 1089
shortcuts. MenuShortcut: 111!
labels.
Label:955
menu items. Menuitem: 1089
menu. Menu: 1040
layout.
Component:306
gridbag. GridBagLayout; 759
insets. Insets; 881
leading, fonts. FontMetrics: 653
listeners, event. AWTEvent: 111
lists. L i st: 983
load file dialog, FileDialog: 601
locale, component. Component: 306
locks, tree. Component: W
masks, events, AWTEvent; 113
media tracker, event id. MediaTracker; 10]
menu bars.
Help menu. MenuBar; 1054
keyboard shortcuts. MenuBar; 1054
MenuBar; 1054
menu items.
keyboard shortcuts. Menu I tem: 1089
Menuitem; 1088
menus.
Help. MenuBar; 1054
keyboard shortcuts. Menu: 1041
labels. Menu; 1040
Menu:1040
popup. Component: 107
properties. Menu: 1040
shortcuts, MenuShortcut: 1111
tear-off. Menu: 1040
message digest algorithm. Appl et: 76
method descriptors.
explicit. MethodDescri ptor; 1116
1670
implicit, MethodDescri ptor; 1116
MethodDescriptor; 1116
modal dialog. Dialog: 509
mode, file dialogs. FileDiaiog; 601
models,
color default. ColorModel; 296
color direct, ColorModel; 296
color indexed. ColorModel; 295
mouse, adapter, MouseAdapter; 1121
mouse events, clicks count, MouseEvent; 1132
multicasting,
AWTEventMulticaster;128
event sets, EventSetDescriptor; 578
name.
component, Component; 305
human presentable, DataFlavor; 501
native, components. Component; 308
observers, Image: 795
origin, popup menu, PopupMenu: 1192
padding, internal as gridbag constraint.
GridBagConstraints; 738
painting. Component; 308
parameter descriptor,
ParameterDescri ptor; 1166
parent, popup menu, PopupMenu; 1192
peers, Component; 306
point.
alignment, LayoutManager?; 972, 973
Point:1178
polygons,
Graphics.drawPol ygon(): 705
Polygon; 1184
popup menus.
Component:307
gesture. PopupMenu: 1192
PopupMenu; 1192
trigger property. MouseEvent; 1132
trigger property, PopupMenu; 1193
position, gridbag constraint,
GridBagConstraints; 739
posted. EventQueue; 573
producers.
Image:795
image. Image: 795
ImageConsumer: 811
propagation id. PropertyChangeEvent; 1217
properties,
alignment, Component; 304
alignment. LayoutManager?; 972
bean default; 162
bound. PropertyChangeEvent:1215
constrained, PropertyChangeEvent: 1216
di rectory. Fi1eDi a1og: 601
enabled. Component; 305
file. Fi leDi alog: 601
filter, FileDiaiog: 601
images. Image: 796
menu. Menu; 1040
mode. FileDiaiog; 601
popup trigger. MouseEvent; 1132
popup trigger. PopupMenu: 1193
property editor. PropertyFditor; 1248
property editor.
PropertyEditorSupport;1267
resi/able, Dialog; 5(19
sheet, Customi zer: 486
title, Dialog: 509
visible. Component; 305
properties, descriptors.
PropertyDescriptor:1229
queues, event, EventQueue: 573
replicate scale filler,
ReplicateScaleFilter;1304
representation class, DataFlavor: 501
resi/able property.
Dialog; 509
Frame:667
RGB (red. green, blue) color system. Color; 278
save file dialog. Fi leDi alog: 601
scroll panes, ScrollPane; 1343
scroll position. Sc rol 1 Pane; 1344
selected item. Choice; 251
semantic, event, AWTEvent: 111
separator, menu item. Menu I tem; 1089
shortcuts.
keyboard, Menu; 1041
keyboard, MenuBar; 1054
keyboard. Menu!tem; 1089
keyboard, MenuShortcut: 1111
size,
dimensions. Dimension; 521
gridbag constraint, GridBagConstraints; 7.3$
source component. MouseEvent; 1132
sources, event, AWTEvent; 111
state, check, CheckboxMenuItem; 239
strings, selection. Stri ngSelection; 1374
stub, applet. Applet: 90
tear-off property, menu. Menu; 1040
г
INDEX
term definitions (eanumiedf
text areas. TextArea; 1405
text fields. TextField; 1456
threads, event-dispatching, tvent Queue; 573
title.
bar. Frame; 667
propertv. Dialog; 509
tide, Гrame; 667
toolkit. Window; 1519
tree lock. Component; 307
types. adjustable components.
AdjustmentEvent: 62
unicast, event sets. L vent Set Descri ptor; 578
unit, increment adjustable components.
Adjustable: 48
update area. PaintEvent; 1158
values, adjustable range. Ad jus tab 1 e; 47
viewports. Scroll Pane; 1343. 1344
\ inual, key code. MenuShortcut: 1111
v isibilil).
property. Adj ustabl e; 47
property. Component; 305
weight. gridbag constraint.
GridBagConstraints; 739
window.Wi ndow; 1518
text.
.Ser Al\a characters; strings
background color. SystemCol or. text: 14(H)
color.
background. SystemColor. textHighl ight:
1402
component. SystemColor. textText; 1403
highlighted.
SystemColor.textHighlightText;1402
inactive.
SystemColor.textlnact i veText: 1402
SystemColor.control Text; 1395
title bar.
SystemColor.activeCaptionText:1392
window.SystemColor.windowText: 1404
cursor. Cursor.TEXT_CURSOR: 485
data flavor. DataFlavor.pla i nTextFlavor: 507
labels.
Label:955
Label. getTextO; 958
Label.setText();960
Label Peer, set Text O: 963
title bar color.
SystemColor.i nactiveCaptionText;1396
text.
SystemColor: 14(H)
text areas.
appending strings to. I ext Area, append (): 1408
character replacement.
textArea. replaceRangeO; 1416
TextAreaPeer. repl aceRangeQ: 1426
columns.
TextArea .getColumnsO: 1409
TextArea. setColumnsO: 1420
event types fired by. Table. AWTEvent: 115
inserting strings m.
TextArea, insertO; 1414
TextAreaPeer. insertO: 1424
peers.
creating. TextArea. addNotifyO; 1408
TextAreaPeer: 1423
Toolkit.createTextAreaO: I486
rows.
Text Area. getRowsO; 1412
TextArea. setRowsO; 1420
size.
TextArea.getPreferredSizeO: 1411
TextAreaPeer.getMi nimumSizeO:1424
TextAreaPeer.getPreferredSizeO.1424
state, string representation,
TextArea.paramString():1415
term definition. TextArea; 1405
TextArea:1405
text components,
peers.
destroy ing.
TextComponent. removeNot i FyО ; 1439
TextComponentPeer; 1447
TEXT.CURSOR,
Frame, replaced by Cursor. TEXT_CURSOR: 68?
Cursor: 485
TEXT_EVENT_MASK,
AWTEvent;126
text events,
callback methods,
TextLi stener.textValueChangedO:1474
components that fire. Tablr, AWTEvent: 115
dispatching. AWTEventMul ticaster. text-
Val ueChangedO; 148
event id.
TextFvent.TEXT_FIRST: 1453
TextEvent. TEXT.! AST; 1454
TextEvent.TEXT_VALUE_CHANGLD:1454
1672
тпачк for. AWTtvent. TEXT EVENT-MASK: 1 26
Mate. TextEvent. paramStri ngO; T453
TextArea;1406
TextComponent. processEventO: 1438
Text Г ield: 1457
TextListener: 1471
types, hible. AWT Event: 115
text fields,
action events.
TextField.addActionLi stenerO*. 1458
TextFi eld. processActionEventO: 1464
TextField. removeActionLi stenerO; 1465
columns.
TextField: 1456
TextField.getColumnsО;1460
TextField. setColumnsO; 1465
event types fired by. hihle. AWTFvent: 115
events. Text Г i el d. processEventO: 1464
peers.
creating. Text Г ield. addNotifyO; 1450
TextFi eldPeer: 1468
Tool ki t .createTextrieldO: 1487
size,
TextFi eld: 1456
Tex t F i eld.ge tM i n i mumS i ze 0: 1461
TextFi eld.getPreferredSi ze(): 1462
TextFieldPeer.getvinimumSize(); 1469
TextFi el dPeer .getPreferredSizeO: 1469
state, string representation.
TextField.paramString О:1463
term definition. TextField; 1456
TextField;1456
TEXT-FIRST,
TextEvent;1453
TEXT_LAST,
TextEvent;1454
TEXT-VALUE_CHANCED,
TextEvent: 1454
TextArea;1405
addNotifyO; 1408
appendO: 1408
appendTextO- replaced by appendO; 1409
getCol umnsO: 1409
getMinimumSize():1411
getPreferredSizeO; 14П
getRowsf): 14)2
getScrol1barVisi bi 1ity(): 1412
insertO: 1414
insertTextO. replaced by insertO; 1415
mi nimumSizeО. ie placed by
getMi nimumSi zeO: 1415
paramStringO; 1415
preferredSizeO. replaced b\
getPreferredSizeO: 1416
replaceRangeC):1416
repl ace Text О. i eplaced hy
replaceRangeO: 1418
SCROLL BARS.BOTH: 1418
SCR0LLBARS-H0RT70NTAL ONLY: 1419
SCROLLBARS-NONE: 1419
SCROLLBARS-VERTTCAL _ONLY: 1419
setCol urrnsQ: 1420
setRowsQ: 1420
lextAreaO: 1421
TextAreaO,
TextArea:1421
TextAreaPeer;1423
getvinimumSizeO: 1424
getPref erredSi zeO; 1434
insertO; 1424
i nsertText(). replaced hy i nsertO;
minimumsize О, i eplaced by
getMi nimumSizeO; 1425
preferredSizeO, replaced by
getPreferredSizeO; 1425
replaceRangeC);1426
replaceText O. replaced by
replaceRangeC);1426
TextComponent;1427
addTextLi stenerO: 1430
qetCaretPosition(): 1431
qetSelectedText():1432
getSelectionEndQ: 1433
getSelect ionStartO; 1431
getTextQ: 1436
isEditablet):1436
paramStri ngO: 1437
processEvent Q: 1438
processTextEventO: 1438
removeNotifyO: 1439
removeTextLi stenerQ: 14 V;
selectO: 1440
selectAll();1441
setCaretPosition(): 1442
setEditableQ; 1443
setSelectionEndO: 1444
setSelectionStartO; 1444
setTextQ; 1445
т
/Л73/2Х
TextComponentPeer:1447
getCaretPosi tion():1448
getSelectionEnd();1448
getSelectionStart():1448
getlextO; 1448
select():1449
setCaretPosition():1449
setLditablet):1449
setlextO: 1450
TextEvent;1451
paramStringO; 1453
TEXT_FIRST; 1453
TFXT_LAST; 1454
TEXT_VALUE_CHANGED;1454
TextFventC); 1454
TextEventO«
TextEvent;1454
TextField;1456
addActionListenerO; 1458
addNotifyO; 1459
echoCharlsSet():1459
getColumnsO: 1460
getEchoChar();1461
getMinimumSizeO; 1461
getPreferredSizeO; 1462
minimumSizeO. replaced b>
getMinimumSizeO: 1462
paramStringO*. 1463
preferredSizeO. replaced bv
getPreferredSizeO: 1463
processActionEventO: 1464
processFventQ:1464
removeActionl i stenerO; 1465
setColumns();1465
setEchoChar():1465
setEc.hoCharacterO, replaced bv
setFchoCharO; 1467
TextFieldO: 1467
TextFieldO,
TextField: 1467
TextFieldPeer;1468
getMinimumSizeO: 1469
getPreferredSizeO; 1469
minimumSizeO. replaced b\
getMinimumSizeO: 1469
preferredSizeO: 1470
setEchoCharO; 1470
setEchoCharacterO. replaced b_\
setEchoCharO: 1470
textHighlight,
SystemColor:1402
textHighlightText,
SystemColor; 1402
textlnactiveText,
SystemColor:1402
TextListener:1471
textValueChangedO: 1474
textText.
SystemColor:1403
textValueChanged О *
AWTEventMulticaster:148
TextLi stener; 1474
threads.
evenl-di.spalching.
awtFventMulticaster; 12s
term definition. EventQueue; 573
timestamp.
inpul evenb.
InputEvent;87?
InputFvent .getModifiersO: 876
title.
propertv. Frame; 667
setting. FranePeer. setTitleO; 684
term definition. Frame: 667
title bar.
background color.
SystemColor.activcCaption:1389
SystemColor.i nact iveCaption: 1396
term definition. Гrame: 667
text color.
SystemColor.act iveCapt ionText; I3S
title propertv,
dialog.
Di al og.getTitle(): 514
Di a I og.setTi 11 e(); 517
DialogPeer.set 1i 11e():520
frame. Frame.getTi tleО; 674
setting. Гrame. setTi 11 e(): 681
term definition. Dialog; 509
toBackO,
Window; 1531
WindowPeer: 1556
toFrontO.
Window;1531
WindowPeer: 1556
toolkit.
component.
Component .getTool ki t Q: 346
1674
ComponentPeer.getToolki t(); 41?
term definition. Wi ndow: 1519
wmdous. Window.getTool к i t ( ): 15?6
Toolkit; 1475
beepQ: 1478
checklmageO: 1479
createButton(): I4?9
createCanvas():1479
createCheckboxO; 1480
createCheckboxMenuItemO; 1480
createChoi ceO: 1480
createComponentO: 1481
createDialogO; 1481
createFi leDialogO; 1482
createFramef): 1482
createlrrageO: 1482
createLabel(): 1483
createLi stQ: 1483
createMenu():1484
createMenuBar():1484
createMenultemO; 1485
c reatePanel();1485
createPopupMenu(); 1485
createScrol1bar();I486
createScrol1Pane(): 1486
createTextAreaQ; I486)
createTextFieldO; 1487
createWindowО; 1487
getColorMode!О:1487
getDefaultToolкit(); 1488
getFontList(),1488
getFontMetrics(); 1488
getFontPeer();1489
getlmageQ; 1489
getMenuShortcutKeyMaskQ; 1491
getNativeContainer(): 1491
getPrintJobQ; 1491
getPropertyO; 1492
getScreenResol ution(); 1493
getScreenSi zeO; 1493
getSystemClipboardО:1493
getSystemEventQueue0: 1493
getSystemEventQueuelmpl();1494
loadSystemColorsO, 1494
preparelmageO: 1495
sync();1495
top,
alignment. Component. TOP_ALTGNV|=sj [; V)0
^alue, Insets.top; 885
top.
Insets;885
TOP^ALIGNMENT.
Component; 390
TOPDOWNLEFTRIGHT,
ImageConsumer:821
toStringO,
Event, replaced by AWTEvent .toStringO
AWTEvent; 126
Borderl ayout; I 88
CardLayout: 220
CheckboxGroup: 238
Color; 294
Component: 390
Di mens i on; 525
Flow! ayout; 627
Г ont;651
FontMetrics:666
Graphics: 735
Gri dBagLayout;780
Gri dLayout:792
Insets;886
MenuComponent;IO79
MenuShortcut;1115
Point; 1182
Rectangle;1101
SystemColor;1403
TRACK,
AdjustmentEvent; 6)9
tracking,
change. Adjust rent Event-TRACK; 69
image loading,
MediaTracker: 101b
MediaTracker.ABORTED: 1020
MediaTracker.checkAll(): 1021
Medi al racker .checkIDO: 1022
MediaTracker.COMPLFГЕ;1022
MediaTracker.ERRORFD: ]f>23
Medialracker.LOADING; 1025
MediaTracker.removeimage(): 1025
Medialracker.wai t ForAll();1027
MediaTracker .wai tForlDQ Ю2К
Transferable;1496
getTransferDataO; 1501
get 1 ransf erDataFl avorsO: 1502
isDataF lavorSupportedO; 1502
transferable objects,
data flavor use. DataFlavor; 500
и
INDEX
transferFocusQ,
Component; '91
transl ateO,
Event, replaced bv
MouseEvent.translatePoi nt Q:568
Graphics: 735
Point: I 183
Polygon:1190
Rec tanqle: 1301
translatePointO,
MouseEvent: 1142
translating,
mouse event coordinates,
MouseEvent.t ransiatePoi nt Q:1142
origin. Graphi cs .translateO; 735
points. Point. translateO: 1183
polygons. Polygon. t ranslate(): 1190
rectangles. Rec tang 1 e. toStri ng 0: 1 301
transmission.
See 4/sm delivers: streams
pixel. ImageFi 1 ter. resendTopDownLeft-
RightQ;828
request. b\ image consumer.
Fi 1 teredlmageSource.requestTopDown-
1 eftRightResendC); 616
transparency,
pixels. IndexColorModel.getTransparent -
Pi xel():852
traversable,
locus.
Component: 305
Component. transferFocusQ: 591
Container; 423
testing for.
Component. i sFocusT raversabl eQ: 151
testing lor, ComponentPeer.isFocus-
I raversableQ: 416
tree,
lock. Component .getTreeLockQ: 346
tree lock,
term definition. Component; 107
types,
adjustable components, term definition.
AdjustmentEvent: 62
adjustment events.
AdjustmentEvent.getAdjustment T ypeQ;
68
AdjustmentEvent.I RACK: 69
Bl OCK.DFCRFMFNT; 67
BLOCK-INCREMENT: 67
cursor.
Cursor.getI уpe():482
(example list). Cursor; 477
Figure. Cursor:477
event.
AWT event hierarchy organization of.
AWTFvent:110
defining. AWT1 vent; 115
fired b\ AWT components.
'table. AWTEvent: 115
listener. EventSetDescri ptor. get Li stener
TypeQ; 588
и
UndefinedProperty,
Image: 810
unicast,
event set. FventSetDesc ri ptor. i sllni castQ:
589
event set signature pattern. Introspector: 892
event sets.
term definiiion. FventSetDescri ptor; 578
testing. EventSetDescri ptor. set -
UnicastQ: 590
union,
rectangle, calculating. Rectangle, uni on (); 1302
unionO,
Rectangle;1302
unit,
decrement.
AdjustrrentEvent. UNIT, DLCR1 MFNT: 69
increment.
adjustable components, term det innion.
Adjust able: 48
Adjustable.getUni tIncrementQ: 58
Adjustable.setlnitlncrement Q; 60
AdjustmentEvent.UNIT-INCREMENT; 69
UNIT-DECREMENT,
AdjustmentEvent: 69
UNIT-INCREMENT,
AdjustmentEvent:69
UnsupportedFlavorException;1503
UnsupportedFlavorFxcept ionQ: 1504
UnsupportedFlavorExceptionf).
LnsupportedFlavorf.xcept ion; 1504
UP,
Event, replaced b\ KeyEvent .VK UP: 569
1676
updateQ.
Component:391
UPDATE,
PaintEvent;1161
update area,
Pai ntEvent.getUpdateRectQ; 1159
Pai ntEvent. setUpdateRectQ; 1161
term definition. PaintEvent; 1158
updating,
painting compared with. Component; 308
URL (Universal Resource Locator),
code base. Applet.getCodeBaseO; 84
document base, Applet.getDocumentBaseQ: 85
image retrieval from, Toolki t. getlmageO; 1489
useGLI flag,
Vi si bility; 1514
user interface,
Component;303
usesShiftModifierO,
MenuShortcut;1115
V
valid state.
See /1 /vo invalidat i ng
Container; 421
val idateQ,
Component;393
Container; 456
validateTreeQ,
Contai ner; 457
validating,
components, Component.validateQ; 393
container components.
Contai nerPeer.begi nVal idateQ; 469
Contai nerPeer. endValidateO: 469
containers.
Container. validateO; 456
Container. val idateTreeQ; 457
validity,
container, LayoutManager: 964
slate, семing for. Component. i sVal i d(); 353
values,
adjustable.
Ad justable.getMaximumO; 57
Adjustable.getMinimumQ; 57
Adjustable.getValueO; 58
Ad justable. getVi si bleAmountO: 58
Adjustable. setMaximumQ; 60
Adjustable. setMinimumQ; 60
Adjustable.setValue0: 61
Adjustable.setVi s i bl eAmount 0: 61
range, term definition. Adjustable; 47
adjustment events,
AdjustmentEvent.getValueQ: 68
applet parameter. Applet .getParameterQ: 86
bottom. Insets.bottom: 884
change notification. Adjustment-
Event .ADJUSTMENT, VALUE. CHANCED: 66
changed property.
PropertyChangeEvent.getNewValueQ;
1220
PropertyChangeEvent.getOldValueQ:
1220
event id, maximum value for reserved AWT id'v
AUTEvent. RESFRVED_ID_MAX: 126
feature descriptor attributes, default values Table.
FeatureDescriptor: 592
initial, Graphi cs; 687
left. Insets, left; 885
parameter. AppletStub.getParameterQ; 100
pixels, convening to default color model,
ColorModel .getRGBO; 30?
properties,
PropertyChangeEvent.getNewValue Q;
1220
PropertyChangeEvent.getOldValueQ;
1220
PropertyEditor.getJavalni tializa-
tionStri ngQ; 1256
PropertyEdi torSupport.get Java-
Ini ti al i zationStringQ: 1278
PropertyEdi torSupport.getValueQ; I 279
retrieving.
PropertyEdi tor. getTagsQ: 1257
PropertyEditorSupport .getTagsQ:
1278
setting.
PropertyEdi tor.setValueQ; 1260
PropertyFdi torSupport. setValueQ:
1284
string representation.
PropertyEdi tor.getAsTextQ;1255
PropertyEdi tor. set AsTextQ; 1260
PropertyEdi torSupport.getAsText О:
1273
PropertyEdi torSupport.setAsTextO:
1281
V
INDEX
values (continued)
property, property editoi use.
PropertyEditor;1248
right. Insets. ri ght: 885
scrol I bar.
retrieving.
Scrol Ibar .getMax imumO: 1328
Scroll bar. getMi nimumO; 1328
Scrol1 bar.getValue(); 1329
ScrolIbar.setValue(); 1339
Scrol1 bar.setValuesО; 1339
top. Insets. top; 885
vertical,
gap,
Borderl ayout.getVgapO; 183
BorderLayout. setVgapO; 188
CardLayout. getVgapO; 215
Card! ayout. setVgapO; 219
FlowLayout .getVgapO; 624
FlowLayout. setVgapO; 627
GridLayout.getVgapO: 786
GridLayout.setVgapO: 791
gaps. FlowLayout: 618
VERTICAL,
Adjustable: 61
GridBagConstraints;757
Scrol Ibar: 1340
vetoable properties,
PropertyVetoException;1286
vetoabl eChangeO,
VetoableChangeListener;1508
VetoableChangeListener; 1505
vetoableChangeO; 1508
VetoableChangeSupport; 1510
addVetoableChangeLi stenerO: 1511
fi reVetoableChangeO: 151?
removeVetoableChangeLi stenerO: 1513
VetoableChangeSupportО; 1513
VetoableChangeSupport O.
VetoableChangeSupport;1513
vetoing,
events. Vetoabl eChangeSupport: 1510
property changes.
VetoableChangeListener;1505
VetoableChangeL i stener.vetoabl e-
ChangeO; 1508
viewer,
applet, as applet con text. Eij>un\ Appl etContext;
92
viewports,
dimensions,
Scrol1 Pane.getViewportSi ze(); 1353
scroll position.
moving. Sc rol 1 Pane. setScrol 1 -
PositionO; 1359
Scrol 1 Pane.getScrol 1 Posi tionQ; 1352
term definition. Scrol 1 Pane; 1343. 1344
virtual,
key code.
MenuShortcut .getKeyO; 1113
term definition. MenuShortcut; 1111
visibility,
component.
testing for. Component. i sShowi ngO; 353
testing for. Component. i sVi si bleO; 353
components,
ComponentAdapter.componentHiddenО;
399
ComponentAdapte r.componentShownО;
ComponentEvent.COMPONENT-HIDDEN;404
ComponentEvent.COMPONENT-SHOWN; 401
ComponentLi stener.componentHidden():
409
ComponentLi stener.componentShown();
410
ComponentPeer. setVi si ble(); 420
dialog,
Dialog.show(); 518
PopupMenu. showO; 1196
PopupMenuPeer.show();1200
Wi ndow. showO; 1530
lists,
L ist .getVisiblelndexO; 998
Li st .makeVi sibleO; 1000
ListPeer. makeVi sibleO; 1013
property.
term dell nition. Adjustable; 47
term definition. Component; 305
setting. Component. setVi si bl e(); 387
Visibility;1514
avoidi ngGui();1517
dontUseGui Q; 1517
needsGui();1517
okToUseGui O: 1517
VK.UNDEFINED,
KeyEvent; 951
1678
w
W_RESIZE_CURSOR.
Frame. replaced In Cursor.W RESIZE- .CURSOR;
682
Cursor: 485
wait,
cursor. Cursor. WAIT-CURSOR: 485
WAIT_CURSOR,
Frame, replaced by Cursor, WAIT CURSOR; 682
Cursor; 485
waitForAllO,
MediaT racker; 1027
waitForlDO,
'MediaTracker; 1028
waiting,
for image loading,
MediaTracker.waitForAl1();1027
MediaTracker.waitForlDO: 1028
warning message,
Wi ndow:1518
Wi ndow.getWarningStri ngO; 1526
web browser.
as applet context, f-i^ure. AppletContext; 92
weight,
gridbag,
column,
GridBagConstraints.weightx; 757
Gri dBagLayout. columnWeights: 764
GridBagLayout.getLayoutWeightsO: 770
row.
GridBagConstrai nts.weighty: 758
GridBaglayout,rowWeights:779
as grid hag constraint, term definition.
GridBagConstraints;739
weightx,
GridBagConstraints: 757
weighty,
GridBagConstraints: 758
west.
resizing cursor, Cursor.W RESIZE_CURSOR; 485
WEST,
BorderLayout:188
GridBagConstraints; 758
when,
Event, replaced by InputEvent .getWhenQ: 569
white,
Color.white: 294
white,
Color: 294
width,
byte array. Font Met ri cs. bytesWidthO: 658
character array,
FontMetrics .charsWidthO: 659
FontMetrics.charwidth():659
column. GridBagLayout. columnwidths; 766
component,
GridBagConstrai nts.gridwidth;746
dimension, Dimension .width; 526
font. FontMetrics.getwidths(): 664
image. Image.getWidth(); 808
images.
ImageObserver.WIDTH; 837
ReplicateScaleFilter.srcWidth:1308
internal padding,
GridBagConstraints.i padx; 751
pixel, FontMetrics. stringWidthO; 666
pixel buffer. PixelGrabber.getWidth(): 1172
rectangle. Rectangle.width; 1303
scaled images.
ReplicateScaleFiIter.destWidth; 1305
widest character in font,
FontMetrics.getMaxAdvanceC):662
width.
Dimension;526
WIDTH,
ImageObserver:837
width,
Rectangle;1303
Window; 151ft
addNotifyO; 1524
addWi ndowLi stenerO; 1524
di sposeO; 1524
getFocusOwnerO: 1525
getLocaleO: 1526
get Tool к i tO; 1526
getWarningStringO; 1526
packO: 1528
postEventO, replaced by
Component.di spatchEventO: 1528
processEventO; 1529
processW’i ndowEvent О; 1529
removeWindowListenerО:1530
show():1530
toBackO; 1531
toFrontO; 1531
WindowO; 1532
window,
SystemColor: 1404
W INDEX
WindowQ.
Window; 1532
WINDOW—ACTIVATED,
WindowFvent;1545
WINDOW-CLOSED,
WindowEvent:1546
WINDOW-CLOSING,
WindowEvent:1546
WINDOW-DEACTIVATED,
WindowEvent;1547
WINDOW.DE ICONIFIED,
WindowFvent;1547
WINDOW.DEICONIFY,
Event, replaced hy
WindowEvent.WINDOW DLICONIFIED:570
WINDOW—DESTROY,
Event, replaced hy
Wi ndowEvent. WINDOW.Cl OSING: 570
WINDOW_EVENT-MASK,
AWTEvent:127
window events,
adapter class. Wi ndowAdapter; 1535
callback methods,
Wi ndowAdapter.wi ndowDeacti vatedQ:
1537
Wi ndowAdapter.wi ndowDei coni fi ed():
1537
Wi ndowAdapter.wi ndowlconi fi edQ: 1538
wi ndowAdapter,wi ndowOpened(): 1538
Wi ndowLi stener. wi ndowActi vatedQ: 1551
WindowLi stener.windowClosedO: 1551
Windowl istener.windowClosingO; 1552
WindowLi stener.windowOpenedO• 1552
components that fire. Table. AWF Event; 115
dispatching,
AWTEventMu1ticaster,wi ndow
Acti vatedQ; 149
AWI EventMul ticaster. wi ndowClosedO:
149
AWTEventMulticaster.wi ndowClosi ngО -
150
AWTEventMulti caster.wi ndow-
Deacti vatedQ: 150
AWTEventMulti caster.window-
Dei coni fiedO; 151
AWTEventMulti caster.window-
lconi fiedO: 151
AWI EventMul ti caster. wi ndowOpenedO *,
151
mask foi. AWTEvent.WINDOW EVENT.MASK: 127
slate. Wi ndowF vent. paramSt ri ng(): 1545
Window;1519
WINDOW-EXPOSE,
Event, replaced by
Wi ndowEvent . WINDOW.AC 11VATFD: 570
WINDOW-FIRST,
WindowEvent:1547
WINDOW_ICONIFIED,
WindowEvent:1548
WINDOW.ICONIFY,
Event, replaced hy
Wi ndowEvent .WINDOW-TCONIFIED; 57 1
WINDOW-LAST,
WindowEvent:1548
WINDOW-MOVED,
Event, replaced by
ComponentEvent. COMPONENT-MOVED; 571
WINDOW-OPENED,
WindowEvent:1548
window! s),
avoiding. Vi si bi 1 i ty: 1514
background, color. SystemColor .wi ndow: 1404
border.SystemColor. inactiveCaptionBorder:
1396
border color
SystemColor.activeCaptionBorder: 131Н)
color.
border. SystemColor.windowBorder: 1404
text. SystemColor.windowText: 1404
coordinates, Wi ndow: 1519
destroying. Wi ndow. di sposeO: 1524
event types fired by. Table. AWTEvent: 115
even is.
Window.processEventQ: 1529
Wi ndow.processWi ndowEvent(): 1529
focus. Wi ndow.getFocusOwnerО; 1525
locale. Wi ndow.getLocal e(); 1526
moving.
Window. toBackQ; 1531
Window.toFrontQ; 1531
peers.
creating. Window. addNotifyO: 1524
Tool ki t. createWi ndowQ: 1487
WindowPeer; 1555
resizing. Wi ndow, pack 0: 1528
system.
Beans. setGuiAvai lableO: 174
1680
support, testing for.
Beans. isGuiAvailableQ; 173
term definition, Wi ndow. 1518
title bar background color,
SystemColor.acti veCapt ion;1389
title bar color.
SystemColor.inactiveCaption;1}96
SystemColor.inactiveCaptionText;1396
title bar text color.
Sys temColor.acti veCapti onlext:1392
toolkit, Wi ndow.getToolki t О; 1526
windowActivated(),
AWTEventMulticaster; 149
WindowAdapter;1536
WindowListener;1551
WindowAdapter;1535
windowActivated();1536
wi ndowClosedO; 1536
windowClosingО;1536
windowDeactivatedO; 1537
windowDeiconified();1537
windowlconifiedO: 1538
wi ndowOpenedO; 1518
windowBorder,
SystemColor; 1404
wi ndowClosedO,
AWTEventMulticaster;149
Wi ndowAdapter; 1536
WindowListener; 1551
windowClosingО,
AWTEventMulticaster; 150
WindowAdapter; 1536
WindowLi stener; 1552
windowDeactivatedO,
AWTEventMulticaster: 150
Wi ndowAdapter; 1517
WindowListener;1552
wi ndowDei coni fiedO,
AWTEventMulticaster;151
WindowAdapter;1537
WindowListener;1553
WindowEvent;1539
getWindow(): 1545
paramStringO; 1545
WINDOW-ACTIVATED: 145
WINDOW-CLOSED; 1546
WINDOW-CLOSING; 1546
WINDOW-DEACTIVATED’ 1547
WINDOW__DEICONIFIED. 1547
WINDOW-FIRST; 1547
WINDOW-ICONIFIED;1548
WINDOW-LAST; 1548
WINDOW-OPENED; 1548
WindowEventО; 1548
WindowEventО*
WindowEvent:1548
windowlconifiedO*
AWTEventMulticaster; 151
WindowAdapter; 1538
WindowListener:1553
WindowListener;1550
windowActivated0: 1551
wi ndowClosedO; 1551
windowClosingO: 1552
windowDeactivatedO; 1552
windowDeiconifiedО; 155^
windowlconifiedO: 155 i
wi ndowOpenedO: 1554
wi ndowOpenedO,
AWTEventMulticaster; 151
Wi ndowAdapter; 1538
WindowL istener.1554
WindowPeer;1555
toBackO; 1556
toFrontO; 1556
windowText,
SystemColor; 1404
writing,
indexed properties. IndexedPropertyDescrip-
tor. getlndexedWri teMethodO; 865
multicaster. io output stream,
AWTEventMulticaster.save О; 147
AWTEventMulti caster.savelnternalО;
148
X
X,
Event, replaced by MouseEvent. getXQ; 571
Point;1183
Rectangle;1303
x-alignment,
BorderLayout.getLayoutAlignmentXO. 181
CardLayout.getLayoutAlignmentXO; 212
Component. getLayoutAlignmentXO; 336
Container.getLayoutAli gnmentX О; 435
GridBagLayout.getLayoutAl ignmentXO; 767
LayoutManager?. getLayoutAl i gnmentXO;
979
r-coordinate,
cell location for component.
GridBagConstrai nt s.gridx:748
MouseEvent.getXО: П36
point, Point .x: 1183
polygon, Pol ygon. xpoi nts: 1190
rectangle. Rectangle.x: 1303
xor mode,
graphics context. Graphics: 686
setting. Graphics.setPai ntModeО: 733
xpoi nts,
Polygon;1190
Y
y,
Event, replaced b> MouseEvent. getYQ: 572
Poi nt;1183
Rectangle;1303
y~a I ignment,
BorderLayout.getLayoutAli gnmentYO; 181
CardLayout.getLayoutAlignmentYQ:212
Component.getLayoutAlignmentY(): 336
Contai ner.getLayoutAli gnmentY 0:436
GridBagLayout.getl ayoutAlignmentY();767
LayoutManager2.getLayoutAlignmentYO;
980
y-cuord inate,
cell locaiion for component
GridBagConstraints.gridy; 749
MouseEvent. getYQ; 1137
point, Poi nt. у; II83
polygon. Polygon.ypoints: 1110
rectangle. Rectangle, y; 1303
yellow,
Color.ye 1 low;294
yel 1 ow.
Color; 294
ypoi nts,
Polygon; ! 110
z
z-ordering,
Contai ner:423
native \s lightweight components. Component; 369
native vs lightweight containers. Container: 423
1682
Contents
List of Figures.................................................xiii
List of Tables.................................................xxiii
Preface..........................................................xxv
Package Overviews
java, applet.......................................................I
java.awt...........................................................3
java.awt.datatransfer.............................................13
java.awt.event ...................................................15
java.awt.image ...................................................19
java.awt.peer.....................................................22
java.beans........................................................26
Alphabetical Reference of Classes
ActionEvent ..................................................... 31
ActionListener ...................................................41
ActiveEvent ......................................................44
Adjustable........................................................47
AdjustmentEvent ..................................................62
AdjustmentListener ...............................................70
Applet............................................................74
AppletContext.....................................................92
AppletStub........................................................98
AreaAveragingScaleFilter ........................................101
AudioClip........................................................106
A WTError108
AWTEvent.........................................................110
AWTEvcntMulticaster..............................................128
AWTException.....................................................153
BeanDescriptor...................................................154
Beaninfo.........................................................161
Beans ...........................................................168
BorderLayout................................................................ 176
Button...................................................................... 189
ButtonPeer...................................................................200
Canvas ......................................................................202
CanvasPeer...................................................................207
CardLayout ..................................................................208
Checkbox.....................................................................221
CheckboxGroup................................................................233
CheckboxMenuItem.............................................................239
CheckboxMenuItemPeer.........................................................247
CheckboxPeer ................................................................249
Choice ......................................................................251
ChoicePeer...................................................................265
Clipboard....................................................................268
ClipboardOw ner..............................................................276
Color .......................................................................278
ColorModel ..................................................................295
Component....................................................................$03
ComponentAdapter ............................................................396
ComponentEvent...............................................................401
ComponentListener ...........................................................408
ComponentPeer.............................................................. 411
Container....................................................................42)
ContainerAdapter.............................................................458
ContainerEvent ..............................................................460
Contai ncrListencr...........................................................466
Containerpeer................................................................468
CropImageFilter..............................................................471
Cursor.......................................................................477
Customizer...................................................................486
DataFlavor...................................................................500
Dialog.......................................................................509
DialogPeer...................................................................519
Dimension ...................................................................521
DirectColorModel ............................................................527
Event .......................................................................534
EventQueue ..................................................................573
EventSetDescriptor ..........................................................576
Cont
FeatureDescriptor...............................................................591
FileDialog......................................................................601
FileDialogPeer..................................................................611
FilteredlmageSource.............................................................613
HowLayout.......................................................................61К
FocusAdapter....................................................................628
FocusEvent......................................................................631
FocusListener...................................................................637
Font............................................................................639
FontPeer........................................................................652
FontMetrics.....................................................................653
Frame ..........................................................................667
Frame Peer......................................................................683
Graphics........................................................................685
GridBagConstraints .............................................................738
GridBagLayout...................................................................759
GridLayout......................................................................781
IllegalComponentStateException..................................................793
Image ..........................................................................795
ImageConsumer...................................................................811
ImageFi Iter....................................................................822
ImageObserver...................................................................831
Image Producer..................................................................838
IndexColorModel.................................................................845
IndexedPropertyDescri ptor......................................................854
InputEvent .....................................................................871
Insets..........................................................................881
IntrospectionException..........................................................887
Introspector...................................................................89(1
ItemEvent.......................................................................902
ItemListener....................................................................909
ItemSelectable ............................................................... 914
KeyAdapter......................................................................919
KeyEvent .......................................................................926
Key Li stener ..................................................................952
Label......................................................................... 955
Labelpeer.......................................................................962
LayoutManager................................................................. 964
LayoutManager?..................................................................972
Light weigh! Peer.............................................................982
List..........................................................................983
Lis! Peer .................................................................. 1010
MediaTracker................................................................ 1016
Memory Image Source......................................................... 1029
Menu ....................................................................... 1040
MenuBar .................................................................... 1054
MenuBarPeer................................................................. 1067
MenuComponent............................................................... 1069
MenuComponentPeer .......................................................... 1080
MenuContainer .............................................................. 1082
Menuitem.................................................................... 1088
MenuItemPeer................................................................ 1107
MenuPeer.................................................................... 1109
MenuShortcut................................................................ 1II1
MethodDescriptor ......................................................... 1116
Mouse/\dapier............................................................... 1121
MouseEvent.................................................................. 1129
MouseLi stener.............................................................. 1143
MouseMotionAdapter ......................................................... 1149
MouseMotionListener......................................................... 1154
PaintEvent ................................................................. 1158
Panel....................................................................... 1162
Panel Peer.................................................................. 1165
Parameter! Jescriptor ...................................................... 1166
PixelGrabber ............................................................... 1167
Point....................................................................... 1178
Polygon .................................................................... 1184
PopupMenu .................................................................. 1192
PopupMenuPeer............................................................... 1199
PrintGraphics............................................................... 1201
PrintJob ................................................................... 1203
Property Changed: vent ..................................................... 1215
PropertyChangeListencr ..................................................... 1223
PropertyChangeSupport....................................................... 1225
PropertyDescriptor.......................................................... 1229
PropcrtyEdilor.............................................................. 1248
Property Ed itorManager..................................................... 1262
PropertyEditorSupport....................................................... 1267
PropertyVetoException ...................................................... 1286
voni
Rectangle .....................................................................1288
ReplicateScaleFilter...........................................................1304
RGBImageFilter.................................................................1309
Scrollbar......................................................................1321
ScrollbarPeer .................................................................1341
ScrollPane.....................................................................1343
ScrollPanePeer.................................................................J 360
Shape .........................................................................1363
SimpleBeanlnfo ................................................................1365
StringSelection................................................................1374
SystemColor....................................................................1381
TextArea.......................................................................1405
TextAreaPeer ..................................................................1423
TextComponent .................................................................1427
TextComponentPecr..............................................................1447
TextEvent......................................................................1451
TextField......................................................................1456
TextFieldPeer..................................................................1468
Text Listener..................................................................1471
Toolkit .......................................................................1475
Transferable ..................................................................1496
UnsupportedFlavorException.....................................................1503
VetoableChangeListener ........................................................1505
VetoableChangeSuppon...........................................................1510
Visibility.....................................................................1514
Window ........................................................................1518
Window Adapter.................................................................1535
Window Event...................................................................1539
WindowListener.................................................................1550
WindowPeer.....................................................................1555
Index..........................................................................1557