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.

java.applet

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

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

Options for target are shown in the following table:

ValueDocument 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.

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

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

java.awt

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

Options for location are as follows:

"North"
"South"
"West"
"East"
"Center"

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

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

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

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

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

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

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

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
Methods

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
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).
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.

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
Sets the layout manager for the component.

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

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

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
Methods

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
Methods

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
Methods
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.

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
Methods

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
Methods

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
Methods

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

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.

Note
The java.awtComponent class implements the ImageObserver interface. Therefore, in most applets, you may use the this keyword as the ImageObserver.

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
Methods

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:

FieldsPurpose
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
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
Methods

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

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
Methods
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.

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
Methods
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
Methods

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
Scrolls the list to make the specified index visible.

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
Methods

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

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