Chapter 14
Java API Reference
CONTENTS
This reference presents and explains the entire Java API. The
API, which stands for Application
Programming Interfaces,
is a set of classes and interfaces that outline a set of platform-independent
behaviors that establish the foundation of all Java applets and
applications. Although any program depends on the strategies of
the programmer, these classes and interfaces are the tools that
all programmers use in creating Java applications.
The java.applet class provides
you with only one class and three interfaces, but it is one of
the most used packages because it lays the foundation for all
applets. The Applet class
is most important because it is required when you create an applet.
Also useful is the AppletContext
interface, which is employed to interact with the browser.
Classes
Applet Extends java.awt.Panel. This class is the
heart of every Java applet. Derived from the java.awt.Pannel
class, the Applet class possesses
all the methods found in the java.awt.Container
class that enable you to create a powerful and appealing user
interface. Every applet that you create must extend the
Applet class.
As stated above, in order to create a Java applet, you must create
a class that extends the java.applet.Applet
class. However, to run the applet, you must embed it in an HTML
page. This is done with the <APPLET>
tag, which must specify the name, height, and width of the applet.
You may also specify additional parameters: information that the
applet can obtain. The HTML page shown in specifies two parameters:
NAME and KEY
(see Listing 14.1).
Listing 14.1 Sample HTML Page for an Applet
<HEAD>
<TITLE>Applet Example</TITLE>
<BODY>
This text is above the applet.<P>
<applet code="examp.class" width=500 height=100 >
<param name=NAME value="Mike">
<param name=KEY value = "j">
</applet>
<P>This text is below the applet.<P>
</BODY>
This document will load the examp
class that will be stored in a file named examp.class.
Listing 14.2 is the complete source code for that class.
Listing 14.2 Sample Applet
import java.applet.Applet;
import java.awt.*;
public class ExampleApplet extends Applet
{
String userName;
char favoriteKey;
int appletWidth, appletHeight, fontHeight;
Font fontToUse;
FontMetrics fm;
/* This class will be called before the applet
is
started. As a result,
it can be used to perform
preparatory operations. */
public void init() {
userName = new String();// creates
a new, empty string
appletWidth = this.size().width
- 2; // uses
//Component.size
()
appletHeight = this.size().height - 2;
fontToUse = new Font("TimesRoman",
Font.PLAIN, 20);
//
creates a new Font object
fm = getFontMetrics(fontToUse);
// obtains the
//FontMetrics
for the font
fontHeight = fm.getMaxAscent();
/* maximum size that
one
of the font's characters may
extend
upwards */
getInfo();
// gets info from HTML tag }
/* This method uses the getParameter() method
to obtain
the information
passed to the applet in the applet
tag. This
method assumes that there will be two
tags, titled "NAME"
and "KEY" in the HTML page. */
void getInfo() {
userName = getParameter("NAME");
favoriteKey = getParameter("KEY").charAt(0);
// we want the first character
in the returned string
}
/* This method is automatically
called whenever the
mouse is
depressed within the applet */
public boolean mouseDown(Event evt, int x, int
y) {
showStatus("Mouse Click at
("+x+","+y+")" );
return true;
}
/* This method is automatically
called whenever a key is
depressed within
the applet */
public boolean keyDown(Event evt, int key) {
if (key == favoriteKey) {
showStatus("You pressed
" + favoriteKey +
",
my favorite key!");
return true;
}
return false;
}
/* This method is automatically called whenever
the
applet needs to be drawn */
public void paint(Graphics g) {
g.setFont(fontToUse);
g.drawRect(0,0,appletWidth, appletHeight);
g.drawString("Hello " + userName
+
". Welcome
to the world of Java!",10,fontHeight + 3);
}
}
The classes used in this example, Font,
FontMetrics, and Graphics,
are explained in the AWT package section. However, you should
note that of the five methods in this applet, only one, getInfo(),
is explicitly called by the applet. The others will be called
by either the browser or by one of the classes on which the java.applet.Applet
class is based. Methods, such as init(),
are called by the browser itself at particular times. Methods,
including keyDown() and mouseDown(),
are called to handle specific user events within the applet. More
such methods can be found in the java.awt.Component
class.
Methods
- void destroy( )
This method may be used to perform any cleanup necessary after
execution of the applet. It is empty by default; thus, you must
override it if you want the method to do anything. The method
is automatically called by the browser when the applet is stopped.
- AppletContext getAppletContext( )
Returns the AppletContext
of the applet. This is the browser (i.e., Netscape or Appletviewer)
used to view the applet.
- String getAppletInfo( )
This can be used to return such information as version number
or the author's name. If you do not override it, a null string
is returned.
- AudioClip getAudioClip(URL url)
Loads the audio clip residing at the specified URL.
- AudioClip getAudioClip(URL url, String clipname)
Loads an audio clip with the specified URL and name.
- URL getCodeBase( )
Returns the URL of the applet, and is usually the URL of the
page containing the current applet without the document name.
- URL getDocumentBase( )
Returns the URL of the page on which the current applet resides.
- Image getImage(URL url)
Loads the specified image, which may not be an immediate process
inasmuch as it may take some time to actually load the image.
- Image getImage(URL url, String imagename)
Loads the specified image, which may not be an immediate process
inasmuch as it may take some time to actually load the image.
- String getParameter(String labelname)
Returns the parameter specified in the HTML page.
- String[ ][ ] getParameterInfo( )
Returns all parameters from the HTML page.
- void init( )
This method may be used to perform some preparatory actions.
While the method is naturally empty, this method is usually used
to perform preparatory tasks-such as to create streams and to
load information. This method is always called by the browser.
- boolean isActive( )
Returns true if the applet
is currently running.
- void play(URL url)
Plays the specified audio clip.
- void play(URL url, String audioClipName)
Plays the specified audio clip.
- void resize(int width, int height)
Resizes the applet to the specified dimensions. In Netscape,
this method has no effect. To set the size of an applet, use the
width and height
parameters in the applet HTML tag.
- void resize(Dimension d)
Resizes the applet to the specified dimensions. In Netscape,
this method has no effect. To set the size of an applet, use the
width and height
parameters in the applet HTML tag.
- void setStub(AppletStub stub)
Sets the AppletStub of
the applet. This task is performed automatically by the browser.
Therefore, you should have no reason to use this method.
- void showStatus(String msg)
Displays a message at the bottom of the browser. This is usually
the simplest way to communicate with the user.
- void start( )
By overriding this method, you can perform some tasks immediately
after the applet is created. This method is automatically called
by the runtime system.
- void stop( )
By overriding this method, you can perform tasks once the
applet is stopped. This method is automatically called by the
runtime system. It is not used often, but can be harnessed to
perform some cleanup operations.
Interfaces
AppletContext. The AppletContext
interface provides you with a means to interact with the browser.
Every applet can obtain its AppletContext
through the getAppletContext( )
method. Although the inner workings of the AppletContext
depends on the browser, you are guaranteed that it will be capable
of performing the following tasks.
See Listing 14.18, "Runnable Example-HTML,"
p. 550
Methods
- Applet getApplet(String name)
Returns the applet with the given name.
- Enumeration getApplets( )
Returns a set of all applets on the given page.
- AudioClip getAudioClip(URL url)
Returns the specified audio clip.
- Image getImage(URL url)
Returns the specified image.
- void showDocument(URL url)
Shows the specified document in the current context.
- void showDocument(URL url, String target)
Requests that the browser show the specified document in a
particular location-either a browser window or a Netscape frame.
Options for target are shown
in the following table:
| Value | Document Display |
| "_self"
| Current Frame. |
| "_parent"
| Parent Frame. |
| "_top"
| Top-most Frame. |
| "_blank"
| In a new and unnamed browser window. |
| "aNameofYourChoice"
| Creates a new browser window with the specified name. You may later display other documents in this window by using the same name as the target.
|
- void showStatus(String mesg)
Displays a string at the bottom of the browser.
AppletStub. The AppletStub
interface is primarily used when creating an applet viewer. However,
it is used by the Applet
class to retrieve information and interact with the browser. Because
all of this interaction is already handled by the Applet
class, there is generally no need for you to use the AppletStub
class.
Methods
- void appletResize(int width, int height)
This method is called when the applet wants to be resized.
- AppletContext getAppletContext( )
Returns the applet context.
- URL getCodeBase( )
Returns the base URL without the document name.
- URL getDocumentBase( )
Returns the current URL.
- String getParameter(String name)
Returns the specified parameter.
- boolean isActive( )
Returns true whenever
the applet is running.
AudioClip. The AudioClip
interface is a high-level representation of the behavior of an
audio clip. While interface objects cannot be created, objects
that extend the AudioClip
interface may be handled through this interface. Consequently,
while the getAudioClip()
in the Applet class returns
an object we know little about, knowing that it implements the
AudioClip interface enables
us to make use of the loop(),
play(), and stop()
methods.
Methods
- void loop( )
Begins to play the audio clip and loops to the beginning upon
reaching the end of the clip.
- void play( )
Plays the audio clip.
- void stop( )
Halts playing of the audio clip.
The Java Abstract Window Toolkit (AWT) consists of resources to
enable you to create rich, attractive, and useful interfaces in
your applets. Possessing managing tools, such as LayoutManager
and Container, the AWT also
has several concrete interactive tools, such as Button
and TextField.
Classes
BorderLayout Implements LayoutManager. A BorderLayout
is a class that may be used for designing and managing components
within your user interface. A BorderLayout
is a landscape onto which you may place up to five components.
Components may be anchored by specifying either "North,"
"South," "East," "West," or "Center"
when adding the component to the layout.
Methods
- BorderLayout( )
Creates a new BorderLayout
with a hgap and a vgap
of 0. The hgap and vgap
fields determine the amount of padding between components in the
layout.
- BorderLayout(int hgap, int vgap)
Creates a new BorderLayout
with the specified hgap and
vgap. The hgap
and vgap fields determine
the amount of padding between components in the layout.
- void addLayoutComponent(String location, Component comp)
Adds a component to the layout at the specified location.
Options for location are
as follows:
"North"
"South"
"West"
"East"
"Center"
- void layoutContainer(Container target)
Reshapes the components in the target
container in accordance with a BorderLayout.
- Dimension minimumLayoutSize(Container target)
Returns the minimum size necessary for the components in the
specified container. This value is based on the minimum sizes
of the components added to the amount of spacing for the container.
- Dimension preferredLayoutSize(Container target)
Returns the "preferred size" of the container. This
is based on the preferred size of each component as well as the
amount of spacing specified.
- void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
- String toString( )
Returns a string detailing the hgap
and the vgap.
Button Extends Component. The Button
class creates a standard button for use in your interfaces. A
Button is a standard component
that may be added to any of the layout manager classes. The label
string for each button serves not only to identify the button
to the user, but to the programmer as well. Whenever a button
is depressed, an ACTION_EVENT
will be posted to the container in which the button resides. To
distinguish between the various buttons on the screen, the Event
will contain an arg string
containing the label of the button that was depressed.
See Listing 14.6, "GridbagLayout
Example," p. 446
Methods
- Button( )
Creates an unlabeled button.
- Button(String label)
Creates a button with the specified label. This will also
serve as the arg value in
the Event created when the
button is depressed.
- synchronized void addNotify( )
Creates a peer for the button.
- String getLabel( )
Returns the label of the button.
- protected String paramString( )
Returns a string specifying the label of the button.
- void setLabel(String label)
Sets the label of the button.
Canvas Extends Component. The Canvas
class provides you with a simple background on which you can build.
The Canvas class establishes
a peer and paints a simple gray background. However, if you choose
to extend the Canvas class,
you are able to create your own custom components-something very
useful.
Methods
- Canvas( )
Creates a new canvas.
- synchronized void addNotify( )
Creates the canvas's peer.
- void paint(Graphics g)
Paints the canvas. By default, this method simply paints a
blank background having the same color as the background.
CardLayout Implements LayoutManager. A CardLayout
enables you to scroll through a series of components. Generally,
the "cards" are containers-each with a specific theme.
Each card is referred to by a title and is furthermore sequentially
indexed. Therefore, you are to scroll through the cards either
in order or by selecting a specific card by name.
The code in Listing 14.3 was used to create the applet. As you
can see, the applet uses a Choice
component to enable the user to scroll through the various cards.
Listing 14.3 CardLayout
Example Source Code
import java.awt.*;
import java.applet.Applet;
public class CardLayoutExample extends Applet {
Frame sidecard;
private static String LINKS = "Links from
Here";
private static String ORDERFORM = "Order
Form";
public CardLayoutExample() {
Choice selector = new Choice(); //
creates a selector
//
on the original page
selector.addItem(LINKS);
selector.addItem(ORDERFORM);
add(selector);
sidecard = new Frame("Multi-Purpose
Window");
//
creates the side frame
sidecard.setLayout(new CardLayout());
Panel p = new Panel(); // create
the individual panels
p.add(new Button("Our Homepage"));
p.add(new Button("Other Products")
);
sidecard.add(LINKS, p);
p = new Panel();
p.setLayout( new FlowLayout() );
p.add(new TextField("Name",
20));
p.add(new TextField("Address",
50) );
p.add(new TextField("Phone",
20) );
p.add(new Button("Order") );
sidecard.add(ORDERFORM, p);
sidecard.show(); //
shows the side frame
}
public boolean action(Event evt, Object arg)
{
CardLayout display;
if (evt.target instanceof Choice) { /*
if the event
occurred in a Choice */
display = (CardLayout)sidecard.getLayout();
//
obtains control of the frame
display.show(sidecard,arg.toString());
// displays the
panel with the corresponding title
return true;
}
return false;
}
public synchronized boolean handleEvent(Event evt)
{
if (evt.id == Event.WINDOW_DESTROY) {
this.hide();
return
true;
}
return super.handleEvent(evt);
}
}
Methods
- CardLayout( )
Creates a new CardLayout
manager.
- CardLayout(int hgap, int vgap)
Creates a new CardLayout
manager with the specified hgap
and vgap-the spacing between
components.
- void addLayoutComponent(String name, Component comp)
Adds the component to the container with the specified name.
- void first(Container parent)
Displays the first card in the layout.
- void last(Container parent)
Displays the last card in the layout.
- void layoutContainer(Container parent)
Arranges the parent container
based on the CardLayout parameters.
- Dimension minimumLayoutSize(Container parent)
Returns the minimum size necessary for this layout. This value
is based on the minimum size of the parameters.
- void next(Container parent)
Displays the next card.
- Dimension preferredLayoutSize(Container parent)
Returns the preferred size of the layout in the parent
container. This is based on the preferred size of the components
in the container.
- void previous(Container parent)
Displays the previous card.
- void removeLayoutComponen(Component comp)
Removes the specified component from the layout.
- void show(Container parent, String cardname)
Shows the specified card in the parent container.
- String toString( )
Returns a string detailing the hgap
and vgap values for this
layout.
Checkbox Extends Component. A checkbox provides you with
an easy way of obtaining input from the user. It resembles a standard
checkbox: a text label and a box on the client's machine.
See "CheckboxGroup," p. 416
See "CheckboxMenuItem Extends MenuItem,"
p. 416
See Listing 14.6, "GridbagLayout Example,"
p. 446
Methods
- Checkbox( )
Creates an non-labeled checkbox.
- Checkbox(String label)
Creates a checkbox with the specified label.
- Checkbox(String label, CheckboxGroup group, boolean state)
Creates a checkbox with the specified label and places it
in a CheckboxGroup. The state
parameter determines whether or not it is initially checked.
- synchronized void addNotify( )
Creates the peer of the checkbox
- CheckboxGroup getCheckboxGroup( )
Returns the CheckboxGroup
of which the current checkbox is a member.
- String getLabel( )
Returns the label of the checkbox.
- boolean getState( )
Returns the state of the checkbox (true
if checked, false if not).
- protected String paramString( )
Returns a string detailing the checkbox's parameters-such
as its status and location.
- void setCheckboxGroup(CheckboxGroup g)
Sets the CheckboxGroup
for the current checkbox.
- void setLabel(String label)
Sets the label of the checkbox.
- void setState(boolean state)
Sets the state of the checkbox (checked or unchecked).
CheckboxGroup. By employing a CheckboxGroup,
you are able to create a radio button group: a set of Checkboxes,
only one of which can be selected at a time. This is useful for
exclusive choices (the user can only choose one of the options),
such as "How do you want to pay for your purchase?"
To employ a CheckboxGroup,
first create and layout your checkboxes as you normally would.
Then assign them to the CheckboxGroup
by using the setCheckboxGroup( )
method.
See "Checkbox Extends Component,"
p. 415
Methods
- CheckboxGroup( )
Creates a new Checkbox group.
- Checkbox getCurrent( )
Returns the currently selected checkbox.
- synchronized void setCurrent(Checkbox box)
Sets the specified checkbox to be the selected checkbox.
- String toString( )
Returns a string detailing the currently selected checkbox.
CheckboxMenuItem Extends MenuItem. A CheckboxMenuItem
is a MenuItem whose status
may be toggled. Placed within a Menu
column, a CheckboxMenuItem
will display a check mark when selected.
See "Checkbox Extends Component,"
p. 415
Methods
- CheckboxMenuItem(String label)
Creates a new checkbox menu item with the specified label.
- synchronized void addNotify( )
Creates the checkbox menu item's peer.
- boolean getState( )
Returns the current state of the checkbox.
- String paramString( )
Returns a string detailing the checkbox's value.
- void setState(boolean state)
Sets the state of the checkbox.
Choice Extends Component. The Choice
component creates a standard pop-up menu from which the user can
select one item.
See Listing 14.6, "GridbagLayout
Example," p. 446
Methods
- Choice( )
Creates a new choice component.
- synchronized void addItem(String label)
Adds a selection to the choice listing with the specified
label.
- synchronized void addNotify( )
Creates the choice's peer.
- int countItems( )
Returns the number of items currently existing in the choice's
listing.
- String getItem(int pos)
Returns the label of the choice in the specified position
in the choice list.
- int getSelectedIndex( )
Returns the index of the currently selected item.
- String getSelectedItem( )
Returns the label of the currently selected item.
- protected String paramString( )
Returns a string including the label of the currently selected
item.
- void select(String label)
Selects the item with the specified label.
- synchronized void select(int pos)
Selects the item at the specified position.
Final Color. The Color
class provides you with the various colors that you can employ
in your programs as well as the capability to create and customize
your own colors.
See "Abstract Graphics," p.
438
Fields
- final static Color black
- final static Color blue
- final static Color cyan
- final static Color darkGray
- final static Color gray
- final static Color green
- final static Color light gray
- final static Color magenta
- final static Color orange
- final static Color pink
- final static Color red
- final static Color white
- final static Color yellow
Methods
- Color(int rgb)
Creates a new color represented by the passed integer. Bits
0-7 represent the blue component, 8-15 the green component, and
16-23 the red component.
- Color(float red_value, float green_value, float blue_value)
Creates a new color with the specified values ranging from
0 to 1.0.
- Color(int red_value, int green_value, int blue_value)
Creates a new color with the specified values ranging from
0 to 255.
- Color brighter( )
Returns a brighter version of the current color by dividing
each integral component of the color by 0.7.
- Color darker( )
Returns a darker version of the current color by multiplying
each integral component of the color by 0.7.
- boolean equals(Object otherObject)
Compares a Color to another
Object. They can only be
equal if the other object is also a Color.
- int getBlue( )
Returns the blue component of the color.
- static Color getColor(String name)
Returns a Color assuming that name
refers to a color specified in the system properties. If the property
is not found, the method returns null.
- static Color getColor(String name, int default)
Returns a Color assuming that name
refers to a color specified in the system properties. If the property
is not found, the method returns the color represented by default.
- static Color getColor(String name, Color default)
Returns a Color assuming that name
refers to a color specified in the system properties. If the property
is not found, the method returns default.
- int getGreen( )
Returns the green component of the color.
- static Color getHSBColor(float hue, float saturation, float
brightness)
Creates a Color based
on the specified HSB (hue, saturation, and brightness) values
ranging from 0.0 to 1.0
- int getRed( )
Returns the red component of the current color.
- int getRGB( )
Returns the rgb value of the current color as one integer.
Bits 0-7 are blue, 8-15 are green, and 16-23 are red.
- int hashCode( )
Returns the hashcode
for the current color. This value is the same as the integer returned
from getRGB().
- static int HSBtoRGB(float hue, float saturation, float
brightness)
Creates a single integer representation of the color defined
by the specified hue, saturation, and brightness. In the integer,
bits 0-7 are blue, 8-15 are green, and 16-23 are red.
- static float[ ] RGBtoHSB(int red, int green, int blue,
float hsbvals[ ])
Returns hue, saturation, and brightness values for the color
defined by the red, green, and blue values. In the array, hsbvals[0]
= hue, hsbvals[1] = saturation,
and hsbvals[2] = brightness.
- String toString( )
Returns a string, including the red, green, and blue components
of the color.
Abstract Component Implements ImageObserver.
The Component class is the
basis for the various components in the AWT that may be employed,
such as Button and Scrollbar.
While the specific components posses methods pertinent to their
function, the Component class
provides them with a myriad of methods designed to facilitate
a base functionality-such as event handling.
You will also note that the Component
class relies heavily on the java.awt.peer
classes for much of its implementation because the system commands
to create a component on UNIX machines are different from those
to create the component on Windows-based machines. Instead of
directly interacting with these methods, the peers serve as intermediaries,
translating your Java-based code into platform-dependent commands.
Methods
- boolean action(Event evt, Object what)
Called by handleEvent( )
when an action occurs in the component. This method should be
overridden if you want to gain more control over events occurring
in components or containers. It returns true
if the event is handled successfully.
- void addNotify( )
"Notifies" the component that it must create a peer.
- Rectangle bounds( )
Returns the boundaries of the component.
- int checkImage(Image image, ImageObserver observer)
Returns the status of an image being displayed on the screen.
This value is either obtained from the component's peer or the
current Toolkit. The specified
ImageObserver will be notified
of the status of the Image.
- int checkImage(Image image, int width, int height, ImageObserver
observer)
Returns the status of an scaled image being displayed on the
screen. This value is either obtained from the component's peer
or the current Toolkit. The
specified ImageObserver will
be notified of the status of the Image.
- Image createImage(int width, int height)
Creates an off-screen image with the specified width and height.
- Image createImage(ImageProducer producer)
Creates an image from the information supplied by the specific
ImageProducer.
- void deliverEvent(Event e)
"Delivers" an event to the component.
- synchronized void disable( )
Disables the current component. The component will not be
able to respond to user events.
- void enable(boolean cond)
If cond is true,
this method enables the component. Otherwise, it disables the
component.
- synchronized void enable( )
Enables the component.
- Color getBackground( )
Returns the current background color.
- synchronized ColorModel getColorModel( )
Returns the ColorModel
used when creating the component.
- Font getFont( )
Returns the font of the component. If the component does not
have a font, this method returns the font of the parent container.
- FontMetrics getFontMetrics(Font font)
Returns the FontMetrics
of the component. Returns null if the component currently is not
available.
- Color getForeground( )
Returns the foreground color of the component. If none exists,
this method defaults to the foreground color of the parent container.
- Graphics getGraphics( )
Returns the graphics context used in creating this component.
As of the 1.0 JDK release, this method was only implemented for
Canvas components.
- Container getParent( )
Returns the parent container in which the Component
resides.
- ComponentPeer getPeer( )
Returns the peer of the component.
- Toolkit getToolkit( )
Returns the component's Toolkit.
- boolean gotFocus(Event evt, Object what)
This method is called whenever the component receives the
input focus (usually the result of a mouse movement). The what
parameter represents the argument of the event. (what
is equal to evt.arg.)
- boolean handleEvent(Event evt)
This method is called whenever an EventFONT>
is posted to the component. By default, it calls a series of more
specific methods, such as mouseDown(
) and keyUp( ).
This method returns true
if the event has been handled successfully. If you override this
method but still want to employ the component's default method
handling abilities, call super.handleEvent(evt).
- synchronized boolean inside(int x, int y)
Determines if the specified coordinates are inside the current
component.
- synchronized void hide( )
"Hides" the component by making it no longer visible.
- boolean imageUpdate(Image img, int flags, int x, int y,
int width,
int height)
Repaints the specified image if and when the image is changed.
The flags are constants,
such as FRAMEBITS and ALLBITS
found in the java.awt.image.ImageObserver
interface.
This method will be called by the system when more information
becomes available about the Image.
Therefore, this method should only be used if you want to add
some functionality to the method.
- void invalidate( )
A component is invalid if it needs to be laid out. This method
makes the current component invalid, forcing it to be laid out
again.
- boolean isEnabled( )
Enables a component to interact with the user. This method
returns true if the component
is enabled and false otherwise.
- boolean isShowing( )
Returns true if the component
is visible to the user. This requires that the component be visible
in a container that is also visible.
- boolean isValid( )
A component is invalid if it needs to be laid out. This method
returns false if the component
is invalid and true if it
is valid.
- boolean isVisible( )
Returns true if the component
is visible.
- boolean keyDown(Event evt, int key)
Called by handleEvent()
when a key is depressed. The event
parameter is the complete event posted. The key
parameter is the key depressed.
- boolean keyUp(Event evt, int key)
Called by handleEvent()
when a key is released. The event
parameter is the complete event posted. The key
parameter is the key released.
- void layout( )
Correctly positions the component in the layout.
- void list( )
Prints out the current parameters to the standard output stream.
- void list(PrintStream out)
Prints out the current parameters to the specified PrintStream.
- void list(PrintStream out, int indent)
Prints out the current parameters to the specified PrintStream,
starting from the specified indentation.
- Component locate(int x, int y)
Returns the component occupying the specified location.
- Point location( )
Returns a Point containing
the x- and y-coordinates of the component in its container.
- boolean lostFocus(Event evt, Object what)
Called by handleEvent()
when the component looses the input focus.
- boolean mouseDown(Event evt, int x, int y)
Called by handleEvent()
when the mouse is depressed in the component.
- boolean mouseDrag(Event evt, int x, int y)
Called by handleEvent()
when the mouse is dragged in the component. (A drag is
considered a mouse movement while the mouse button is down.)
- boolean mouseEnter(Event evt, int x, int y)
Called by handleEvent()
when the mouse enters the component.
- boolean mouseExit(Event evt, int x, int y)
Called by handleEvent()
when the mouse leaves the component.
- boolean mouseMove(Event evt, int x, int y)
Called by handleEvent()
when the component loses the input focus. (A move is a
mouse movement while the mouse button is up.)
- boolean mouseUp(Event evt, int x, int y)
Called by handleEvent()
when the component loses the input focus.
- Dimension minimumSize( )
Returns the minimum size necessary to display the component.
- void move(int x, int y)
Moves the component to the new location and causes the component
to become invalidated.
- void nextFocus( )
Advances the focus to the next component. This is useful in
such applications as forms in which the user wants to go from
one component to the next.
- void paint(Graphics g)
Paints the component.
- void paintAll(Graphics g)
Paints the component and all its subcomponents.
- protected String paramString( )
Returns a string containing information about the component
including its location, and whether it is visible, valid, and/or
enabled.
- boolean postEvent(Event e)
Posts the specified event to the component, resulting in a
call to handleEvent(). If
the component does not successfully handle the event, the event
will be passed to the component's parent container.
- Dimension preferredSize( )
Returns the preferred size of this component. This value is
supplied by the component's peer.
- boolean prepareImage(Image image, int width, int height,
ImageObserver observer)
This method "prepares" a scaled image to be displayed.
This process includes loading the image and preparing the screen
where the image is to be displayed. The imageUpdate()
method in the specified ImageObserver
will be informed of the status of this process.
- boolean prepareImage(Image image, ImageObserver observer)
This method "prepares" and image to be displayed.
This process includes loading the image and preparing the screen
where the image is to be displayed. The specified ImageObserver
will be informed of the status of this process through the imageUpdate()
method.
- void print(Graphics g)
"Prints" the component. By default, this method
simply calls the paint()
method.
- void printAll(Graphics g)
"Prints" the component and its subcomponents. By
default, this method paints the component and its subcomponents.
- synchronized void removeNotify( )
Disposes of the component's peer.
- void repaint(int x, int y, int width, int height)
Repaints a portion of the component.
- void repaint(long delay, int x, int y, int width,
Repaints a portion of the component after waiting the specified
number of milliseconds.
- void repaint(long time)
Repaints the entire component after waiting the specified
number of milliseconds.
- void paint( )
Repaints the entire component.
- void requestFocus( )
Requests the input focus.
- synchronized void reshape(int x, int y, int width, int
height)
Moves the component to the specified coordinates and reshapes
it to the specified size. This will cause the component to become
invalidated.
- void resize(Dimension d)
Resizes the component to the specified dimensions-width and
height. This will cause the component to become invalidated.
- void resize(int width, int height)
Resizes the component to the specified width and height. This
will cause the component to become invalidated.
- synchronized void setBackground(Color c)
Sets the background color for the component.
- synchronized void setFont(Font f)
Sets the font for the component.
- synchronized void setForeground(Color c)
Sets the background color for the component.
- void show(boolean cond)
Displays the component if the cond
parameter is true. If the
cond parameter is false,
the component is hidden.
- synchronized void show( )
Displays the component.
- Dimension size( )
Returns the size of the component.
- String toString( )
Returns a string containing the component's parameters. This
consists of the name of the component as well as the values returned
by paramString().
- void update(Graphics g)
This method is called as a result of a call to repaint().
It can be used to perform management tasks associated with updating
the component.
- void validate( )
Makes the component valid. This means that it does not need
to be laid out.
Abstract Container Extends Component. The
Container class is a basic
class that may hold other Components.
The Container class serves
as the basis for the other container-type classes such as Frame,
Panel, and FileDialog.
Note that you cannot create a Container
explicitly, but rather must either use one of the derived classes
or create your own Container
class.
Methods
- synchronized Component add(String info, Component comp)
Adds the component to the container. The use of the information
supplied in the string depends on the LayoutManager
for the Container.
- synchronized Component add(Component comp, int pos)
Adds the component to the container at the specified position.
- Component add(Component comp)
Adds the component to the end of the container.
- synchronized void addNotify( )
Creates the container's peer.
- int countComponents( )
Returns the number of components in the container.
- void deliverEvent(Event evt)
Delivers the specified event to the appropriate component.
If the event does not occur in one of the components belonging
to the container, the event is handed over to the java.awt.Component.postEvent()
method.
- synchronized Component getComponent(int num) throws ArrayIndexOutOfBoundsException}
Returns the component at the specified index. Throws an ArrayIndexOutOfBoundsException
if there are fewer than num
components in the container.
- synchronized Component[ ] getComponents( )
Returns an array containing the components residing in the
Container.
- LayoutManager getLayout( )
Returns the layout manager used in creating this container.
- synchronized void layout( )
Organizes the components in the container according to the
conventions of the layout manager.
- void list(PrintStream out, int indent)
Displays the standard component information (name and parameters)
as well as the components within the container. Begins printing
at the specified indentation point.
- Component locate(int x, int y)
Returns the component that occupies the specified coordinates.
- synchronized Dimension minimumSize( )
Returns the minimum size necessary for this component. This
value is based on the minimum sizes for the individual components.
- void paintComponents(Graphics g)
Paints the components in the container. Identical to the printComponents()
method in this class.
- protected String paramString( )
Returns the information supplied by the java.awt.Component.paramString()
method in addition to the layout manager of the component.
- synchronized Dimension preferredSize( )
Returns the preferred size of the container. This is based
on the values returned from the preferredSize()
methods for the individual components.
- void printComponents(Graphics g)
Displays the components in the container. Identical to the
printComponents() method
in this class.
- synchronized void remove(Component comp)
Removes the specified component from the container.
- synchronized void removeNotify( )
Removes the container's peer.
- void setLayout(LayoutManager mgr)
Sets the layout manager for the component.
- synchronized void validate( )
Valid components do not need to be laid out. This method makes
the container and all its components valid.
Dialog Extends Window. A Dialog
is a type of Window that
is used to accept user input. A Dialog
must exist in a Frame object.
A modal Dialog is a type
of Dialog that will capture
all the input from the user.
Methods
- Dialog(Frame parent, String title, boolean modal)
Creates a new Dialog
in the specified Frame and
with the specified title. If the modal
parameter is true, the Dialog
will be modal.
- Dialog(Frame parent, boolean modal)
Creates a new Dialog
in the specified Frame that
will have no title. If the modal
parameter is true, the Dialog
will be modal.
- synchronized void addNotify( )
Creates the Dialog's
peer.
- boolean isModal( )
Returns true if the Dialog
is modal.
- boolean isResizable( )
Returns true if the Dialog
is resizable.
- protected String paramString( )
Returns a string containing the parameters of the Dialog,
including its title whether or not it is modal.
- void setTitle(String title)
Sets the title for the Dialog.
Dimension. The Dimension
class provides you with a simple way of handling the dimensions
of graphical tools. Most often, the Dimension
class is used to enable a single method to return two values:
width and height.
Fields
Methods
- Dimension( )
Creates a new Dimension
object.
- Dimension(Dimension d)
Creates a new Dimension
object with the same values as an already created
Dimension object.
- Dimension(int width, int height)
Creates a new Dimension
object with the specified width and height.
- String toString( )
Returns the width and height of the Dimension
in the form of a string.
Event. The Event class,
used as a means of responding to user interactions, delivers a
lot of information about a user event in a single object. Through
its constants and instance variables, each Event
object is capable of providing you with many specific details
regarding each event.
All final fields serve as constants against which you may compare
information contained in the Event
objects that you receive. In general, the fields fall into two
categories: those that represent certain keys (e.g., F1
and HOME) and those that
represent certain events (e.g., GOT_FOCUS
and KEY_PRESS).
See Listing 14.3, "CardLayout Example
Source Code," p. 413
See Listing 14.7, "Menu Example," p. 458
Fields
- final static int ACTION_EVENT
A flag representing a broad umbrella of event types. An ACTION_EVENT
will cause a call to action().
- final static int ALT_MASK
Will be placed in the modifiers
field if the ALT key is down. It should be tested for using the
AND operator.
- Object arg
An optional argument dependent on the type of event. Most
components set the arg equal
to their titles.
- int clickCount
Tracks the number of consecutive mouse clicks.
- final static int CTRL_MASK
Will be placed in the modifiers
field if the CTRL key is
down. Should be tested for using the AND
operator.
- final static int DOWN
- Event evt A reference to another Event
object. This can be used to create a linked list of Event
objects.
- final static int F1
A possible value for the key
field.
- final static int F2
- final static int F3
- final static int F4
- final static int F5
- final static int F6
- final static int F7
- final static int F8
- final static int F9
- final static int F10
- final static int F11
- final static int F12
- final static int GOT_FOCUS
Created when the Component
gets the input focus. It calls gotFocus().
- final static int HOME
A possible value for the key
field.
- int id
The ID of the event. It can be compared to such static constants
as ACTION_EVENT or MOUSE_DOWN.
- int key
Contains the key that was depressed.
- final static int KEY_ACTION
Created when the user presses a function key. It causes a
call to keyDown().
- final static int KEY_ACTION_RELEASE
Created when the user releases a function key. It causes a
call to keyUp().
- final static int KEY_PRESS
Created when the user presses a standard ASCII
key. It causes a call to keyDown().
- final static int KEY_RELEASE
Created when the user releases a standard ASCII
key. It causes a call to keyUp().
- final static int LEFT
A possible value for the key
field. It represents the left-arrow key.
- final static int LIST_DESELECT
Called when the user deselects an item on a List.
The Event will also contain
an Integer as its arg
field representing the item that was deselected.
- final static int LIST_SELECT
Called when the user deselects an item on a List.
The Event will also contain
an Integer as its arg
field representing the item that was deselected.
- final static int LOAD_FILE
Created when a file is loaded.
- final static int LOST_FOCUS
Created when the Component
looses the input focus. It causes a call to lostFocus().
- final static int META_MASK
Will be placed in the modifiers
field if the META key is
down. It should be tested for using the AND
operator.
- int modifiers
Represents the status of the modifier keys: Alt,
Ctrl, Meta,
and Shift. It can be compared
against the static constants defined within the class using the
AND operator.
- final static int MOUSE_DOWN
Created by a mouse click. It causes a call to mouseDown().
- final static int MOUSE_DRAG
- final static int MOUSE_ENTER
- final static int MOUSE_EXIT
- final static int MOUSE_MOVE
- final static int MOUSE_UP
- final static int PGDN
- final static int PGUP
- final static int RIGHT
- final static int SAVE_FILE
- final static int SCROLL_ABSOLUTE
Created when the user moves a scrollbar marker to a specific
location within the scrollbar.
- final static int SCROLL_LINE_DOWN
Created when the user clicks on the down arrow in a scrollbar.
- final static int SCROLL_LINE_UP
- final static int SCROLL_PAGE_DOWN
- final static int SCROLL_PAGE_UP
- final static int SHIFT_MASK
Will be placed in the modifiers
field if the Shift key is down or if Caps Lock is on. It should
be tested for using the AND
operator.
- Object target
The object at which the event was directed.
- final static int UP
- long when
The time at which the event occurred.
- final static int WINDOW_DEICONIFY
A possible value of the id
field.
- final static int WINDOW_DESTROY
A possible value of the id
field. It is used when the user tries to close a Window.
- final static int WINDOW_EXPOSE
A possible value of the id
field.
- final static int WINDOW_ICONIFY
A possible value of the id
field.
- final static int WINDOW_MOVED
A possible value of the id
field.
- int x
The x-coordinate of a mouse click.
- int y
The y-coordinate of a mouse click.
Methods
- Event( )Object target, int id, Object arg)
Creates a new Event with
the specified target, ID, and arg values.
- Event(Object target, long when, int id, int x, int y, int
key,
int modifiers)
Creates a new Event with
the specified target, time stamp (when), ID, x, y, key, and modifier
values.
- Event(Object target, long when, int id, int x, int y, int
key,
int modifiers, Object arg)
Creates a new Event with
the specified target, time stamp (when), ID, x, y, key, modifiers,
and arg values.
- boolean controlDown( )
Returns true if the Control
key is down.
- boolean metaDown( )
Returns meta if the Control
key is down.
- protected String paramString( )
Returns a string containing the values of all the Event's
instance variables.
- boolean shiftDown( )
Returns true if the shift
key is down.
- String toString( )
Returns the Event object's
name as well as the information returned from the paramString()
method.
- void translate(int x, int y)
FileDialog Extends Dialog. A FileDialog
creates a window to provide the user with a selection of files.
The FileDialog itself will
resemble the appearance of file dialog boxes on the client's machine.
The FileDialog was created
with the code in Listing 14.4. Although the code is obviously
too simple to serve as a complete applet, it nevertheless demonstrates
the technique for creating a FileDialog.
Listing 14.4 FileDialog
Example
import java.applet.Applet;
import java.awt.*;
public class FDialogExample extends Applet {
public void init() {
Frame
f;
f = new Frame();
Dialog d;
d = new FileDialog(f,"FileDialogExample");
f.show();
d.show();
}
}
Fields
- final static LOAD
This constant is used to define the mode of the FileDialog.
If the mode equals LOAD,
then the FileDialog is designed
to load files.
- final static SAVE
This constant is used to define the mode of the FileDialog.
If the mode equals SAVE,
then the FileDialog is designed
to save files.
Methods
- FileDialog(Frame parent, String title, int mode)
Creates a FileDialog
with the specified mode.
- FileDialog(Frame parent, String title)
Creates a FileDialog,
setting the mode to LOAD.
- synchronized void addNotify( )
Creates the FileDialog's
peer.
- String getDirectory( )
Returns the current directory.
- String getFile( )
Returns the file name selected by the user.
- FilenameFilter getFilenameFilter( )
Returns the FilenameFilter
used by the user in selecting the file.
- int getMode( )
Returns the mode of the FileDialog-either
LOAD or SAVE.
- protected String paramString( )
Returns the attributes of the component including the directory
and the mode.
- void setDirectory(String dir)
Sets the directory in the FileDialog.
- void setFile(String file)
Highlights the specific file in the FileDialog.
- public void setFilenameFilter(FilenameFilter filter)
Sets the filter for the dialog to be employed by the user
in selecting the file.
FlowLayout Implements LayoutManager. The FlowLayout
class is a relatively simple layout manager. It places components
in rows and continues on the next line when the current line becomes
full.
Fields
- final static int CENTER
Aligns the components with the center.
- final static int LEFT
Aligns the components on the left.
- final static int RIGHT
Aligns the components on the right.
Methods
- FlowLayout( )
Creates a new FlowLayout
with an alignment of CENTER.
- FlowLayout(int align)
Creates a new FlowLayout
with the specified alignment.
- FlowLayout(int align, int hgap, int vgap)
Creates a new FlowLayout
with the specified alignment. hgap
and vgap specify the amount
of spacing around the component.
- void addLayoutComponent(String name, Component comp)
This method is required inasmuch as this class implements
the LayoutManager interface.
However, it does absolutely nothing.
- void layoutContainer(Container target)
Arranges the specified container according to its FlowLayout
parameters.
- Dimension minimumLayoutSize(Container target)
Returns the minimum size necessary for the components in the specified
container. This value is based on the minimum sizes of the components
added to the amount of spacing for the container.
- Dimension preferredLayoutSize(Container target)
Returns the preferred size necessary for the components in
the specified container. This value is based on the preferred
sizes of the components added to the amount of spacing for the
container.
- void removeLayoutComponent(Component comp)
Removes the specified component from the layout manager.
- String toString( )
Returns a string containing the layout's name, the alignment,
the hgap, and the vgap.
Font. The Font class
serves as an intermediary between your code and the client's machine,
providing you with specific styles for your text. Although it
will not affect the appearance of the output to the output streams
(e.g., System.out), the current
font will determine the appearance of any text created in displaying
a Component-particularly
an Applet.
See Listing 14.2, "Sample Applet,"
p. 406
| Note |
To actually change the display font, you must first create a new Font and then set the current font. This is done using either the java.awt.Component.setFont( ) or java.awt.Graphics.setFont( ) method.
|
Fields
- final static int BOLD
A possible value for style
indicating a bold font.
- final static int ITALIC
A possible value for style
indicating an italic font.
- protected String name
The name of the font.
- final static int PLAIN
A possible value for style
indicating the standard font.
- protected int size
The size of the font.
- protected int style
The style of the font.
Methods
- Font(String name, int style, int size)
Creates a new font with the specified name, style, and size.
- boolean equals(Object anotherobject)
Compares two fonts for equality. The return value will always
be false if the second object
is not a Font.
- String getFamily( )
Returns the name of the family to which the font belongs.
This value depends on the system itself.
- static Font getFont(String name)
Returns the font possessing the system-dependent font name.
- static Font getFont(String name, Font defaultfont)
Returns the font possessing the system-dependent font name.
If the font cannot be found, the method returns the defaultfont.
- String getName( )
Returns the name of the font.
- int getSize( )
Returns the size of the font.
- int getStyle( )
Returns the style of the font.
- int hashCode( )
Returns the hashcode
of the font, a value dependent on the font name, style, and size.
Returns the name of the font.
- boolean isBold( )
Returns true if the font
is bold.
- boolean isItalic( )
Returns true if the font
is italic.
- boolean isPlain( )
Returns true if the font
is plain (neither bold nor italic).
- String toString( )
Returns a string containing information on the font, including
its name, style, and size.
FontMetrics. The FontMetrics
class provides you with information regarding a given font. This
class is very useful for such tasks as animation of text because
it is often necessary to know exactly where each character will
be. By creating a FontMetrics
for the font and then using the accessor methods to obtain information,
you can determine the exact size of your characters and strings.
See "Font," p. 433
| Note |
To employ a FontMetrics in your program, declare an instance of a FontMetrics and then use the java.awt.getFontMetrics( ) method to provide the FontMetrics with information.
|
Field
- protected Font font
The font on which the FontMetrics
is based.
Methods
- protected FontMetrics(Font font)
Creates a new FontMetrics.
- int bytesWidth(byte data[ ], int offset, int len)
Returns the width of a set of bytes. The offset
parameter specifies the index at which the measurement begins
and the len parameter specifies
the number of terms to be considered in the measurement.
- int charsWidth(char data[ ], int offset, int len)
Returns the width of a set of characters. The offset
parameter specifies the index at which the measurement begins,
and the len parameter specifies
the number of terms to be considered in the measurement.
- int charWidth(char ch)
Returns the width of a single character.
- int charWidth(int ch)
Returns the width of a single character.
- int getAscent( )
Returns the amount of space between the x-height (the height
of the main body of lowercase letters) and the top of a character
in the font.
- int getDescent( )
Returns the amount of space between the baseline (the imaginary
line on which the type sits) and the bottom of a character in
the font.
- Font getFont( )
Returns the font.
- int getHeight( )
Returns the amount of space between the top and bottom of
a character in this font.
- int getMaxAdvance( )
The advance is defined as the space between two characters
(actually between the bottom of one character and the top of the
next). This method returns the maximum advance for any character
in this font.
- int getMaxAscent( )
The ascent is the distance from the x-height to the top of
the letter. This method returns the maximum ascent for any character
in the font.
- int getMaxDescent( )
The descent is the distance from the baseline to the bottom
of the letter. This method returns the maximum descent for any
character in the font.
- int[ ] getWidths( )
Returns an array containing the width of the first 256 characters
of the font.
- int stringWidth(String str)
Returns an integer representing the width of the specified
string.
- String toString( )
Returns a string containing information about the class, including
the class name, font name, ascent, descent, and height.
Frame Extends Window Implements MenuContainer. A Frame
is a Window that has added
capabilities. In terms of appearance, a Frame
possesses a border and a title. In terms of functionality, you
can add a menu to a Frame
and specify the image that appears when the Frame
is minimized.
See "MenuBar Extends MenuComponent
Implements MenuContainer," p. 457
See "Window Extends Container," p. 471
| Tip |
When using a Frame, remember to invoke the show( ) method. Otherwise, your frame will be invisible!
|
Fields
- final static int CROSSHAIR_CURSOR
- final static int DEFAULT_CURSOR
- final static int E_RESIZE_CURSOR
- final static int HAND_CURSOR
- final static int MOVE_CURSOR
- final static int NE_RESIZE_CURSOR
- final static int NW_RESIZE_CURSOR
- final static int N_RESIZE_CURSOR
- final static int SE_RESIZE_CURSOR
- final static int SW_RESIZE_CURSOR
- final static int S_RESIZE_CURSOR
- final static int TEXT_CURSOR
- final static int WAIT_CURSOR
- final static int W_RESIZE_CURSOR
Methods
- Frame( )
Creates a new Frame without a title.
- Frame(String title)
Creates a new frame with the specified title.
- synchronized void addNotify( )
Creates the Frame's peer.
- synchronized void dispose( )
Disposes the resources used by the Frame.
- int getCursorType( )
Returns the cursor type for this Frame.
- Image getIconImage( )
Returns the icon for
this frame. The icon is an
inaccessible variable that defines the appearance of the Frame
when it is minimized.
- MenuBar getMenuBar( )
Returns the current MenuBar
for this Frame.
- String getTitle( )
Returns the title of this Frame.
- boolean isResizable( )
Returns true if the Frame
can be resized.
- protected String paramString( )
Returns a string, including the title of the Frame
and the word resizable if the Frame
is resizable.
- synchronized void remove(MenuComponent m)
Removes the specified MenuBar
from this Frame.
- void setCursor(int cursorType)
Sets the appearance of the cursor for this Frame.
The parameter value may be any one of the above listed constants.
- void setIconImage(Image image)
Sets the icon for this Frame.
The icon will be displayed when the Frame
is minimized.
- synchronized void setMenuBar(MenuBar mb)
Sets the MenuBar for
this Frame.
- void setResizable(boolean resizable)
Makes the Frame either
resizable (true) or not resizable
(false). All Frames
are initially resizable.
- void setTitle(String title)
Sets the title for the Frame.
Abstract Graphics. The Graphics class provides
you with a wide variety of graphical tools, ranging from the generic
drawing tools, such as drawLine(),
to editing tools, such as clipRect().
If you are creating an applet, the creation of a graphics object
will be done for you by the browser environment. Therefore, you
can use the Graphics objects
passed as parameters to the paint()
and update() methods without
worrying about how drawLine()
actually does its chore.
See Listing 14.2, "Sample Applet,"
p. 406
The Graphics class provides
you with a wide variety of graphical tools to create attractive
interfaces. Listing 14.5 gives a brief sample of these tools and
demonstrates the form for creating graphics.
Listing 14.5 Graphics
Example
import java.applet.Applet;
import java.awt.*;
public class GraphicsExample extends Applet
{
public void paint(Graphics g) {
g.setFont( new Font("TimesRoman",
Font.PLAIN, 14) );
//
sets the font for the drawString() statement
g.drawString("This is a sample of what
the Graphics class can do!",30,20);
g.setColor(Color.red);
g.fill3DRect(10,60,20,10,true);
g.fill3DRect(50,60,20,10,false);
int xpoints[ ] = {120,130, 150,
140, 180 };
//
x-coordinates for polygon
int ypoints[ ] = {60,50, 90, 170,
60};
g.fillPolygon( xpoints, ypoints,
5);
g.fillRoundRect(200,80,100,100,10,5);
g.setColor(Color.blue);
g.fillArc(10,150,100,100,0,360);
g.setColor(Color.white);
g.fillArc(35,175,50,50,0,270);
g.setColor(Color.magenta);
g.drawLine(300,180,350,180);
g.drawLine(300,180,300,220);
g.drawLine(300,220,350,180);
}
}
Methods
- protected Graphics( )
Creates a new Graphics
object.
- abstract void clearRect(int x, int y, int width, int height)
Clears the specified rectangle with the background color.
- abstract void clipRect(int x, int y, int width, int height)
Sets the clipping rectangle for the graphical operations.
Only those graphics within the specified area will be displayed.
| Tip |
Be careful when setting the clipping area. Once this is done, it cannot be undone! Therefore, it is often wise to create a temporary Graphics object with the create( ) method. You can set the clipping area and paint with this new object.
When you want to display on the full screen again, you can revert to the original Graphics object.
|
- abstract void copyArea(int x, int y, int width, int width,
int height,
int dx, int dy)
Copies the area defined by the x- and y-coordinates and the
width and height
dimensions. This region will then be moved dx
pixels horizontally and dy
pixels vertically.
- Graphics create(int x, int y, int width, int height)
Creates a new Graphics
object. This object will be identical to the current Graphics
object except for the fact that its clipping area will be set
to the specified coordinates and dimensions. This is useful inasmuch
as once the clipping area is set it cannot be reset. Therefore,
by creating a new Graphics
object, you are able to employ a clipping area without destroying
the original Graphics object.
- abstract Graphics create( )
Creates a new Graphics
object identical to the current object. Because both the original
and the new copy may paint to the same region, this is often useful
when you are making temporary yet irrevocable changes to the Graphics
object-such as setting the clipping area.
- abstract void dispose( )
Disposes of the resources used by the graphics context.
- void draw3DRect(int x, int y, int width, int height, boolean
raised)
Creates a 3-D rectangle with the specified location and size.
Setting the raised parameter
to a value of true gives
the rectangle a brighter color-making it appear three-dimensional.
- abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle)
Draws the outline of an arc at the specified coordinates with
the given size. The startAngle
and arcAngle are measured
in degrees and represent the angle at which the arc begins and
ends (i.e., an arc from 0 to 360 is a complete circle)
- void drawBytes(byte data[ ], int offset, int length, int
x, int y)
Displays bytes from the data[ ]
array. The offset value represents
the index of the first byte to be drawn; length
is the number of bytes to be drawn; and x
and y are the coordinates
at which the bytes will be drawn on the screen.
- void drawChars(char data[ ], int offset, int length, int
x, int y)
Displays characters from the data[]
array. The offset value represents
the index of the first character to be drawn; length
is the number of characters to be drawn; and x
and y are the coordinates
at which the characters will be drawn.
- abstract boolean drawImage(Image img, int x, int y, int
width, int height, Color bgcolor, ImageObserver observer)
Draws an image at the specified location with the specified
size. bgcolor is the color
that will be drawn "behind" the image-visible if there
are any transparent pixels in the image. observer
is the ImageObserver that
monitors the progress of the image.
| Note |
The java.awtComponent class implements the ImageObserver interface. Therefore, in most applets, you may use the this keyword as the ImageObserver.
|
- abstract boolean drawImage(Image img, int x, int y, Color
bgcolor, ImageObserver observer)
Draws an image at the specified location with its normal size.
bgcolor is the color that
will be drawn "behind" the applet-visible if there are
any transparent pixels in the image. observer
is the ImageObserver that
monitors the progress of the image.
- abstract boolean drawImage(Image img, int x, int y, int
width, int height, ImageObserver observer)
Draws an image at the specified location with the specified
size. observer is the ImageObserver
that monitors the progress of the image.
- abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer)
Draws an image at the specified location with its normal size.
observer is the ImageObserver
that will monitor the progress of the image.
- abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line between the given points.
- abstract void drawOval(int x, int y, int width, int height)
Draws the outline of an oval at the specified coordinates
with the specified size.
- void drawRect(int x, int y, int width, int height)
Draws the outline of a rectangle at the specified coordinates
with the specified size.
- abstract void drawRoundRect( )int x, int y, int width,
int height, int arcWidth, int arcHeight)
Draws the outline of a rectangle at the specified coordinates
having the specified size. arcWidth
and arcHeight determine the
size and shape of the corners of the rectangle.
- void drawPolygon(Polygon p)
Draws the polygon defined by the specified java.awt.Polygon
object.
- abstract void drawPolygon(int xPoints[ ], int yPoints[
], int nPoints)
Draws the polygon defined by the specified set of points.
nPoints represents the number
of vertices on the polygon. Java will pair the first n
coordinates of the arrays to create n ordered pairs that
will serve as the vertices of the polygon.
- abstract void drawString(String str, int x, int y)
Draws a string at the specified coordinates using the current
font.
- void fill3DRect(int x, int y, int width, int height, boolean
raised)
Fills a rectangle at the specified coordinates that has the
specified size. The raised
variable will change the darkness of the rectangle-making it appear
three-dimensional if true.
- abstract void fillOval(int x, int y, int width, int height)
Fills an oval defined by the x- and y-coordinates that will
have the specified size.
- abstract void fillRect(int x, int y, int width, int height)
Fills a rectangle at the given coordinates with the specified
size.
- abstract void fillRoundRect(int x, int y, int width, int
height, int arcWidth, int arcHeight)
Fills in a rectangle at the specified coordinates having the
specified size. arcWidth
and arcHeight determine the
size and shape of the corners of the rectangle.
- abstract void fillArc( )int x, int y, int width, int height,
int startAngle, int arcAngle)
Fills an arc at the given coordinates with the specified size.
The arc will extend from the startAngle
to the arcAngle, measured
in degrees.
- void fillPolygon(Polygon p)
Fills the polygon defined by the particular Polygon
object.
- abstract void fillPolygon(int xPoints[ ], int yPoints[
], int nPoints)
Fills the polygon defined by the specified set of points.
nPoints represents the number
of vertices on the polygon. Java will pair the first n
coordinates of the arrays to create n ordered pairs that
will serve as the vertices of the polygon.
- void finalize( )
Disposes of the specific Graphics
object.
- abstract Rectangle getClipRect( )
Returns the clipping rectangle set by the clipRect()
method.
- abstract Color getColor( )
Returns the current color used by graphical operations.
- abstract Font getFont( )
Returns the font used by all text-related operations.
- abstract FontMetrics getFontMetrics(Font f)
Returns the FontMetrics
for the specified Font.
- FontMetrics getFontMetrics( )
Returns the FontMetrics
for the current font.
- abstract void setColor(Color c)
Sets the color to be used by all graphical operations.
- abstract void setFont(Font font)
Sets the font for all graphical operations.
- abstract void setPaintMode( )
Causes subsequent graphical commands to cover the locations
with the current color.
- abstract void setXORMode(Color otherColor)
This method will cause the Graphics
object to XOR mode using the current color and the specified otherColor.
When painting graphics, all figures in the current color will
be painted with the otherColor
and vice versa. Any figures not in either color will be displayed
in a different, random color.
- abstract void translate(int x, int y)
Makes the specified coordinates the new origin for graphical
operations. As a result, all operations will be relative to this
new origin.
- String toString( )
Returns a string containing information about the Graphics
object, including the current color and font.
GridBagConstraints Implements java.lang.Cloneable. The
GridBagConstraint class enables
you to customize the layout attributes of each component in a
GridBagLayout. By first creating
a GridBagConstraint and setting
its fields, you are able specify the shape, size, and behavior
of the component once added to the layout.
See "GridBagLayout Implements LayoutManager,"
p. 445
Fields
- int anchor
Describes the location at which the component will be placed.
- final static int BOTH
A possible fill value.
The component will fill as much space as allowed, both horizontally
and vertically.
- final static int CENTER
A possible anchor value.
- final static int EAST
A possible anchor value.
- int fill
Determines how the component will behave if the container
is resized. The component may expand horizontally, vertically,
or in both directions.
- int gridheight
Sets the height of the component.
- int gridwidth
Sets the width of the component.
- int gridx
The x-coordinate of the component.
- int gridy
The y-coordinate of the component.
- final static int HORIZONTAL
A value for fill. Causes
the component to expand horizontally when the area available for
the component exceeds the size of the component.
- Insets insets
Defines the amount of space to be placed around the outside
of any components on the edge of the layout.
- int ipadx
The amount of horizontal space to be placed between components.
- int ipady
The amount of vertical space to be placed between components.
- final static int NONE
A value for fill. The
component will not expand in any direction.
- final static int NORTH
A value for anchor.
- final static int NORTHEAST
A value for anchor.
- final static int NORTHWEST
A value for anchor.
- final static int RELATIVE
A value for gridx or
gridy. The component will
be placed just after the previous component. For gridx
this means to the left. For gridy,
this means directly beneath.
- final static int REMAINDER
A value for gridwidth
or gridheight. The component
will take up the remainder of the row or column, respectively.
- final static int SOUTH
A value for anchor.
- final static int SOUTHEAST
A value for anchor.
- final static int SOUTHWEST
A value for anchor.
- final static int VERTICAL
A value for fill. The
component will expand vertically to fill the available area.
- double weightx
Defines the relative importance of the component. This attribute
is used when resizing the container in which the component resides.
- double weighty
Defines the relative importance of the component. This attribute
is used when resizing the container in which the component resides.
- final static int WEST
A value for anchor.
Methods
- GridBagConstraints( )
Creates a new GridBagConstraints
object.
- Object clone( )
Returns a copy of the GridBagConstraints
object.
GridBagLayout Implements LayoutManager. The GridBagLayout
is the most versatile and commonly used layout manager for components.
A GridBagLayout enables you
to place any number of components in virtually any layout that
you can imagine.
To control the layout of components in a GridBagLayout,
you must employ the GridBagConstraints
class. After setting the values of the GridBagConstraints
class, you can add a component to the layout using the constraints.
This flexibility enables you to specify a great deal of information
about how the components will be laid out.
See "GridBagConstraints Implements
java.lang.Cloneable," p. 443
The constraints for a GridBagLayout
are set through the fields in the GridBagLayout,
as described in the following table:
| Fields | Purpose
|
| anchor
| Can be used to place the component in a particular region of the container (for example, SOUTHWEST).
|
| fill |
Determines how the component will act if the container provides it with room to grow. Valid values are NONE, HORIZONTAL, VERTICAL, and BOTH.
|
| insets
| Specifies the amount of space between components on the side of the container and the container edge.
|
| ipadx, ipady
| Specifies the amount of space between components.
|
| gridx, gridy
| Defines the upper lefthand corner of the component.
|
| gridwidth, gridheight
| Defines the size of the component. |
| weightx, weighty
| Defines the relative importance of the components; to be used only when the container is resized.
|
Listing 14.6 GridbagLayout
Example
import java.applet.Applet;
import java.awt.*;
public class GridBagExample extends Applet
{
GridBagLayout gridbag;
GridBagConstraints c;
public void init() {
Button button;
Checkbox checkbox;
TextArea textarea;
TextField textfield;
Choice choice;
gridbag = new GridBagLayout();
c = new GridBagConstraints();
setLayout(gridbag);
c.ipadx=2;c.ipady=2; //
padding between components
c.insets=new Insets(5,5,5,5); /*
padding
between the components and the edge
of the container*/
button = new Button("Button
One");
gridbag.setConstraints(button,c);
add(button);
c.gridwidth = GridBagConstraints.REMAINDER;
/* Button will occupy the remainder
of this row.
Forces the next
component onto the next row. */
button = new Button("Button
Two");
gridbag.setConstraints(button,c);
add(button);
c.gridwidth = 1;
// back to defaults - components continue
on same row
checkbox = new Checkbox("Checkbox");
gridbag.setConstraints(checkbox,c);
add(checkbox);
c.gridwidth = GridBagConstraints.REMAINDER;
textfield = new TextField("This
is a TextField");
gridbag.setConstraints(textfield,c);
add(textfield);
c.gridwidth = 1;
c.gridheight = GridBagConstraints.REMAINDER;
choice = new Choice();
choice.addItem("Selection One");
choice.addItem("Selection Two");
gridbag.setConstraints(choice,c);
add(choice);
textarea = new TextArea("This
is a Text Area",10,3);
gridbag.setConstraints(textarea,c);
add(textarea);
}
}
Fields
- double columnWeights[ ]
Stores the horizontal weights of the components in each column.
- int columnWidths[ ]
Stores the horizontal sizes of the components in each column.
- protected Hashtable comptable
A Hashtable
to store the components.
- protected GridBagConstraints defaultConstraints
The default constraints for a component.
- protected GridBagLayoutInfo layoutInfo
The GridBagLayoutInfo
class is a restricted class that facilitates management of the
layout for the GridBagLayout
class. It tracks the size of the layout, the minimum dimensions
of the components, and the weights.
The class consists only of the following fields and one constructor
method.
Unless you are creating a new class in the java.awt package that
extends the GridbagLayout class, you will not need to use this
class-nor will you be able to.
int width, height; //
number of cells in each direction
int startx, starty; // start of layout
int minWidth[ ]; //
largest minWidth for each column
int minHeight[ ]; // largest
minHeight for each row
double weightX[ ]; // largest
weight for each column
double weightY[ ]; // largest
weight for each row
- protected final static int MAXGRIDSIZE
The maximum number of rows or columns. Set to 128.
- protected final static int MINSIZE
The minimum number of rows or columns. Set to 1.
- protected final static int PREFERREDSIZE
The preferred size of a component. Set to 2.
- int rowHeights[ ]
Tracks the heights of the components in each row.
- double rowWeights[ ]
Tracks the weights of the components in each row.
Methods
- GridBagLayout( )
Creates a new GridBagLayout.
- void addLayoutComponent(String name, Component comp)
This function is required inasmuch as the GridBagLayout
class implements the LayoutManager
interface. It however has no function in this class.
- protected void AdjustForGravity(GridBagConstraints constraints,
Rectangle r)
Adjusts the components according to their attributes within
the specified
Rectangle. This method is
called by ArrangeGrid().
- protected void ArrangeGrid(Container parent)
Arranges the parent container.
- protected void DumpConstraints(GridBagConstraints constraints)
Prints out the current constraints.
- protected void DumpLayoutInfo(GridBagLayoutInfo string)
Prints out the current layout information.
- GridBagConstraints getConstraints(Component comp)
Returns the current constraints.
- int[ ][ ] getLayoutDimensions( )
Returns an array of integers obtained for the arrays in the
LayoutInfo object. If the
returned array is named arr,
then arr[0] is the array
of minimum widths for each column and arr[1]
is the array of minimum heights for each row.
- protected GridBagLayoutInfo GetLayoutInfo(Container parent,
int sizeflag)
Returns the GridBagLayoutInfo
object for the GridBagLayout.
- Point getLayoutOrigin( )
Returns the origin for the layout. This may not always be
(0,0).
- double[ ][ ] getLayoutWeights( )
Returns the maximum weights of the components in each row
and column. arr[0] is an
array of the maximum weight in each column. arr[1]
is an array of the maximum weight in each row.
- protected Dimension GetMinSize(Container parent, GridBagLayoutInfo
info)
Returns the minimum size required for this layout. This value
is based on the size of the components and the insets
values for the parent container. This method is called by perferredLayoutSize()
and minimumLayoutSize(),
each with a different info
parameter.
- void layoutContainer(Container parent)
Arranges the container in accordance with the GridBagLayout
parameters.
- Point location(int x, int y)
Returns the size of the rectangle occupied by all components
above and to the left of the point (x,y) on the grid. This value
is created by summing the minimum widths and minimum heights for
each component having a x-coordinate less than or equal to x
and a y-coordinate less than or equal to y.
- protected GridBagConstraints lookupConstraints(Component
comp)
Returns the constraints for the particular component.
- Dimension minimumLayoutSize(Container parent)
Returns the minimum layout size required for the container.
It is based on the minimum sizes for the components within the
layout.
- Dimension preferredLayoutSize(Container parent)
Returns the preferred size of the container. It is based on
the preferred sizes for the components within the layout.
- void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
- void setConstraints(Component comp, GridBagConstraints
constraints)
Assigns the given component a new set of constraints.
- String toString( )
Returns the string, "java.awt.GridBagLayout."
GridLayout Implements LayoutManager. A GridLayout
provides you with slightly less control over the layout than the
GridBagLayout class. A GridLayout
is created by specifying a number of rows and columns. Each subsequent
add() statement will place
the specified component in the layout, adjusting the size of all
components. As a result, all components in a GridLayout
are of the same size.
Methods
- GridLayout(int rows, int cols)
Constructs a GridLayout
with the specified number of rows and columns. The hgap
and vgap will be set to 0.
- GridLayout(int rows, int cols, int hgap, int vgap)
Constructs a GridLayout
with the specified number of rows and columns, hgap,
and vgap.
- void addLayoutComponent(String name, Component comp)
This method has no function.
- void layoutContainer(Container parent)
Arranges the container in accordance with the GridLayout
model.
- Dimension minimumLayoutSize(Container parent)
Returns the minimum layout size required for the container.
It is based on the preferred sizes for the components within the
layout.
- Dimension preferredLayoutSize(Container parent)
Returns the preferred layout size requested for the container.
Based on the preferred sizes for the components within the layout.
- void removeLayoutComponent(Component comp)
Removes the specified component.
- String toString( )
Returns a string containing the layout's name, hgap,
vgaps, and the number of
rows and columns.
Abstract Image. The Image
class provides you with an platform-independent manner of handling
images. Regardless of the source of the image or the platform,
all the following methods may be used on all Images.
One problem often encountered with images is that they often take
some time to completely load. As a result, in all methods where
this could be problematic, it is necessary to specify an ImageObserver
(an object that implements the ImageObserver
interface). If the method is unable to return the requested information,
it will return a value of -1 or a null string. However, once the
information does become available, the information will be sent
along to the imageUpdate()
method of the specified ImageObserver.
See "java.awt.Image," p. 472
Field
- final static Object UndefinedProperty
This field is returned whenever you request a property not
defined for the particular Image.
Methods
- Image( )
Creates a new Image.
- abstract Graphics getGraphics( )
Returns the Graphics
object for this Image.
- abstract int getHeight(ImageObserver observer)
Returns the height of the Image.
If the height is not currently known, this method will return
a value of -1 and will inform the specified ImageObserver
at a later time though the imageUpdate()
method.
- abstract Object getProperty(String propertyname, ImageObserver
observer)
Returns the requested property for this Image.
If this property is undefined, the UndefinedProperty
object will be returned. If the property is currently unknown,
the method will return a value of null,
and will later inform the ImageObserver.
- abstract void flush( )
Disposes of all memory being used by the Image.
This contains cached information. If the Image
is to be displayed again, it will be re-created for you, but this
will take longer than if it were still cached.
- abstract ImageProducer getSource( )
Returns the source of the Image in
the form of a class implementing the ImageProducer interface.
This method is useful when using ImageFilters.
By first invoking this method, you can obtain the source of the
Image to be used when creating
a new java.awt.image.FilteredImageSource.
- abstract int getWidth(ImageObserver observer)
Returns the width of the Image.
If the height is not currently known, this method will return
a value of -1 and will later inform the specified ImageObserver.
Insets Implements Cloneable. The Insets
class is a tool to be used by layout managers, particularly GridBagLayoutManager.
An Inset
may be used to set and track the amount of space that will be
inserted between the components of the layout and the border of
the container.
See Listing 14.6, "GridbagLayout
Example," p. 446
Fields
- int bottom
- int left
- int right
- int top
Methods
- Insets(int top, int left, int bottom, int right)
Creates a new Insets
object with the specified spacing values.
- Object clone( )
Creates a copy of the Insets
object.
- String toString( )
Returns a string containing the class name and the four spacing
values.
Label Extends Component. A Label
is a convenient way of placing a single line of text on the screen.
Because it is a Component,
it may be placed in a layout manager.
Fields
- final static int CENTER
An alignment value for the text in the Label.
- final static int LEFT
An alignment value for the text in the Label.
- final static int RIGHT
An alignment value for the text in the Label.
Methods
- Label( )
Constructs a new, empty label whose text will be left justified.
- Label(String label)
Constructs a new label with the specified
text. The text will be left justified.
- Label(String label, int alignment)
Constructs a new label with the specified text and alignment.
The alignment value may be either LEFT,
CENTER, or RIGHT.
- synchronized void addNotify( )
Creates the Label's peer.
- int getAlignment( )
Returns the alignment for the Label.
- String getText( )
Returns the current text for the Label.
- protected String paramString( )
Returns a string containing the parameters for the Label
including the alignment and the text.
- void setAlignment(int alignment)
Sets the alignment for the displayed text. The parameter may
be either LEFT,
CENTER, or RIGHT.
- void setText(String label)
Sets the text for the Label.
List Extends Component. A List
is a useful scrollable index of textual headers. When using a
List, you may not only add
items to the end of the list, but may also insert them within
the list. Furthermore, during execution, you can query the list
for information regarding the user's actions or even scroll the
list yourself using the makeVisible()
method.
Methods
- List( )
Creates
a new List that contains
no rows and does not allow multiple selections.
- List(int rows, boolean multipleSelections)
Creates a new List with
the specified number of rows. If the multipleSelection
argument is true, then more
than one item in the list can be selected at a given time.
- synchronized void addItem(String itemTitle, int index)
Adds an new item to the list at the specified index. itemTitle
specifies the title that will be displayed. If the index is -1
or greater than the number of the items in the List,
the item will be added to the end of the List.
- synchronized void addItem(String itemTitle)
Adds an item with the specified title to the end of the List.
- synchronized void addNotify( )
Creates the List's peer.
- boolean allowsMultipleSelections( )
Returns true if the user
may select more than one item in this list.
- synchronized void clear( )
Clears the list. All items are erased.
- int countItems( )
Returns the number of items in the list.
- String getItem(int index)
Returns the title of the item at the specified index.
- synchronized void delItem(int index)
Deletes the item at the specified index.
- synchronized void delItems(int start, int end)
Deletes all items between and including the start
and end parameters.
- synchronized void deselect(int index)
Deselects the specified index. No item will be selected.
- int getRows( )
Returns the number of items that can be seen by the user.
- synchronized int getSelectedIndex( )
Returns the index of the currently selected item. Returns
-1 if none is selected at the time.
- synchronized int[ ] getSelectedIndexes( )
Returns an array containing the indexes of all selected items.
This is only useful when multiple selections are permitted.
- synchronized String getSelectedItem( )
Returns the title of the currently selected item. Returns
-1 if none is selected at the time.
- synchronized String[ ] getSelectedItems( )
Returns an array containing the titles of all selected items.
This is only useful when multiple selections are permitted.
- int getVisibleIndex( )
Returns the index of the item that was made visible by the
last call to makeVisible().
- synchronized boolean isSelected(int index)
Returns true if the specified
item is visible.
- void makeVisible(int index)
Scrolls the list to make the specified index visible.
- Dimension minimumSize( )
Returns the minimum size required to properly display the
entire list. This value is based on either the size returned from
the List's peer or the Component
class.
- Dimension minimumSize(int rows)
Returns the minimum size required to properly display the
specified number of rows in this list. This value is based on
either the size returned from the List's
peer or the Component class.
- protected String paramString( )
Returns a string containing information on the List
including the title of the
selected item.
- Dimension preferredSize( )
Returns the size desired to display the entire list. This
value is based on either the size returned from the List's
peer or the Component class.
- Dimension preferredSize(int rows)
Returns the size desired to display the specified number of
rows in the list. This value is based on either the size returned
from the List's peer or the
Component class.
- synchronized void removeNotify( )
Removes the List's peer.
- synchronized void replaceItem(String newValue, int index)
Changes the value of the item at the specified index. This
is done by deleting the item at the specified index and then creating
a new item with the specified title and index.
- synchronized void select(int index)
Selects the specified item.
- void setMultipleSelections(boolean multipleSelections)
If the multipleSelections
parameter is true, then more
than one item in the list can be selected at a time. If this is
false, then only one item
can be selected at a given moment.
MediaTracker. A MediaTracker
is a means of managing a number of media objects, such as images
and audio clips. (However, as of the 1.0 JDK, only Images
were supported.) Somewhat like an array, the MediaTracker
assigns each a reference number. However, it also keeps track
of the status of each image, allowing you to determine the status
of each or lock up the tracker until all images have been loaded.
Fields
- final static int ABORTED
A flag indicating the loading of the media has been aborted.
- final static int COMPLETE
A flag indicating the loading of the media has been successfully
completed.
- final static int ERRORED
A flag indicating an error has been encountered while loading
the media.
Methods
- MediaTracker(Component comp)
Creates a new MediaTracker
to report on the media in the specified component.
- void addImage(Image image, int id)
Adds an item to the MediaTracker
with the specified id. This
id value can later be used
as a reference to a set of media items.
- synchronized void addImage(Image image, int id, int width,
int height)
Adds an image with the specified dimensions to the MediaTracker
with the specified id. This
can later be used as a reference to a set of media items.
- synchronized boolean checkAll(boolean load)
Returns true if all media
items have been successfully loaded, false
otherwise.
If the load parameter is
true, this method will also
load any non-loaded images.
- boolean checkAll( )
Returns true if all media
items have been successfully loaded, false
otherwise. This method will not affect non-loaded images.
- synchronized boolean checkID(int id, boolean load)
Returns true if all media
items with the specified id
have been successfully loaded, false
otherwise. If the load parameter
is true, this method will
also load any non-loaded images.
- boolean checkID(int id)
Returns true if all media
items with the specified id
have been successfully loaded, false
otherwise. This method has no effect on unloaded images.
- synchronized Object[ ] getErrorsAny( )
Returns an array of all media items that have encountered
an error.
- synchronized Object[ ] getErrorsID(int id)
Returns an array of all media items with the specified id
that have encountered an error.
- synchronized boolean isErrorAny( )
Returns true if any media
items have encountered an error.
- synchronized boolean isErrorID(int id)
Returns true if any media
items with the specified id
have encountered an error.
- int statusAll(boolean load)
Returns the status for all media items in the MediaTracker.
If the load parameter is
true, any unloaded images
will be loaded.
- int statusID(int id, boolean load)
Returns the status for all media items with the specified
id. If the load
parameter is true, all unloaded
items will be loaded.
- void waitForAll( ) throws InterruptedException
Begins to load all media items and does not return until this
process is complete. Note
that this
method does
not guarantee
that these
items will
be loaded
successfully,
and thus you are strongly encouraged to check for any errors.
- synchronized boolean waitForAll(long ms) throws InterruptedException
Locks up the MediaTracker
object and loads all media items. This method relinquishes control
of the MediaTracker only
when the loading is complete or the specified number of milliseconds
has expired. Note
that this
method does
not guarantee
that these
items will
be loaded
successfully,
and thus you are strongly encouraged to check for any errors.
- void waitForID(int id) throws InterruptedException
Begins to load all media items with the specified id
and does not return until this process is complete. Note
that this
method does
not guarantee
that these
items will
be loaded
successfully,
and thus you are strongly encouraged to check for any errors.
- synchronized boolean itForID(int id, long ms) throws InterruptedException
Begins to load all media items and does not return until this
process is complete or the specified number of milliseconds has
expired. Note that
this method
does not
guarantee that
these items
will be
loaded successfully,
and thus you are strongly encouraged to check for any errors.
Menu Extends MenuItem Implements MenuContainer. A Menu
is a column in a MenuBar.
Like the standard "File" and "Help" headers
in most applications, a Menu
defines the title on the MenuBar
as well as the headings in the column. When creating a menu, you
must first create Menu items
and then add them to your MenuBar.
See the following section,
"MenuBar Extends MenuComponent Implements
MenuContainer"
See "Frame Extends Window Implements MenuContainer,"
p. 437
Methods
- Menu(String title)
Creates a new Menu with
the specified title.
- Menu(String title, boolean tearOff)
Creates a new Menu with
the specified title. The effects of the tearOff
parameter are platform-dependent. However, the idea of a tear-off
menu is that it will remain as a separate window until the user
selects an item from it.
- void add(String label)
Adds a selection with the specified label to the Menu
listing.
- synchronized MenuItem add(MenuItem mitem)
Adds a MenuItem to the
Menu listing.
- synchronized void addNotify( )
Creates the Menu's peer.
- void addSeparator( )
Inserts a line between the already added items in the Menu
and any later items that you add.
- int countItems( )
Returns the number of items in the menu listing.
- MenuItem getItem(int index)
Returns the item at the specified index.
- boolean isTearOff( )
Returns true if the menu
is a tear-off menu.
- synchronized void remove(MenuComponent item)
Removes the specified item from the menu listing.
- synchronized void remove(int index)
Removes the item at the specified index from the menu listing.
- synchronized void removeNotify( )
Removes the Menu's peer.
MenuBar Extends MenuComponent Implements MenuContainer.
A MenuBar is a container
for Menu items and serves
as the head of the menu when displayed. In order to create a menu
in your program, you must first create Menu
items, and then add them to a MenuBar.
By adding a MenuBar to the
Frame, you are able to make
the menu visible to the user.
See "Menu Extends MenuItem Implements
MenuContainer," p. 456
See "Frame Extends Window Implements MenuContainer,"
p. 437
Also note the use of the Display
class to enable the applet to monitor the user's
selections.
Listing 14.7 Menu
Example
import java.applet.Applet;
import java.awt.*;
public class MenuExample extends Applet
{
private Menu category;
private MenuBar bar;
private Display picture;
public void init() {
bar = new MenuBar();
category = new Menu("Document");
category.add("Option One");
category.add("Option Two");
category.add("Option Three");
bar.add(category);
category = new Menu("Session");
category.add("Reset");
category.add("Restart");
bar.add(category);
category = new Menu("Screen");
category.add("Change colors");
category.add("Display Titles");
bar.add(category);
picture = new Display();
picture.setMenuBar(bar);
picture.setTitle("Menu Example");
picture.show();
}
}
class Display extends Frame {
public boolean action(Event evt, Object arg)
{
if(arg.equals("Option Two"))
{
System.out.println("Option
Two was Selected");
return true;
}
return super.handleEvent(evt);
}
public boolean handleEvent(Event evt) {
if (evt.id == Event.WINDOW_DESTROY)
{
hide(); //
closes the frame when appropriate
return true;
}
return super.handleEvent(evt);
}
}
Methods
- MenuBar( )
Creates a new MenuBar.
- synchronized Menu add(Menu m)
Adds a