This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
<APPLET code="Scribble.class" width=500 height=300> Your browser does not support Java, or Java is not enabled. Sorry! Suppose we save this example HTML file as Scribble.html. Then to run this applet, you could use Sun's appletviewer command like this: % appletviewer Scribble.html You could also display the applet by viewing the Scribble.html file in your Web browser, if your browser supports Java applets. Figure 1.1 showed the Scribble applet running in Netscape Navigator.
Why Is Java Interesting?
http://localhost/java/javaref/javanut/ch01_02.htm (5 of 5) [20/12/2001 10:59:29]
How Java Differs from C
[Chapter 6] Applets
Chapter 6
6. Applets Contents: Introduction to Applets A First Applet Drawing Graphics Handling Events Reading Applet Parameters Images and Sounds JAR Files Applet Security Restrictions Signed Applets This chapter demonstrates the techniques of applet writing. It proceeds from a trivial "Hello World" applet to more sophisticated applets. Along the way, it explains how to: ● Draw graphics in your applet. ● Handle and respond to simple user input. ● Read and use values of applet parameters, allowing customization of an applet. ● Load and display images and load and play sounds. ● Package an applet and related files into a JAR file. ● Attach a digital signature to an applet. Study the examples carefully. They are the important part of this chapter! You may find it useful to refer to the quick reference in Chapter 17, The java.applet Package while reading these examples. Note that this chapter merely introduces the framework for writing applets. Applets, like other Java programs, use features from throughout the Java API. See Chapter 7, Events, in particular, for details on event processing in Java applets and applications.
http://localhost/java/javaref/javanut/ch06_01.htm (1 of 3) [20/12/2001 10:59:30]
[Chapter 6] Applets
6.1 Introduction to Applets An applet, as the name implies, is a kind of mini-application, designed to be run by a Web browser, or in the context of some other "applet viewer." Applets differ from regular applications in a number of ways. One of the most important is that there are a number of security restrictions on what applets are allowed to do. An applet often consists of untrusted code, so it cannot be allowed access to the local file system, for example. The details of applet security and the restrictions placed on applets are discussed at the end of this chapter. From a programmer's standpoint, one of the biggest differences between applets and applications is that applets do not have a main() method, or other single entry point from which the program starts running. Instead, to write an applet, you subclass the Applet class and override a number of standard methods. At appropriate times, under well-defined circumstances, the Web browser or applet viewer invokes the methods you have defined. The applet is not in control of the thread of execution; it simply responds when the browser or viewer tells it to. For this reason, the methods you write must take the necessary action and return promptly--they are not allowed to enter time-consuming (or infinite) loops. In order to perform a time-consuming or repetitive task, such as animation, an applet must create its own thread, over which it does have complete control. The task of writing an applet, then, comes down to defining the appropriate methods. A number of these methods are defined by the Applet class: init() Called when the applet is first loaded into the browser or viewer. It is typically used to perform applet initialization, in preference to a constructor method. (The Web browser doesn't pass any arguments to an applet's constructor method, so defining one isn't too useful.) destroy() Called when the applet is about to be unloaded from the browser or viewer. It should free any resources, other than memory, that the applet has allocated. start() Called when the applet becomes visible and should start doing whatever it is that it does. Often used with animation and with threads. stop() Called when the applet becomes temporarily invisible, for example, when the user has scrolled it off the screen. Tells the applet to stop performing an animation or other task. getAppletInfo() Called to get information about the applet. Should return a string suitable for display in a dialog box. getParameterInfo() Called to obtain information about the parameters the applet responds to. Should return strings describing those parameters.
http://localhost/java/javaref/javanut/ch06_01.htm (2 of 3) [20/12/2001 10:59:30]
[Chapter 6] Applets
In addition to these Applet methods, there are a number of other methods, inherited from superclasses of Applet, that the browser invokes at appropriate times, and that an applet should override. The most obvious of these methods is paint(), which the browser or viewer invokes to ask the applet to draw itself on the screen. In Java 1.1, a related method is print(), which an applet should override if it wants to display itself on paper differently than it does on the screen. There are quite a few other methods that applets should override to respond to events. For example, if an applet wants to respond to mouse clicks, it should override mouseDown(). (As we'll see in Chapter 7, Events, however, there are other, preferred, ways to receive mouse events in Java 1.1.) The Applet class also defines some methods that are commonly used by applets: getImage() Loads an image file from the network and returns an Image object. getAudioClip() Loads a sound clip from the network and returns an AudioClip object. getParameter() Looks up and returns the value of a named parameter, specified in the HTML file that refers to the applet with the tag. getCodeBase() Returns the base URL from which the applet class file was loaded. getDocumentBase() Returns the base URL of the HTML file that refers to the applet. showStatus() Displays a message in the status line of the browser or applet viewer. getAppletContext() Returns the AppletContext object for the applet. AppletContext defines the useful showDocument() method that asks the browser to load and display a new Web page.
Other New Features of Java 1.1
http://localhost/java/javaref/javanut/ch06_01.htm (3 of 3) [20/12/2001 10:59:30]
A First Applet
[Chapter 17] The java.applet Package
Chapter 17
17. The java.applet Package Contents: java.applet.Applet (JDK 1.0) java.applet.AppletContext (JDK 1.0) java.applet.AppletStub (JDK 1.0) java.applet.AudioClip (JDK 1.0) An applet is a small, embeddable Java program. The java.applet package is a small one. It contains the Applet class, which is the superclass of all applets, and three related interfaces. Figure 17.1 shows the class hierarchy of this package. See Chapter 6, Applets, for more information about this package. Figure 17.1: The java.applet package
17.1 java.applet.Applet (JDK 1.0) This class implements an applet. To create your own applet, you should create a subclass of this class and override some or all of the following methods. Note that you never need to call these methods--they are called when appropriate by a Web browser or other applet viewer. init() should perform any initialization for the applet; it is called when the applet first starts. destroy() should free up any resources that the applet is holding; it is called when the applet is about to be permanently stopped. start() is called to make the applet start doing whatever it is that it does. Often, it starts a thread to perform an animation or similar task. stop() should temporarily stop the applet from executing. It is called when the applet temporarily becomes hidden or non-visible.
http://localhost/java/javaref/javanut/ch17_01.htm (1 of 3) [20/12/2001 10:59:30]
[Chapter 17] The java.applet Package
getAppletInfo() should return text suitable for display in an About dialog posted by the Web browser or applet viewer. getParameterInfo() should return an arbitrary-length array of three-element arrays of strings where each element describes one of the parameters that this applet understands. The three elements of each parameter description are strings that specify, respectively, the parameter's name, type, and description. In addition to these methods, an applet also typically overrides several of the methods of java.awt.Component, notably the paint() method to draw the applet on the screen. There are also several Applet methods that you do not override but may call from applet code: showStatus() displays text in the Web browser or applet viewer's status line. getImage() and getAudioClip() read image (GIF and JPEG formats) and audio files (AU format) over the network and return corresponding Java objects. getParameter() looks up the value of a parameter specified with a tag within an <APPLET>... pair. getCodeBase() returns the base URL from which the applet's code was loaded, and getDocumentBase() returns the base URL from which the HTML document containing the applet was loaded. getAppletContext() returns an AppletContext object, which also has useful methods. public class Applet extends Panel { // Default Constructor: public Applet() // Public Instance Methods public void destroy(); public AppletContext getAppletContext(); public String getAppletInfo(); public AudioClip getAudioClip(URL url); public AudioClip getAudioClip(URL url, String name); public URL getCodeBase(); public URL getDocumentBase(); public Image getImage(URL url); public Image getImage(URL url, String name); public Locale getLocale(); // Overrides Component public String getParameter(String name); public String[][] getParameterInfo(); public void init(); public boolean isActive(); public void play(URL url); public void play(URL url, String name); public void resize(int width, int height); // Overrides Component public void resize(Dimension d); // Overrides Component public final void setStub(AppletStub stub); public void showStatus(String msg); public void start(); public void stop(); }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Container->Panel->Applet
http://localhost/java/javaref/javanut/ch17_01.htm (2 of 3) [20/12/2001 10:59:30]
[Chapter 17] The java.applet Package
Returned By: AppletContext.getApplet()
Reading a Quick Reference Entry
http://localhost/java/javaref/javanut/ch17_01.htm (3 of 3) [20/12/2001 10:59:30]
java.applet.AppletContext (JDK 1.0)
[Chapter 17] 17.2 java.applet.AppletContext (JDK 1.0)
Chapter 17 The java.applet Package
17.2 java.applet.AppletContext (JDK 1.0) This interface defines the methods that allow an applet to interact with the context in which it runs (which is usually a Web browser or an applet viewer). The object that implements the AppletContext interface is returned by Applet.getAppletContext(). You can use it to take advantage of a Web browser's cache, or to display a message to the user in the Web browser's or applet viewer's message area. The getAudioClip() and getImage() methods may make use of a Web browser's caching mechanism. showDocument() and showStatus() give an applet a small measure of control over the appearance of the browser or applet viewer. The getApplet() and getApplets() methods allow an applet to find out what other applets are running at the same time. public abstract interface AppletContext { // Public Instance Methods public abstract Applet getApplet(String name); public abstract Enumeration getApplets(); public abstract AudioClip getAudioClip(URL url); public abstract Image getImage(URL url); public abstract void showDocument(URL url); public abstract void showDocument(URL url, String target); public abstract void showStatus(String status); }
Returned By: Applet.getAppletContext(), AppletStub.getAppletContext()
java.applet.Applet (JDK 1.0)
http://localhost/java/javaref/javanut/ch17_02.htm [20/12/2001 10:59:30]
java.applet.AppletStub (JDK 1.0)
[Chapter 17] 17.3 java.applet.AppletStub (JDK 1.0)
Chapter 17 The java.applet Package
17.3 java.applet.AppletStub (JDK 1.0) This is an internal interface used when implementing an applet viewer. public abstract interface AppletStub { // Public Instance Methods public abstract void appletResize(int width, int height); public abstract AppletContext getAppletContext(); public abstract URL getCodeBase(); public abstract URL getDocumentBase(); public abstract String getParameter(String name); public abstract boolean isActive(); }
Passed To: Applet.setStub()
java.applet.AppletContext (JDK 1.0)
http://localhost/java/javaref/javanut/ch17_03.htm [20/12/2001 10:59:31]
java.applet.AudioClip (JDK 1.0)
[Chapter 2] How Java Differs from C
Chapter 2
2. How Java Differs from C Contents: The Name Space: Packages, Classes, and Members Comments No Preprocessor Unicode and Character Escapes Primitive Data Types Reference Data Types Objects Arrays Strings Operators Statements Exceptions and Exception Handling Miscellaneous Differences Java is a lot like C, which makes it relatively easy for C programmers to learn. But there are a number of important differences between C and Java, such as the lack of a preprocessor, the use of 16-bit Unicode characters, and the exception handling mechanism. This chapter explains those differences, so that programmers who already know C can start programming in Java right away! This chapter also points out similarities and differences between Java and C++. C++ programmers should beware, though: While Java borrows a lot of terminology and even syntax from C++, the analogies between Java and C++ are not nearly as strong as those between Java and C. C++ programmers should be careful not to be lulled into a false sense of familiarity with Java just because the languages share a number of keywords. One of the main areas in which Java differs from C, of course, is that Java is an object-oriented language and has mechanisms to define classes and create objects that are instances of those classes. Java's object-oriented features are a topic for a chapter of their own, and they'll be explained in detail in Chapter 3, Classes and Objects in Java.
http://localhost/java/javaref/javanut/ch02_01.htm (1 of 3) [20/12/2001 10:59:31]
[Chapter 2] How Java Differs from C
2.1 Program Structure and Environment A program in Java consists of one or more class definitions, each of which has been compiled into its own .class file of Java Virtual Machine object code. One of these classes must define a method main(), which is where the program starts running. [1] [1] Method is an object-oriented term for a procedure or function. You'll see it used throughout this book. To invoke a Java program, you run the Java interpreter, java, and specify the name of the class that contains the main() method. You should omit the .class extension when doing this. Note that a Java applet is not an application--it is a Java class that is loaded and run by an already running Java application such as a Web browser or applet viewer. The main() method that the Java interpreter invokes to start a Java program must have the following prototype: public static void main(String args[]) The Java interpreter runs until the main() method returns, or until the interpreter reaches the end of main(). If no threads have been created by the program, the interpreter exits. Otherwise, the interpreter continues running until the last thread terminates.
Command-Line Arguments The single argument to main() is an array of strings, conventionally named args or argv. The length of this array (which would be passed as the argc argument in C) is available as argv.length, as is the case with any Java array. The elements of the array are the arguments, if any, that appeared on the interpreter command line after the class name. Note that the first element of the array is not the name of the class, as a C programmer might expect it to be. Example 2.1 shows how you could write a UNIX-style echo command (a program that simply prints out its arguments) in Java. Example 2.1: An Echo Program in Java public class echo { public static void main(String argv[]) { for(int i=0; i < argv.length; i++) System.out.print(argv[i] + " "); System.out.print("\n"); System.exit(0); } }
http://localhost/java/javaref/javanut/ch02_01.htm (2 of 3) [20/12/2001 10:59:31]
[Chapter 2] How Java Differs from C
Program Exit Value Note that main() must be declared to return void. Thus you cannot return a value from your Java program with a return statement in main(). If you need to return a value, call System.exit() with the desired integer value, as we've done in Example 2.1. Note that the handling and interpretation of this exit value are, of course, operating-system dependent. System.exit() causes the Java interpreter to exit immediately, whether or not other threads are running.
Environment The Java API does not allow a Java program to read operating system environment variables because they are platform-dependent. However, Java defines a similar, platform-independent mechanism, known as the system properties list, for associating textual values with names. A Java program can look up the value of a named property with the System.getProperty() method: String homedir = System.getProperty("user.home"); String debug = System.getProperty("myapp.debug"); The Java interpreter automatically defines a number of standard system properties when it starts up. You can insert additional property definitions into the list by specifying the -D option to the interpreter: % java -Dmyapp.debug=true myapp See Chapter 14, System Properties for more information on system properties.
A Simple Example
http://localhost/java/javaref/javanut/ch02_01.htm (3 of 3) [20/12/2001 10:59:31]
The Name Space: Packages, Classes, and Members
[Chapter 6] 6.6 Images and Sounds
Chapter 6 Applets
6.6 Images and Sounds Example 6.5 shows a Java applet that implements a simple client-side imagemap, which has the capability to highlight the "hot spots" in the image and play a sound clip when the user clicks on the image. Figure 6.4 shows what this applet might look like, when configured with an appropriate image. Figure 6.4: An imagemap applet
This applet demonstrates quite a few important applet techniques: ● getParameter() looks up the name of the image to display and the audio clip to play when the user clicks, and it also reads a list of rectangles and URLs that define the hot spots and hyperlinks of the imagemap. ● The getImage() and getDocumentBase() methods load the image in the init() method, and Graphics.drawImage() displays the image in the paint() method. ● getAudioClip() loads a sound file in the init() method, and AudioClip.play() plays the sound in the mousePressed() method. ● Events are handled by an "event listener" object, which is defined by an inner class (see Chapter 5, Inner Classes and Other New Language Features). This is an example of the Java 1.1 event handling model (see Chapter 7, Events). Therefore, this applet only runs in Web browsers that support Java 1.1. ●
The showStatus() method displays the destination URL when the user presses the mouse button over a hot
http://localhost/java/javaref/javanut/ch06_06.htm (1 of 4) [20/12/2001 10:59:32]
[Chapter 6] 6.6 Images and Sounds
●
●
spot, while the AppletContext.showDocument() method makes the browser display that URL when the user releases the mouse button. The applet uses "XOR mode" of the Graphics class to highlight an area of the image in a way that can be easily "un-highlighted" by redrawing. The individual hot spots are represented by instances of a nested top-level class. The java.util.Vector class stores the list of hot spot objects, and java.util.StringTokenizer parses the descriptions of those hot spots.
The following HTML fragment shows an example of the properties read by this applet: <APPLET code="Soundmap.class" width=288 height=288> Example 6.5: An Imagemap Applet import java.applet.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.util.*; /** * A Java applet that simulates a client-side imagemap. * Plays a sound whenever the user clicks on one of the hyperlinks. */ public class Soundmap extends Applet { protected Image image; // The image to display. protected Vector rects; // A list of rectangles in it. protected AudioClip sound; // A sound to play on user clicks in a rectangle. /** Initialize the applet. */ public void init() { // Look up the name of the image, relative to a base URL, and load it. // Note the use of three Applet methods in this one line. image = this.getImage(this.getDocumentBase(), this.getParameter("image")); // Lookup and parse a list of rectangular areas and the URLs they map to. // The convenience routine getRectangleParameter() is defined below. rects = new Vector(); ImagemapRectangle r; for(int i = 0; (r = getRectangleParameter("rect" + i)) != null; i++) rects.addElement(r); // Look up a sound to play when the user clicks one of those areas. sound = this.getAudioClip(this.getDocumentBase(), this.getParameter("sound")); // Specify an "event listener" object to respond to mouse button http://localhost/java/javaref/javanut/ch06_06.htm (2 of 4) [20/12/2001 10:59:32]
[Chapter 6] 6.6 Images and Sounds
// presses and releases. Note that this is the Java 1.1 event model. // Note that it also uses a Java 1.1 inner class, defined below. this.addMouseListener(new Listener()); } /** Called when the applet is being unloaded from the system. * We use it here to "flush" the image we no longer need. This may * result in memory and other resources being freed more quickly. */ public void destroy() { image.flush(); } /** To display the applet, we simply draw the image. */ public void paint(Graphics g) { g.drawImage(image, 0, 0, this); } /** We override this method so that it doesn't clear the background * before calling paint(). No clear is necessary, since paint() overwrites * everything with an image. Causes less flickering this way. */ public void update(Graphics g) { paint(g); } /** Parse a comma-separated list of rectangle coordinates and a URL. * Used to read the imagemap rectangle definitions from applet parameters. */ protected ImagemapRectangle getRectangleParameter(String name) { int x, y, w, h; URL url; String value = this.getParameter(name); if (value == null) return null; try { StringTokenizer st = new StringTokenizer(value, ","); x = Integer.parseInt(st.nextToken()); y = Integer.parseInt(st.nextToken()); w = Integer.parseInt(st.nextToken()); h = Integer.parseInt(st.nextToken()); url = new URL(this.getDocumentBase(), st.nextToken()); } catch (NoSuchElementException e) { return null; } catch (NumberFormatException e) { return null; } catch (MalformedURLException e) { return null; } return new ImagemapRectangle(x, y, w, h, url); } /** * An instance of this inner class is used to respond to mouse events. */ class Listener extends MouseAdapter { /** The rectangle that the mouse was pressed in. */ private ImagemapRectangle lastrect; /** Called when a mouse button is pressed. */ public void mousePressed(MouseEvent e) { // On button down, check if we're inside one of the specified rectangles. // If so, highlight the rectangle, display a message, and play a sound. // The utility routine findrect() is defined below. ImagemapRectangle r = findrect(e); if (r == null) return; Graphics g = Applet.this.getGraphics(); g.setXORMode(Color.red); g.drawRect(r.x, r.y, r.width, r.height); // highlight rectangle Applet.this.showStatus("To: " + r.url); // display URL
http://localhost/java/javaref/javanut/ch06_06.htm (3 of 4) [20/12/2001 10:59:32]
[Chapter 6] 6.6 Images and Sounds
sound.play(); lastrect = r;
// play the sound // Remember the rectangle so it can be un-highlighted.
} /** Called when a mouse button is released. */ public void mouseReleased(MouseEvent e) { // When the button is released, un-highlight the rectangle. If the // mouse is still inside it, ask the browser to go to the URL. if (lastrect != null) { Graphics g = Applet.this.getGraphics(); g.setXORMode(Color.red); g.drawRect(lastrect.x, lastrect.y, lastrect.width, lastrect.height); Applet.this.showStatus(""); // Clear the message. ImagemapRectangle r = findrect(e); if ((r != null) && (r == lastrect)) // If still in the same rectangle Applet.this.getAppletContext().showDocument(r.url); // Go to the URL lastrect = null; } } /** Find the rectangle we're inside. */ protected ImagemapRectangle findrect(MouseEvent e) { int i, x = e.getX(), y = e.getY(); for(i = 0; i < rects.size(); i++) { ImagemapRectangle r = (ImagemapRectangle) rects.elementAt(i); if (r.contains(x, y)) return r; } return null; } } /** * A helper class. Just like java.awt.Rectangle, but with a URL field. * Note the use of a nested top-level class for neatness. */ static class ImagemapRectangle extends Rectangle { URL url; public ImagemapRectangle(int x, int y, int w, int h, URL url) { super(x, y, w, h); this.url = url; } } }
Reading Applet Parameters
http://localhost/java/javaref/javanut/ch06_06.htm (4 of 4) [20/12/2001 10:59:32]
JAR Files
[Chapter 6] 6.5 Reading Applet Parameters
Chapter 6 Applets
6.5 Reading Applet Parameters Example 6.4 shows an extension to our Scribble applet. The ColorScribble class is a subclass of Scribble that adds the ability to scribble in a configurable foreground color over a configurable background color. (The ColorScribble applet looks a lot like the Scribble applet of Figure 6.3 and is not pictured here.) ColorScribble has an init() method that reads the value of two "applet parameters" that can be optionally specified with the tag in the applet's HTML file. The returned string values are converted to colors and specified as the default foreground and background colors for the applet. Note that the init() method invokes its superclass's init() method, just in case a future version of Scribble defines that method to perform initialization. This example also introduces the getAppletInfo() and getParameterInfo() methods. These methods provide textual information about the applet (its author, its version, its copyright, etc.) and the parameters that it can accept (the parameter names, their types, and their meanings). An applet should generally define these methods, although the current generation of Web browsers do not actually ever make use of them. (The appletviewer application in the JDK does call these methods, however.) Example 6.4: Reading Applet Parameters import java.applet.*; import java.awt.*; public class ColorScribble extends Scribble { // Read in two color parameters and set the colors. public void init() { super.init(); Color foreground = getColorParameter("foreground"); Color background = getColorParameter("background"); if (foreground != null) this.setForeground(foreground); if (background != null) this.setBackground(background); } // Read the specified parameter. Interpret it as a hexadecimal // number of the form RRGGBB and convert it to a color. protected Color getColorParameter(String name) { String value = this.getParameter(name); http://localhost/java/javaref/javanut/ch06_05.htm (1 of 2) [20/12/2001 10:59:32]
[Chapter 6] 6.5 Reading Applet Parameters
try { return new Color(Integer.parseInt(value, 16)); } catch (Exception e) { return null; } } // Return information suitable for display in an About dialog box. public String getAppletInfo() { return "ColorScribble v. 0.02. Written by David Flanagan."; } // Return info about the supported parameters. Web browsers and applet // viewers should display this information, and may also allow users to // set the parameter values. public String[][] getParameterInfo() { return info; } // Here's the information that getParameterInfo() returns. // It is an array of arrays of strings describing each parameter. // Format: parameter name, parameter type, parameter description private String[][] info = { {"foreground", "hexadecimal color value", "foreground color"}, {"background", "hexadecimal color value", "background color"} }; } The following HTML fragment references the applet, and demonstrates how parameter values can be set with the tag: <APPLET code="ColorScribble.class" width=300 height=300>
Handling Events
http://localhost/java/javaref/javanut/ch06_05.htm (2 of 2) [20/12/2001 10:59:32]
Images and Sounds
[Chapter 1] Getting Started with Java
Chapter 1
1. Getting Started with Java Contents: Why Is Java Interesting? A Simple Example When it was introduced in late 1995, Java took the Internet by storm. Java 1.1, released in early 1997, nearly doubles the speed of the Java interpreter and includes many important new features. With the addition of APIs to support database access, remote objects, an object component model, internationalization, printing, encryption, digital signatures, and many other technologies, Java is now poised to take the rest of the programming world by storm. Despite all the hype surrounding Java and the new features of Java 1.1, it's important to remember that at its core, Java is just a programming language, like many others, and its APIs are just class libraries, like those of other languages. What is interesting about Java, and thus the source of much of the hype, is that it has a number of important features that make it ideally suited for programming in the heavily networked, heterogenous world of the late 1990s. The rest of this chapter describes those interesting features of Java and demonstrates some simple Java code. Chapter 4, What's New in Java 1.1 explores the new features that have been added to version 1.1 of the Java API.
1.1 Why Is Java Interesting? In one of their early papers about the language, Sun described Java as follows: Java: A simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language. Sun acknowledges that this is quite a string of buzzwords, but the fact is that, for the most part, they aptly describe the language. In order to understand why Java is so interesting, let's take a look at the language features behind the buzzwords.
http://localhost/java/javaref/javanut/ch01_01.htm (1 of 7) [20/12/2001 10:59:33]
[Chapter 1] Getting Started with Java
Object-Oriented Java is an object-oriented programming language. As a programmer, this means that you focus on the data in your application and methods that manipulate that data, rather than thinking strictly in terms of procedures. If you're accustomed to procedure-based programming in C, you may find that you need to change how you design your programs when you use Java. Once you see how powerful this new paradigm is, however, you'll quickly adjust to it. In an object-oriented system, a class is a collection of data and methods that operate on that data. Taken together, the data and methods describe the state and behavior of an object. Classes are arranged in a hierarchy, so that a subclass can inherit behavior from its superclass. A class hierarchy always has a root class; this is a class with very general behavior. Java comes with an extensive set of classes, arranged in packages, that you can use in your programs. For example, Java provides classes that create graphical user interface components (the java.awt package), classes that handle input and output (the java.io package), and classes that support networking functionality (the java.net package). The Object class (in the java.lang package) serves as the root of the Java class hierarchy. Unlike C++, Java was designed to be object-oriented from the ground up. Most things in Java are objects; the primitive numeric, character, and boolean types are the only exceptions. Strings are represented by objects in Java, as are other important language constructs like threads. A class is the basic unit of compilation and of execution in Java; all Java programs are classes. While Java is designed to look like C++, you'll find that Java removes many of the complexities of that language. If you are a C++ programmer, you'll want to study the object-oriented constructs in Java carefully. Although the syntax is often similar to C++, the behavior is not nearly so analogous. For a complete description of the object-oriented features of Java, see Chapter 3, Classes and Objects in Java.
Interpreted Java is an an interpreted language: the Java compiler generates byte-codes for the Java Virtual Machine (JVM), rather than native machine code. To actually run a Java program, you use the Java interpreter to execute the compiled byte-codes. Because Java byte-codes are platform-independent, Java programs can run on any platform that the JVM (the interpreter and run-time system) has been ported to. In an interpreted environment, the standard "link" phase of program development pretty much vanishes. If Java has a link phase at all, it is only the process of loading new classes into the environment, which is an incremental, lightweight process that occurs at run-time. This is in contrast with the slower and more cumbersome compile-link-run cycle of languages like C and C++.
Architecture Neutral and Portable Because Java programs are compiled to an architecture neutral byte-code format, a Java application can run on any system, as long as that system implements the Java Virtual Machine. This is a particularly important for applications distributed over the Internet or other heterogenous networks. But the architecture neutral approach is useful beyond the scope of network-based applications. As an application
http://localhost/java/javaref/javanut/ch01_01.htm (2 of 7) [20/12/2001 10:59:33]
[Chapter 1] Getting Started with Java
developer in today's software market, you probably want to develop versions of your application that can run on PCs, Macs, and UNIX workstations. With multiple flavors of UNIX, Windows 95, and Windows NT on the PC, and the new PowerPC Macintosh, it is becoming increasingly difficult to produce software for all of the possible platforms. If you write your application in Java, however, it can run on all platforms. The fact that Java is interpreted and defines a standard, architecture neutral, byte-code format is one big part of being portable. But Java goes even further, by making sure that there are no "implementation-dependent" aspects of the language specification. For example, Java explicitly specifies the size of each of the primitive data types, as well as its arithmetic behavior. This differs from C, for example, in which an int type can be 16, 32, or 64 bits long depending on the platform. While it is technically possible to write non-portable programs in Java, it is relatively easy to avoid the few platform-dependencies that are exposed by the Java API and write truly portable or "pure" Java programs. Sun's new "100% Pure Java" program helps developers ensure (and certify) that their code is portable. Programmers need only to make simple efforts to avoid non-portable pitfalls in order to live up to Sun's trademarked motto "Write Once, Run Anywhere."
Dynamic and Distributed Java is a dynamic language. Any Java class can be loaded into a running Java interpreter at any time. These dynamically loaded classes can then be dynamically instantiated. Native code libraries can also be dynamically loaded. Classes in Java are represented by the Class class; you can dynamically obtain information about a class at run-time. This is especially true in Java 1.1, with the addition of the Reflection API, which is introduced in Chapter 12, Reflection. Java is also called a distributed language. This means, simply, that it provides a lot of high-level support for networking. For example, the URL class and OArelated classes in the java.net package make it almost as easy to read a remote file or resource as it is to read a local file. Similarly, in Java 1.1, the Remote Method Invocation (RMI) API allows a Java program to invoke methods of remote Java objects, as if they were local objects. (Java also provides traditional lower-level networking support, including datagrams and stream-based connections through sockets.) The distributed nature of Java really shines when combined with its dynamic class loading capabilities. Together, these features make it possible for a Java interpreter to download and run code from across the Internet. (As we'll see below, Java implements strong security measures to be sure that this can be done safely.) This is what happens when a Web browser downloads and runs a Java applet, for example. Scenarios can be more complicated than this, however. Imagine a multi-media word processor written in Java. When this program is asked to display some type of data that it has never encountered before, it might dynamically download a class from the network that can parse the data, and then dynamically download another class (probably a Java "bean") that can display the data within a compound document. A program like this uses distributed resources on the network to dynamically grow and adapt to the needs of its user.
http://localhost/java/javaref/javanut/ch01_01.htm (3 of 7) [20/12/2001 10:59:33]
[Chapter 1] Getting Started with Java
Simple Java is a simple language. The Java designers were trying to create a language that a programmer could learn quickly, so the number of language constructs has been kept relatively small. Another design goal was to make the language look familiar to a majority of programmers, for ease of migration. If you are a C or C++ programmer, you'll find that Java uses many of the same language constructs as C and C++. In order to keep the language both small and familiar, the Java designers removed a number of features available in C and C++. These features are mostly ones that led to poor programming practices or were rarely used. For example, Java does not support the goto statement; instead, it provides labelled break and continue statements and exception handling. Java does not use header files and it eliminates the C preprocessor. Because Java is object-oriented, C constructs like struct and union have been removed. Java also eliminates the operator overloading and multiple inheritance features of C++. Perhaps the most important simplification, however, is that Java does not use pointers. Pointers are one of the most bug-prone aspects of C and C++ programming. Since Java does not have structures, and arrays and strings are objects, there's no need for pointers. Java automatically handles the referencing and dereferencing of objects for you. Java also implements automatic garbage collection, so you don't have to worry about memory management issues. All of this frees you from having to worry about dangling pointers, invalid pointer references, and memory leaks, so you can spend your time developing the functionality of your programs. If it sounds like Java has gutted C and C++, leaving only a shell of a programming language, hold off on that judgment for a bit. As we'll see in Chapter 2, How Java Differs from C, Java is actually a full-featured and very elegant language.
Robust Java has been designed for writing highly reliable or robust software. Java certainly doesn't eliminate the need for software quality assurance; it's still quite possible to write buggy software in Java. However, Java does eliminate certain types of programming errors, which makes it considerably easier to write reliable software. Java is a strongly typed language, which allows for extensive compile-time checking for potential type-mismatch problems. Java is more strongly typed than C++, which inherits a number of compile-time laxities from C, especially in the area of function declarations. Java requires explicit method declarations; it does not support C-style implicit declarations. These stringent requirements ensure that the compiler can catch method invocation errors, which leads to more reliable programs. One of the things that makes Java simple is its lack of pointers and pointer arithmetic. This feature also increases the robustness of Java programs by abolishing an entire class of pointer-related bugs. Similarly, all accesses to arrays and strings are checked at run-time to ensure that they are in bounds, eliminating the possibility of overwriting memory and corrupting data. Casts of objects from one type to another are also checked at run-time to ensure that they are legal. Finally, and very importantly, Java's automatic garbage collection prevents memory leaks and other pernicious bugs related to memory allocation and deallocation.
http://localhost/java/javaref/javanut/ch01_01.htm (4 of 7) [20/12/2001 10:59:33]
[Chapter 1] Getting Started with Java
Exception handling is another feature in Java that makes for more robust programs. An exception is a signal that some sort of exceptional condition, such as a "file not found" error, has occurred. Using the try/catch/finally statement, you can group all of your error handling code in one place, which greatly simplifies the task of error handling and recovery.
Secure One of the most highly touted aspects of Java is that it's a secure language. This is especially important because of the distributed nature of Java. Without an assurance of security, you certainly wouldn't want to download code from a random site on the Internet and let it run on your computer. Yet this is exactly what people do with Java applets every day. Java was designed with security in mind, and provides several layers of security controls that protect against malicious code, and allow users to comfortably run untrusted programs such as applets. At the lowest level, security goes hand-in-hand with robustness. As we've already seen, Java programs cannot forge pointers to memory, or overflow arrays, or read memory outside of the bounds of an array or string. These features are one of Java's main defenses against malicious code. By totally disallowing any direct access to memory, an entire huge, messy class of security attacks is ruled out. The second line of defense against malicious code is the byte-code verification process that the Java interpreter performs on any untrusted code it loads. These verification steps ensure that the code is well-formed--that it doesn't overflow or underflow the stack or contain illegal byte-codes, for example. If the byte-code verification step was skipped, inadvertently corrupted or maliciously crafted byte-codes might be able to take advantage of implementation weaknesses in a Java interpreter. Another layer of security protection is commonly referred to as the "sandbox model": untrusted code is placed in a "sandbox," where it can play safely, without doing any damage to the "real world," or full Java environment. When an applet, or other untrusted code, is running in the sandbox, there are a number of restrictions on what it can do. The most obvious of these restrictions is that it has no access whatsoever to the local file system. There are a number of other restrictions in the sandbox as well. These restrictions are enforced by a SecurityManager class. The model works because all of the core Java classes that perform sensitive operations, such as filesystem access, first ask permission of the currently installed SecurityManager. If the call is being made, directly or indirectly, by untrusted code, the security manager throws an exception, and the operation is not permitted. See Chapter 6, Applets for a complete list of the restrictions placed on applets running in the sandbox. Finally, in Java 1.1, there is another possible solution to the problem of security. By attaching a digital signature to Java code, the origin of that code can be established in a cryptographically secure and unforgeable way. If you have specified that you trust a person or organization, then code that bears the digital signature of that trusted entity is trusted, even when loaded over the network, and may be run without the restrictions of the sandbox model. Of course, security isn't a black-and-white thing. Just as a program can never be guaranteed to be 100% bug-free, no language or environment can be guaranteed 100% secure. With that said, however, Java does seem to offer a practical level of security for most applications. It anticipates and defends against most of the techniques that have historically been used to trick software into misbehaving, and it has been intensely scrutinized by security experts and hackers alike. Some security holes were found in early
http://localhost/java/javaref/javanut/ch01_01.htm (5 of 7) [20/12/2001 10:59:33]
[Chapter 1] Getting Started with Java
versions of Java, but these flaws were fixed almost as soon as they were found, and it seems reasonable to expect that any future holes will be fixed just as quickly.
High-Performance Java is an interpreted language, so it is never going to be as fast as a compiled language like C. Java 1.0 was said to be about 20 times slower than C. Java 1.1 is nearly twice as fast as Java 1.0, however, so it might be reasonable to say that compiled C code runs ten times as fast as interpreted Java byte-codes. But before you throw up your arms in disgust, be aware that this speed is more than adequate to run interactive, GUI and network-based applications, where the application is often idle, waiting for the user to do something, or waiting for data from the network. Furthermore, the speed-critical sections of the Java run-time environment, that do things like string concatenation and comparison, are implemented with efficient native code. As a further performance boost, many Java interpreters now include "just in time" compilers that can translate Java byte-codes into machine code for a particular CPU at run-time. The Java byte-code format was designed with these "just in time" compilers in mind, so the process of generating machine code is fairly efficient and it produces reasonably good code. In fact, Sun claims that the performance of byte-codes converted to machine code is nearly as good as native C or C++. If you are willing to sacrifice code portability to gain speed, you can also write portions of your program in C or C++ and use Java native methods to interface with this native code. When you are considering performance, it's important to remember where Java falls in the spectrum of available programming languages. At one end of the spectrum, there are high-level, fully-interpreted scripting languages such as Tcl and the UNIX shells. These languages are great for prototyping and they are highly portable, but they are also very slow. At the other end of the spectrum, you have low-level compiled languages like C and C++. These languages offer high performance, but they suffer in terms of reliability and portability. Java falls in the middle of the spectrum. The performance of Java's interpreted byte-codes is much better than the high-level scripting languages (even Perl), but it still offers the simplicity and portability of those languages.
Multithreaded In a GUI-based network application such as a Web browser, it's easy to imagine multiple things going on at the same time. A user could be listening to an audio clip while she is scrolling a page, and in the background the browser is downloading an image. Java is a multithreaded language; it provides support for multiple threads of execution (sometimes called lightweight processes) that can handle different tasks. An important benefit of multithreading is that it improves the interactive performance of graphical applications for the user. If you have tried working with threads in C or C++, you know that it can be quite difficult. Java makes programming with threads much easier, by providing built-in language support for threads. The java.lang package provides a Thread class that supports methods to start and stop threads and set thread priorities, among other things. The Java language syntax also supports threads directly with the synchronized keyword. This keyword makes it extremely easy to mark sections of code or entire methods that should only be run by a single thread at a time.
http://localhost/java/javaref/javanut/ch01_01.htm (6 of 7) [20/12/2001 10:59:33]
[Chapter 1] Getting Started with Java
While threads are "wizard-level" stuff in C and C++, their use is commonplace in Java. Because Java makes threads so easy to use, the Java class libraries require their use in a number of places. For example, any applet that performs animation does so with a thread. Similarly, Java does not support asynchronous, non-blocking I/O with notification through signals or interrupts--you must instead create a thread that blocks on every I/O channel you are interested in.
Acknowledgments
http://localhost/java/javaref/javanut/ch01_01.htm (7 of 7) [20/12/2001 10:59:33]
A Simple Example
[Chapter 6] 6.9 Signed Applets
Chapter 6 Applets
6.9 Signed Applets In Java 1.1 it is possible to circumvent these applet security restrictions by attaching a digital signature to a JAR file. When a Web browser or applet viewer loads a JAR file that has been signed by a trusted entity (the user specifies whom she trusts), the browser may grant the applet contained in the JAR file special privileges, such as the ability to read and write local files, that are not available to untrusted applets. Signing an applet with the javakey tool provided by the JDK is a somewhat cumbersome task. First, of course, you must have a security database set up. The database must contain the certificate and the public and private keys that you want to use to sign the applet. See the javakey documentation in Chapter 16, JDK Tools for details on this process. Once you have a properly configured security database, you must create a simple "directive file" that gives javakey the information it needs to sign your JAR file. A directive file might look like this: # The entity doing the signing signer=david # The certificate number to use cert=1 # Currently unused chain=0 # The base name of the signature files to be added to the JAR manifest signature.file=DAVIDSIG Having created a directive file named mysig, for example, you could then sign a JAR file like this: % javakey -gs mysig soundmap.jar This command creates a new JAR file named soundmap.jar.sig that you can use in an HTML archive attribute just as you would use an unsigned JAR file. The javakey tool is used for all aspects of administering the Java system security database. One of the other things you can do with it is to declare which entities are trusted. You do this with the -t option. For example, you might declare your trust for the author as follows:
http://localhost/java/javaref/javanut/ch06_09.htm (1 of 2) [20/12/2001 10:59:33]
[Chapter 6] 6.9 Signed Applets
% javakey -t DavidFlanagan true Or you could revoke your trust like this: % javakey -t DavidFlanagan false The appletviewer program makes use of any trust values declared in this way. Note that javakey and appletviewer support only untrusted entities and fully-trusted entities, without any gradations in between. We may see additional levels of trust in the future. Bear in mind that the javakey techniques described here apply only to the JDK. Other vendors may provide other mechanisms for signing applets, and Web browsers may provide other ways of declaring trusted entities.
Applet Security Restrictions
http://localhost/java/javaref/javanut/ch06_09.htm (2 of 2) [20/12/2001 10:59:33]
Events
[Chapter 16] JDK Tools
Chapter 16
16. JDK Tools Contents: appletviewer jar java javac javadoc javah javakey javap jdb native2ascii serialver
appletviewer Name appletviewer---The Java Applet Viewer
Availability JDK 1.0 and later.
Synopsis appletviewer [-debug]
[-Jjavaoption] [-encoding enc] url|file...
http://localhost/java/javaref/javanut/ch16_01.htm (1 of 6) [20/12/2001 10:59:33]
[Chapter 16] JDK Tools
Description appletviewer reads or downloads one or more HTML documents specified by filename or URL on the command line. It reads or downloads all the applets referenced in each document and displays them, each in their own window. If none of the named documents has an <APPLET> tag, appletviewer does nothing.
Options -debug If this option is specified, the appletviewer is started within jdb (the Java debugger). This allows you to debug the applets referenced by the document or documents. -Jjavaoption This option passes the following javaoption as a command-line argument to the Java interpreter. The specified javaoption should not contain spaces. If a multi-word option must be passed to the Java interpreter, multiple -J options should be used. See java for a list of valid Java interpreter options. Available in JDK 1.1 and later. -encodingenc This option specifies the character encoding that appletviewer should use when reading the contents of the specified files or URLs. It is used in the conversion of applet parameter values to Unicode. Available in JDK 1.1 and later.
Commands The window displayed by appletviewer contains a single Applet menu, with the following commands available: Restart Stops and destroys the current applet, then re-initializes and restarts it. Reload Stops, destroys, and unloads the applet, then reloads, reinitializes, and restarts it. Stop Stops the current applet. Available in Java 1.1 and later. Save Serializes the applet and saves the serialized applet in the file Applet.ser in the user's home directory. The applet should be stopped before selecting this option. Available in Java 1.1 and later. Start
http://localhost/java/javaref/javanut/ch16_01.htm (2 of 6) [20/12/2001 10:59:33]
[Chapter 16] JDK Tools
Restarts a stopped applet. Available in Java 1.1 and later. Clone Creates a new copy of the applet in a new appletviewer window. Tag Pops up a dialog box that displays the <APPLET> tag and all associated tags that created the current applet. Info Pops up a dialog box that contains information about the applet. This information is provided by the getAppletInfo() and getParameterInfo() methods implemented by the applet. Edit This command is not implemented. The Edit menu item is disabled. Character Encoding Displays the current character encoding in the status line. Available in Java 1.1 and later. Print Prints the applet. Available in Java 1.1 and later. Properties Displays a dialog that allows the user to set appletviewer preferences, including settings for firewall and caching proxy servers. Close Closes the current appletviewer window. Quit Quits appletviewer, closing all open windows.
Properties When it starts up, appletviewer reads property definitions from the file ~/.hotjava/properties (UNIX) or the .hotjava\properties file relative to the HOME environment variable (Windows). These properties are stored in the system properties list and are used to specify the various error and status messages the applet viewer displays, as well as its security policies and use of proxy servers. The properties that affect security and proxies are described below.
Security The following properties specify the security restrictions that appletviewer places on untrusted applets: acl.read
http://localhost/java/javaref/javanut/ch16_01.htm (3 of 6) [20/12/2001 10:59:33]
[Chapter 16] JDK Tools
This is a list of files and directories that an untrusted applet is allowed to read. The elements of the list should be separated with colons on UNIX systems and semicolons on Windows systems. On UNIX systems, the ~ character is replaced with the home directory of the current user. If the plus character appears as an element in the list, it is replaced by the value of the acl.read.default property. This provides an easy way to enable read access--by simply setting acl.read to "+". By default, untrusted applets are not allowed to read any files or directories. acl.read.default This is a list of files and directories that are readable by untrusted applets if the acl.read property contains a plus character. acl.write This is a list of files and directories that an untrusted applet is allowed to write to. The elements of the list should be separated with colons on UNIX systems and semicolons on Windows systems. On UNIX systems, the ~ character is replaced with the home directory of the current user. If the plus character appears as an element in the list, it is replaced by the value of the acl.write.default property. This provides an easy way to enable write access--by simply setting acl.write to "+". By default, untrusted applets are not allowed to write to any files or directories. acl.write.default This is a list of files and directories that are writable by untrusted applets if the acl.write property contains a plus character. appletviewer.security.mode This property specifies the types of network access an untrusted applet is allowed to perform. If it is set to "none", then the applet can perform no networking at all. The value "host" is the default, and specifies that the applet can connect only to the host from which it was loaded. The value "unrestricted" specifies that an applet may connect to any host without restrictions. package.restrict.access.package-prefix Properties of this form may be set to true to prevent untrusted applets from using classes in any package that has the specified package name prefix as the first component of its name. For example, to prevent applets from using any of the Sun classes (such as the Java compiler and the appletviewer itself) that are shipped with the JDK, you could specify the following property: package.restrict.access.sun=true appletviewer sets this property to true by default for the sun.* and netscape.* packages. package.restrict.definition.package-prefix Properties of this form may be set to true to prevent untrusted applets from defining classes in a package that has the specified package name prefix as the first component of its name. For example, to prevent an applet from defining classes in any of the standard Java packages, you could specify the following property:
http://localhost/java/javaref/javanut/ch16_01.htm (4 of 6) [20/12/2001 10:59:33]
[Chapter 16] JDK Tools
package.restrict.definition.java=true appletviewer sets this property to true by default for the java.*, sun.*, and netscape.* packages. property.applet When a property of this form is set to true in Java 1.1, it specifies that an applet should be allowed to read the property named property from the system properties list. By default, applets are only allowed to read ten standard system properties (see Chapter 14, System Properties, for a list). For example, to allow an applet to read the user.home property, specify a property of the form user.home.applet=true
Proxies appletviewer uses the following properties to configure its use of firewall and caching proxy servers: firewallHost This is the firewall proxy host to connect to if the firewallSet property is true. firewallPort This is the port of the firewall proxy host to connect to if the firewallSet property is true. firewallSet This tells you whether the applet viewer should use a firewall proxy. Values are true or false. proxyHost This is the caching proxy host to connect to if the proxySet property is true. proxyPort This is the port of the caching proxy host to connect to if the proxySet property is true. proxySet This tells you whether the applet viewer should use a caching proxy. Values are true or false.
Environment CLASSPATH Specifies an ordered list (colon-separated on UNIX, semicolon-separated on Windows systems) of directories and ZIP files in which appletviewer should look for class definitions. When a path is specified with this environment variable, appletviewer always implicitly appends the location of the system classes to the end of the path. If this environment variable is not specified, the default
http://localhost/java/javaref/javanut/ch16_01.htm (5 of 6) [20/12/2001 10:59:33]
[Chapter 16] JDK Tools
path is the current directory and the system classes. Note that appletviewer does not support the -classpath command-line argument, except indirectly through the -J option.
See Also java, javac, jdb
serialver
http://localhost/java/javaref/javanut/ch16_01.htm (6 of 6) [20/12/2001 10:59:34]
jar
[Chapter 29] 29.3 java.text.ChoiceFormat (JDK 1.1)
Chapter 29 The java.text Package
29.3 java.text.ChoiceFormat (JDK 1.1) This class is a subclass of Format that converts a number to a String in a way that is reminiscent of a switch statement or an enumerated type. Each ChoiceFormat object has an array of doubles known as its "limits" and an array of strings known as its "formats." When the format() method is called to format a number x, the ChoiceFormat finds an index i such that: limits[i] Format(Serializable, Cloneable)->NumberFormat(Cloneable)->ChoiceFormat
java.text.CharacterIterator (JDK 1.1)
java.text.CollationElementIterator (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_03.htm (2 of 2) [20/12/2001 10:59:34]
[Chapter 29] 29.9 java.text.DecimalFormat (JDK 1.1)
Chapter 29 The java.text Package
29.9 java.text.DecimalFormat (JDK 1.1) This is the concrete Format class used by NumberFormat for all locales that use base 10 numbers. Most applications do not need to use this class directly--they can use the static methods of NumberFormat to obtain a default NumberFormat object for a desired locale, and may then perform minor locale-independent customizations on that object. Applications that require highly-customized number formatting and parsing may create custom DecimalFormat objects by passing a suitable pattern to the DecimalFormat() constructor method. The applyPattern() method can be used to change this pattern. A pattern consists of a string of characters from the following table. For example: "$#,##0.00;($#,##0.00)". Character Meaning # A digit; zeros show as absent 0 A digit; zeros show as 0 . The locale-specific decimal separator , The locale-specific grouping separator The locale-specific negative prefix % Show value as a percentage ; Separates positive number format (on left) from optional negative number format (on right) ' Quote a reserved character, so it appears literally in the output other Appears literally in output A DecimalFormatSymbols object may be optionally specified when creating a DecimalFormat object. If one is not specified, a DecimalFormatSymbols object suitable for the default locale is used. public class DecimalFormat extends NumberFormat { // Public Constructors public DecimalFormat(); public DecimalFormat(String pattern); public DecimalFormat(String pattern, DecimalFormatSymbols symbols); // Public Instance Methods public void applyLocalizedPattern(String pattern); public void applyPattern(String pattern); public Object clone(); // Overrides NumberFormat public boolean equals(Object obj); // Overrides NumberFormat public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition); // Defines NumberFormat public StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition); // Defines NumberFormat
http://localhost/java/javaref/javanut/ch29_09.htm (1 of 2) [20/12/2001 10:59:34]
[Chapter 29] 29.9 java.text.DecimalFormat (JDK 1.1)
public public public public public public public public public public
DecimalFormatSymbols getDecimalFormatSymbols(); int getGroupingSize(); int getMultiplier(); String getNegativePrefix(); String getNegativeSuffix(); String getPositivePrefix(); String getPositiveSuffix(); int hashCode(); // Overrides NumberFormat boolean isDecimalSeparatorAlwaysShown(); Number parse(String text, ParsePosition status);
// Defines
NumberFormat public public public public public public public public public public
void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols); void setDecimalSeparatorAlwaysShown(boolean newValue); void setGroupingSize(int newValue); void setMultiplier(int newValue); void setNegativePrefix(String newValue); void setNegativeSuffix(String newValue); void setPositivePrefix(String newValue); void setPositiveSuffix(String newValue); String toLocalizedPattern(); String toPattern();
}
Hierarchy: Object->Format(Serializable, Cloneable)->NumberFormat(Cloneable)->DecimalFormat
java.text.DateFormatSymbols (JDK 1.1)
java.text.DecimalFormatSymbols (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_09.htm (2 of 2) [20/12/2001 10:59:34]
[Chapter 29] 29.13 java.text.MessageFormat (JDK 1.1)
Chapter 29 The java.text Package
29.13 java.text.MessageFormat (JDK 1.1) This class formats and substitutes objects into specified positions in a message string (also known as the "pattern" string). It provides the closest Java equivalent to the printf() function of the C programming language. If a message is to be displayed only a single time, the simplest way to use the MessageFormat class is through the static format() method which is passed a message or pattern string and an array of argument objects to be formatted and substituted into the string. If the message is to be displayed several times, it makes more sense to create a MessageFormat object, supplying the pattern string, and then to call the format() instance method of this object, supplying the array of objects to be formatted into the message. The message or pattern string used by the MessageFormat should contain digits enclosed in curly braces to indicate where each argument should be substituted. The sequence "{0}" indicates that the first object should be converted to a string (if necessary) and inserted at that point, while the sequence "{3}" indicates that the fourth object should be inserted, for example. If the object to be inserted is not a string, MessageFormat checks to see if it is a Date or a subclass of Number. If so, it uses a default DateFormat or NumberFormat object to convert the value to a string. If not, it simply invokes the object's toString() method to convert it. A digit within curly braces in a pattern string may be optionally followed by a comma, and one of the words "date", "time", "number", or "choice", to indicate that the corresponding argument should be formatted as a date, time, number, or choice before being substituted into the pattern string. Any of these keywords may additionally be followed by a comma and additional pattern information to be used in formatting the date, time, number, or choice. (See SimpleDateFormat, DecimalFormat, and ChoiceFormat for more information.) You can use the setLocale() method to specify a non-default Locale that the MessageFormat should use when obtaining DateFormat and NumberFormat objects to format dates, time, and numbers inserted into the pattern. You can change the Format object used at a particular position in the pattern with the setFormat() method. You can set a new pattern for the MessageFormat object by calling applyPattern(), and you can obtain a string that represents the current formatting pattern by calling toPattern(). MessageFormat also supports a parse() method that can parse an array of objects out of a specified string, according to the specified pattern. public class MessageFormat extends Format { // Public Constructor public MessageFormat(String pattern); // Class Methods public static String format(String pattern, Object[] arguments); // Public Instance Methods public void applyPattern(String newPattern); public Object clone(); // Overrides Format public boolean equals(Object obj); // Overrides Object public final StringBuffer format(Object[] source, StringBuffer result, FieldPosition ignore); public final StringBuffer format(Object source, StringBuffer result, http://localhost/java/javaref/javanut/ch29_13.htm (1 of 2) [20/12/2001 10:59:34]
[Chapter 29] 29.13 java.text.MessageFormat (JDK 1.1)
FieldPosition ignore); // Defines Format public Format[] getFormats(); public Locale getLocale(); public int hashCode(); // Overrides Object public Object[] parse(String source, ParsePosition status); public Object[] parse(String source) throws ParseException; public Object parseObject(String text, ParsePosition status); Format public void setFormat(int variable, Format newFormat); public void setFormats(Format[] newFormats); public void setLocale(Locale theLocale); public String toPattern(); }
Hierarchy: Object->Format(Serializable, Cloneable)->MessageFormat
java.text.Format (JDK 1.1)
java.text.NumberFormat (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_13.htm (2 of 2) [20/12/2001 10:59:34]
// Defines
[Chapter 29] 29.18 java.text.SimpleDateFormat (JDK 1.1)
Chapter 29 The java.text Package
29.18 java.text.SimpleDateFormat (JDK 1.1) This is the concrete Format subclass used by DateFormat to handle formatting and parsing of dates. Most applications should not use this class directly--instead, they should obtain a localized DateFormat object by calling one of the static methods of DateFormat. SimpleDateFormat formats dates and times according to a pattern, which specifies the positions of the various fields of the date, and a DateFormatSymbols object, which specifies important auxiliary data, such as the names of months. Applications that require highly customized date or time formatting can create a custom SimpleDateFormat object by specifying the desired pattern. This creates a SimpleDateFormat object that uses the DateFormatSymbols object for the default locale. You may also specify a locale explicitly to use the DateFormatSymbols object for that locale. Or, you can even provide an explicit DateFormatSymbols object of your own, if you need to format dates and times for an unsupported locale. You can use the applyPattern() method of a SimpleDateFormat to change the formatting pattern used by the object. The syntax of this pattern is described in the following table. Any characters in the format string that do not appear in this table appear literally in the formatted date. Field Full Form Short Form Year yyyy (4 digits) yy (2 digits) Month MMM (name) MM (2 digits), M (1 or 2 digits) Day of week EEEE EE Day of month dd (2 digits) d (1 or 2 digits) Hour (1-12) hh (2 digits) h (1 or 2 digits) Hour (0-23) HH (2 digits) H (1 or 2 digits) Hour (0-11) KK K Hour (1-24) kk k Minute mm Second ss Millisecond SSS AM/PM a Time zone zzzz zz Day of week in month F (e.g., 3rd Thursday) Day in year DDD (3 digits) D (1, 2, or 3 digits) Week in year ww Era (e.g., BC/AD) G public class SimpleDateFormat extends DateFormat { // Public Constructors public SimpleDateFormat(); public SimpleDateFormat(String pattern); public SimpleDateFormat(String pattern, Locale loc); http://localhost/java/javaref/javanut/ch29_18.htm (1 of 2) [20/12/2001 10:59:35]
[Chapter 29] 29.18 java.text.SimpleDateFormat (JDK 1.1)
public SimpleDateFormat(String pattern, DateFormatSymbols formatData); // Public Instance Methods public void applyLocalizedPattern(String pattern); public void applyPattern(String pattern); public Object clone(); // Overrides DateFormat public boolean equals(Object obj); // Overrides DateFormat public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos); // Defines DateFormat public DateFormatSymbols getDateFormatSymbols(); public int hashCode(); // Overrides DateFormat public Date parse(String text, ParsePosition pos); // Defines DateFormat public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols); public String toLocalizedPattern(); public String toPattern(); }
Hierarchy: Object->Format(Serializable, Cloneable)->DateFormat(Cloneable)->SimpleDateFormat
java.text.RuleBasedCollator (JDK 1.1)
java.text.StringCharacterIterator (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_18.htm (2 of 2) [20/12/2001 10:59:35]
[Chapter 4] 4.5 Other AWT Improvements
Chapter 4 What's New in Java 1.1
4.5 Other AWT Improvements In addition to the major change in the AWT event model, there have been quite a few other improvements to the AWT. These improvements are summarized in the sections below.
Printing Printing in Java 1.1 is implemented through the new PrintJob class and PrintGraphics interface. The PrintJob class represents a print request. When a PrintJob object is created, the user is prompted with a platform-dependent print dialog, which allows her to specify options such as which printer to use. The getGraphics() method of a PrintJob object returns a Graphics object that can be used for printing. This object is an instance of a subclass of Graphics that knows how to print in a platform-dependent way. The object also implements the PrintGraphics interface. To print a component, you simply pass this Graphics object to the component's print() method. If the component does not define this method, the default implementation simply invokes the paint() method, which usually does the right thing. When you want to print a component and all of its subcomponents, you can simply pass the Graphics object to the printAll() method of the component. Printing multiple pages is more complex, of course. The application is responsible for pagination of the output, and in order to draw the output on the page the application may also need to query the PrintJob object to determine the page size (in pixels) and page resolution (in pixels per inch). For security reasons, applets are not allowed to initiate print jobs; if they were, you could expect to see applets on the Net that automatically printed hardcopy advertisements to your printer! Note, however, that this does not mean that applets cannot print themselves when the browser or applet viewer initiates the print request object and invokes the printAll() method of the applet. Chapter 8, New AWT Features contains an example that uses the printing capabilities of Java 1.1.
http://localhost/java/javaref/javanut/ch04_05.htm (1 of 4) [20/12/2001 10:59:35]
[Chapter 4] 4.5 Other AWT Improvements
Cut-and-Paste Data transfer via the cut-and-paste metaphor is supported in Java 1.1 by the classes and interfaces in the java.awt.datatransfer package. One half of this package provides generic data-transfer functionality, and the other half provides the classes and interfaces needed for clipboard-based cut-and-paste. In future versions of the JDK, we can expect to see support for the drag-and-drop data transfer metaphor added to this package. For the purposes of data transfer, the DataFlavor class represents the notion of a data type or data format. A DataFlavor consists of a human-readable name for the flavor and one of two possible machine-readable format definitions. The first of the machine-readable descriptions is a String that specifies a MIME type for the transferred data. The second is a Class object that represents a Java class. When a DataFlavor is specified with a Class object, it is an instance of this class that is passed when data transfer actually occurs. Any value that can be transferred through the Java 1.1 data transfer mechanism must be represented by a class that implements the Transferable interface. This interface defines methods to query the data flavors that the class supports, and it defines a method that the data transfer mechanism calls to convert the transferable value into the appropriate form for a given DataFlavor. While the DataFlavor class and the Transferable interface define the fundamental data transfer mechanism, they, by themselves, are not enough to initiate or perform data transfer. For this purpose, java.awt.datatransfer also defines the Clipboard class and the ClipboardOwner interface. Together, they support a cut-and-paste metaphor for data transfer. Because strings are often transferred between applications, java.awt.datatransfer provides the StringSelection class. This class implements both the Transferable and the ClipboardOwner interfaces and makes it very easy to transfer textual data through cut-and-paste. Inter-application data transfer is performed through the system clipboard. It is also possible to perform intra-application transfers through a private clipboard that an application creates for itself. Note that untrusted applets are not allowed to access the system clipboard--there could be sensitive information contained on it that untrusted code should not have access to. This means that applets cannot participate in inter-application cut-and-paste. Chapter 8, New AWT Features provides an example that demonstrates intra-application cut-and-paste data transfer.
Popup Menus and Menu Shortcuts Java 1.1 adds support for popup menus to the AWT. The PopupMenu class is a subclass of Menu; menu items are added to it just as they are added to regular pulldown menus. A popup menu can be attached to an arbitrary AWT component, using the new add() method of the Component class. And, finally, a popup menu can be "popped up" by calling its show() method. (The menu pops itself down automatically.) An application typically displays a popup menu when the user clicks a certain mouse button over the component that the menu is attached to. However, different platforms traditionally use different mouse buttons to display popup menus. You can use the new isPopupTrigger() method of MouseEvent to determine whether a given mouse click has the appropriate modifiers set to trigger the popup menu for http://localhost/java/javaref/javanut/ch04_05.htm (2 of 4) [20/12/2001 10:59:35]
[Chapter 4] 4.5 Other AWT Improvements
the current platform. Java 1.1 also adds support for menu shortcut keys. The new MenuShortcut class represents a menu shortcut key. An instance of this class may optionally be specified whenever you create a MenuItem object. Again, different platforms use different modifier keys to invoke menu shortcuts, so when you create a MenuShortcut object, you specify only the key in question (plus, optionally, the Shift key). The system translates this into a platform-dependent shortcut using Ctrl, Alt, or some other modifier key. The example in Chapter 8, New AWT Features demonstrates both a popup menu and menu shortcuts.
Keyboard Focus Traversal The ability to operate a GUI without using the mouse is an important feature of any windowing toolkit. The addition of menu shortcuts in Java 1.1 is an important step in this direction. Java 1.1 also adds rudimentary facilities for keyboard focus traversal (i.e., moving keyboard focus among the individual components in a window) using the Tab and Shift-Tab keys. Under the new focus traversal scheme, components within a container are traversed in the order in which they were added to the container. (Note, however, that it is possible to override this order by specifying an explicit position within the container's component list for a new component as it is added to the container with the add() method.) Beyond adding components to their container in the order desired for traversal, nothing else is required of the programmer in order to make keyboard focus traversal work. If you are creating a custom component that can accept keyboard focus, you should override the isFocusTraversable() method to return true. The component should call the requestFocus() method it inherits from Component when the user clicks on it or otherwise activates it. Finally, when a component receives focus, (i.e., when its processFocusEvent() method is invoked), it should provide some sort of visual indication, such as a highlighted border, that it has the focus.
Miscellaneous Improvements The SystemColor class represents a color used by the desktop system. On some platforms, these colors may be dynamically updated while the system is running. The SystemColor class also implements quite a few constants that represent system colors for various GUI components. Thus, if you want your GUIs to match the desktop color scheme, you might create them using colors such as SystemColor.menu (the background color for menus) and SystemColor.menuText (foreground color for menus), for example. The treatment of fonts has been changed and improved somewhat in Java 1.1. The use of the font names "TimesRoman," "Helvetica," and "Courier" is now discouraged. Instead, you should use "serif," "sansserif," and "monospaced"--these names convey the essential style of the font face, without specifying the exact font to be used. The font names "Dialog" and "DialogInput" are still supported in Java 1.1. An important reason for switching to generic font names is that Java can now display any Unicode character for which there is an appropriate font installed on the host system. The names "serif" and "sansserif" have meaning even when applied to non-Latin character sets, such as Japanese Kanji
http://localhost/java/javaref/javanut/ch04_05.htm (3 of 4) [20/12/2001 10:59:35]
[Chapter 4] 4.5 Other AWT Improvements
characters; the names "timesroman" and "helvetica" clearly do not. Another result of this fuller Unicode support is that the use of the "ZapfDingbats" font is also discouraged. Instead, regardless of what font you are using, you can simply encode these graphical symbols using Unicode characters between \u2700 and \u27ff. (See Chapter 11, Internationalization for an example.) This improved support for Unicode makes it much easier to write internationalized programs in Java. In Java 1.0, mouse cursors could only be specified for a Frame. In Java 1.1, every component can have a its own cursor, represented by the new Cursor object. There are new methods of Component for setting and querying the cursor. This change does not add any new predefined cursor images, nor does it add the ability to create custom cursors; it merely allows you to specify a cursor for any arbitrary component, and to do so in a more logical fashion. The ScrollPane class is new in Java 1.1. It is a Container that makes it very easy to scroll a large component or GUI within a smaller visible area. Doing this in Java 1.0 required a custom container, and suffered from some serious performance problems. Chapter 8, New AWT Features shows the use of a ScrollPane object. Another new feature is the ability to create "lightweight components." These are components and containers that do not have a native window of their own. In Java 1.0, custom components and containers had to be subclassed from Canvas or Panel. In Java 1.1, however, you can subclass Component and Container directly. Doing so creates a simpler component or container, without the overhead of a native window. It also allows you to create partially transparent components that appear non-rectangular. Java 1.1 also includes several miscellaneous changes to clipping and image manipulation: ● The Graphics class defines a method to set an arbitrary clipping rectangle, even to one that is larger than the current clipping region. There is also a new method to query the current clipping region. ● Graphics also defines two new drawImage() methods that are more flexible than the existing drawImage() methods. These new methods allow arbitrary image cropping, scaling, and flipping. ● There are two new classes, ReplicateScaleFilter and AreaAveragingScaleFilter, that can be used to scale an image as it is loaded, and a new convenience method, Image.getScaledInstance(), to obtain a new Image object that contains a scaled version of some other Image. ● New methods have been added to the MemoryImageSource class that allow images generated from memory to be dynamically and efficiently updated, allowing a kind of image animation. ● New methods have been added to the PixelGrabber class to make it more efficient and flexible to use.
Deprecated Features
http://localhost/java/javaref/javanut/ch04_05.htm (4 of 4) [20/12/2001 10:59:35]
Internationalization
[Chapter 21] The java.awt.image Package
Chapter 21
21. The java.awt.image Package Contents: java.awt.image.ColorModel (JDK 1.0) java.awt.image.CropImageFilter (JDK 1.0) java.awt.image.DirectColorModel (JDK 1.0) java.awt.image.FilteredImageSource (JDK 1.0) java.awt.image.ImageConsumer (JDK 1.0) java.awt.image.ImageFilter (JDK 1.0) java.awt.image.ImageObserver (JDK 1.0) java.awt.image.ImageProducer (JDK 1.0) java.awt.image.IndexColorModel (JDK 1.0) java.awt.image.MemoryImageSource (JDK 1.0) java.awt.image.PixelGrabber (JDK 1.0) java.awt.image.RGBImageFilter (JDK 1.0) java.awt.image.ReplicateScaleFilter (JDK 1.1) The java.awt.image package is, by any standard, a confusing one. The purpose of the package is to support image processing, and the classes in the package provide a powerful infrastructure for that purpose. (see Figure 21.1.) Most of the classes are part of the infrastructure, however, and are not normally used by ordinary applications that have only simple image manipulation requirements. To understand this package, it is first important to note that the Image class itself is part of the java.awt package, not the java.awt.image package. Furthermore, the java.awt.image classes are not the source of images; they simply serve to manipulate images that come from somewhere else. The Applet.getImage() method is perhaps the most common method for obtaining an image in Java--it downloads the image from a specified URL. In a stand-alone application, the URL.getContent() method can be used to obtain an ImageProducer object, which can then be passed to the Component.createImage() method to obtain an Image object. Figure 21.1: The java.awt.image package
http://localhost/java/javaref/javanut/ch21_01.htm (1 of 3) [20/12/2001 10:59:36]
[Chapter 21] The java.awt.image Package
The ImageProducer interface is one you'll encounter frequently in java.awt.image. It represents an image source. If you've created an Image object with Applet.getImage(), you can obtain the ImageProducer for that Image (which has not been downloaded yet) with Image.getSource(). Conversely, given an ImageProducer object, you can create an Image from it with the createImage() method of any Component (such as an Applet). Once you have an ImageProducer object, you can manipulate it with the other java.awt.image classes. FilteredImageSource is the most important class for image manipulation. It is itself a type of ImageProducer that, when created, applies a specified ImageFilter object to some other specified ImageProducer object. The FilteredImageSource thus configured can be used as an ImageProducer to display a filtered image. CropImageFilter is a predefined type of ImageFilter that you can use to extract a specified rectangle out of a larger image. RGBImageFilter is another subclass of ImageFilter that makes it easy to filter the colors of an image. To do so, you must subclass RGBImageFilter and provide the definition of a single simple method that manipulates the image colors. In order to manipulate image colors, you will probably need to be familiar with the ColorModel class and its two subclasses, DirectColorModel and IndexColorModel. An instance of ColorModel or of one of its subclasses converts a pixel value to the red, green, and blue components of the color it represents. Finally, two other classes in the java.awt.image package are worth noting. MemoryImageSource is a type of ImageProducer that generates an image from an array of bytes or integers in memory. PixelGrabber does the reverse--it captures pixels from an ImageProducer and stores them into an array. You can use these classes separately or together to perform your own custom image manipulation.
21.1 java.awt.image.AreaAveragingScaleFilter (JDK 1.1) This class implements an ImageFilter that scales an image to a specified pixel size. It uses a scaling algorithm that averages adjacent pixel values when shrinking an image, which produces relatively smooth scaled images. Its superclass, ReplicateScaleFilter, implements a faster, less smooth scaling algorithm. The methods of this class are ImageConsumer methods intended for communication between the image filter and the FilteredImageSource that uses it. Applications do not usually call these methods directly. The easiest way to use this filter is to call Image.getScaledInstance(), specifying an appropriate hint constant. public class AreaAveragingScaleFilter extends ReplicateScaleFilter { http://localhost/java/javaref/javanut/ch21_01.htm (2 of 3) [20/12/2001 10:59:36]
[Chapter 21] The java.awt.image Package
// Public Constructor public AreaAveragingScaleFilter(int width, int height); // Public Instance Methods public void setHints(int hints); // Overrides ImageFilter public void setPixels(int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize); public void setPixels'u'// Overrides ReplicateScaleFilter public void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize); public void setPixels'u'// Overrides ReplicateScaleFilter }
Hierarchy: Object->ImageFilter(ImageConsumer, Cloneable)-> ReplicateScaleFilter->AreaAveragingScaleFilter
java.awt.event.WindowListener (JDK 1.1)
java.awt.image.ColorModel (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_01.htm (3 of 3) [20/12/2001 10:59:36]
[Chapter 2] 2.6 Primitive Data Types
Chapter 2 How Java Differs from C
2.6 Primitive Data Types Java adds byte and boolean primitive types to the standard set of C types. In addition, it strictly defines the size and signedness of its types. In C, an int may be 16, 32, or 64 bits, and a char may act signed or unsigned depending on the platform. Not so in Java. In C, an uninitialized local variable usually has garbage as its value. In Java, all variables have guaranteed default values, though the compiler may warn you in places where you rely, accidentally or not, on these default values. Table 2.2 lists Java's primitive data types. The subsections below provide details about these types. Table 2.2: Java Primitive Data Types Min Value Type
Contains
Default Size
boolean true or false false 1 bit
Max Value N.A. N.A.
char
Unicode character \u0000 16 bits \u0000
byte
0
\uFFFF 8 bits -128
0
127 16 bits -32768
short
signed integer signed integer
32767 int long
signed integer signed integer
0
32 bits -2147483648
0
2147483647 64 bits -9223372036854775808 9223372036854775807
float
IEEE 754 floating-point
double IEEE 754 floating-point
0.0
32 bits +/-3.40282347E+38 +/-1.40239846E-45
0.0
64 bits +/-1.79769313486231570E+308 +/-4.94065645841246544E-324
http://localhost/java/javaref/javanut/ch02_06.htm (1 of 3) [20/12/2001 10:59:36]
[Chapter 2] 2.6 Primitive Data Types
The boolean Type boolean values are not integers, may not be treated as integers, and may never be cast to or from any other type. To perform C-style conversions between a boolean value b and an int i, use the following code: b = (i != 0); i = (b)?1:0;
// integer-to-boolean: non-0 -> true; 0 -> false; // boolean-to-integer: true -> 1; false -> 0;
The char Type char values represent characters. Character literals may appear in a Java program between single quotes. For example: char c = 'A'; All of the standard C character escapes, as well as Unicode escapes, are also supported in character literals. For example: char newline = '\n', apostrophe = '\", delete = '\377', aleph='\u05D0'; Values of type char do not have a sign. If a char is cast to a byte or a short, a negative value may result. The char type in Java holds a two-byte Unicode character. While this may seem intimidating to those not familiar with Unicode and the techniques of program internationalization, it is in fact totally transparent. Java does not provide a way to compute the size of a variable, nor does it allow any sort of pointer arithmetic. What this means is that if you are only using ASCII or Latin-1 characters, there is no way to distinguish a Java char from a C char.
Integral Types The integral types in Java are byte, short, char, int, and long. Literals for these types are written just as they are in C. All integral types, other than char, are signed. There is no unsigned keyword as there is in C. It is not legal to write long int or short int as it is in C. A long constant may be distinguished from other integral constants by appending the character l or L to it. Integer division by zero or modulo zero causes an ArithmeticException to be thrown. [3] [3] Exceptions signal errors in Java. Exception handling is described later in this chapter.
Floating-Point Types The floating-point types in Java are float and double. Literals for these types are written just as they are in C. Literals may be specified to be of type float by appending an f or F to the value; they may be specified to be of type double by appending a d or D.
http://localhost/java/javaref/javanut/ch02_06.htm (2 of 3) [20/12/2001 10:59:36]
[Chapter 2] 2.6 Primitive Data Types
float and double types have special values that may be the result of certain floating-point operations: positive infinity, negative infinity, negative zero and not-a-number. The java.lang.Float and java.lang.Double classes define some of these values as constants: POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN. NaN is unordered--comparing it to any other number, including itself, yields false. Use Float.isNaN() or Double.isNaN() to test for NaN. Negative zero compares equal to regular zero (positive zero), but the two zeros may be distinguished by division: one divided by negative zero yields negative infinity; one divided by positive zero yields positive infinity. Floating-point arithmetic never causes exceptions, even in the case of division by zero.
String Literals Strings in Java are not a primitive type, but are instances of the String class. However, because they are so commonly used, string literals may appear between quotes in Java programs, just as they do in C. When the compiler encounters such a string literal, it automatically creates the necessary String object.
Unicode and Character Escapes
http://localhost/java/javaref/javanut/ch02_06.htm (3 of 3) [20/12/2001 10:59:36]
Reference Data Types
[Chapter 25] 25.2 java.lang.ArithmeticException (JDK 1.0)
Chapter 25 The java.lang Package
25.2 java.lang.ArithmeticException (JDK 1.0) A RuntimeException that signals an exceptional arithmetic condition, such as integer division by zero. public class ArithmeticException extends RuntimeException { // Public Constructors public ArithmeticException(); public ArithmeticException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->ArithmeticException
Thrown By: BigDecimal.divide(), BigDecimal.setScale(), BigInteger.add(), BigInteger.clearBit(), BigInteger.divide(), BigInteger.divideAndRemainder(), BigInteger.flipBit(), BigInteger.modInverse(), BigInteger.pow(), BigInteger.remainder(), BigInteger.setBit(), BigInteger.testBit()
java.lang.AbstractMethodError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_02.htm [20/12/2001 10:59:36]
java.lang.ArrayIndexOutOfBoundsException (JDK 1.0)
[Chapter 25] 25.60 java.lang.System (JDK 1.0)
Chapter 25 The java.lang Package
25.60 java.lang.System (JDK 1.0) This class defines methods that provide a platform-independent interface to system functions. All of the methods and variables of this class are static. The class may not be instantiated. getProperty() looks up a named property on the system properties list, returning the optionally specified default value if no property definition was found. getProperties() returns the entire properties list. setProperties() sets a Properties object on the properties list. The in, out, and err variables are the system standard input, output, and error streams. arraycopy() copies an array or a portion of an array into a destination array. currentTimeMillis() returns the current time in milliseconds since midnight GMT on January 1, 1970. exit(), gc(), load(), loadLibrary(), and runFinalization() invoke the methods of the same name in the Runtime object. See Runtime for details. public final class System extends Object { // No Constructor // Constants public static final PrintStream err; public static final InputStream in; public static final PrintStream out; // Class Methods public static native void arraycopy(Object src, int src_position, Object dst, int dst_position, int length); public static native long currentTimeMillis(); public static void exit(int status); public static void gc(); public static Properties getProperties(); public static String getProperty(String key); public static String getProperty(String key, String def); public static SecurityManager getSecurityManager(); # public static String getenv(String name); 1.1public static native int identityHashCode(Object x); public static void load(String filename); public static void loadLibrary(String libname); public static void runFinalization(); 1.1public static void runFinalizersOnExit(boolean value); 1.1public static void setErr(PrintStream err); 1.1public static void setIn(InputStream in); 1.1public static void setOut(PrintStream out); public static void setProperties(Properties props); public static void setSecurityManager(SecurityManager s); }
http://localhost/java/javaref/javanut/ch25_60.htm (1 of 2) [20/12/2001 10:59:37]
[Chapter 25] 25.60 java.lang.System (JDK 1.0)
java.lang.StringIndexOutOfBoundsException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_60.htm (2 of 2) [20/12/2001 10:59:37]
java.lang.Thread (JDK 1.0)
[Chapter 26] The java.lang.reflect Package
Chapter 26
26. The java.lang.reflect Package Contents: java.lang.reflect.Array (JDK 1.1) java.lang.reflect.Constructor (JDK 1.1) java.lang.reflect.Field (JDK 1.1) java.lang.reflect.InvocationTargetException (JDK 1.1) java.lang.reflect.Member (JDK 1.1) java.lang.reflect.Method (JDK 1.1) java.lang.reflect.Modifier (JDK 1.1) The java.lang.reflect package contains the classes and interfaces that, along with java.lang.Class, comprise the Java Reflection API. This package is new in Java 1.1. Figure 26.1 shows the class hierarchy. The Constructor, Field, and Method classes represent constructors, fields, and methods of a class. Because these types all represent members of a class, they each implement the Member interface, which defines a simple set of methods that can be invoked for any class member. These classes allow information about the class members to be obtained, and allow methods and constructors to be invoked and fields to be queried and set. Class member modifiers are represented as integers that specify a number of bit flags. The Modifier class defines static methods that are useful in interpreting the meanings of these flags. The Array class defines static methods for creating arrays and reading and writing array elements. See Chapter 12, Reflection for examples of using these classes. Figure 26.1: The java.lang.reflect package
http://localhost/java/javaref/javanut/ch26_01.htm (1 of 3) [20/12/2001 10:59:37]
[Chapter 26] The java.lang.reflect Package
26.1 java.lang.reflect.Array (JDK 1.1) This class contains methods that allow you to set and query the values of array elements, to determine the length of an array, and to create new instances of arrays. Note that the Array class is used for manipulating array values, not array types; Java data types, including array types, are represented by java.lang.Class. Since the Array class represents a Java value, unlike the Field, Method, and Constructor classes which represent class members, the Array class is significantly different (despite some surface similarities) from those other classes in this package. Most notably, all the methods of Array are static and apply to all array values, rather than applying only to a specific field, method, or constructor. The get() method returns the value of the specified element of the specified array as an Object. If the array elements are of a primitive type, the value is converted to a wrapper object before being returned. You can also use getInteger() and related methods to query array elements and return them as specific primitive types. The set() method and its primitive type variants perform the opposite operation. Also, the getLength() method returns the length of the array. The newInstance() methods create new arrays. One version of this method is passed the number of elements in the array and the type of those elements. The other version of this method creates multidimensional arrays. Besides just specifying the component type of the array, it is passed an array of numbers. The length of this array specifies the number of dimensions for the array to be created, and the values of each array element specify the size of each dimension of the created array. public final class Array extends Object { // No Constructor // Class Methods public static native Object get(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native boolean getBoolean(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native byte getByte(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native char getChar(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native double getDouble(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native float getFloat(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native int getInt(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native int getLength(Object array) throws IllegalArgumentException; public static native long getLong(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native short getShort(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static Object newInstance(Class componentType, int length) throws NegativeArraySizeException; public static Object newInstance(Class componentType, int[] dimensions) throws IllegalArgumentException, NegativeArraySizeException; public static native void set(Object array, int index, Object value) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native void setBoolean(Object array, int index, boolean z) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native void setByte(Object array, int index, byte b) Xsthrows IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native void setChar(Object array, int index, char c) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native void setDouble(Object array, int index, double d) http://localhost/java/javaref/javanut/ch26_01.htm (2 of 3) [20/12/2001 10:59:37]
[Chapter 26] The java.lang.reflect Package
throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native void setFloat(Object array, int index, float f) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native void setInt(Object array, int index, int i) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native void setLong(Object array, int index, long l) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; public static native void setShort(Object array, int index, short s) throws IllegalArgumentException, ArrayIndexOutOfBoundsException; }
java.lang.Void (JDK 1.1)
java.lang.reflect.Constructor (JDK 1.1)
http://localhost/java/javaref/javanut/ch26_01.htm (3 of 3) [20/12/2001 10:59:37]
[Chapter 25] 25.3 java.lang.ArrayIndexOutOfBoundsException (JDK 1.0)
Chapter 25 The java.lang Package
25.3 java.lang.ArrayIndexOutOfBoundsException (JDK 1.0) Signals that an array index less than zero or greater than or equal to the array size has been used. public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException { // Public Constructors public ArrayIndexOutOfBoundsException(); public ArrayIndexOutOfBoundsException(int index); public ArrayIndexOutOfBoundsException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException-> IndexOutOfBoundsException->ArrayIndexOutOfBoundsException
Thrown By: Array.get(), Array.getBoolean(), Array.getByte(), Array.getChar(), Array.getDouble(), Array.getFloat(), Array.getInt(), Array.getLong(), Array.getShort(), Array.set(), Array.setBoolean(), Array.setByte(), Array.setChar(), Array.setDouble(), Array.setFloat(), Array.setInt(), Array.setLong(), Array.setShort()
java.lang.ArithmeticException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_03.htm [20/12/2001 10:59:37]
java.lang.ArrayStoreException (JDK 1.0)
[Chapter 25] 25.4 java.lang.ArrayStoreException (JDK 1.0)
Chapter 25 The java.lang Package
25.4 java.lang.ArrayStoreException (JDK 1.0) Signals an attempt to store the wrong type of object into an array. public class ArrayStoreException extends RuntimeException { // Public Constructors public ArrayStoreException(); public ArrayStoreException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->ArrayStoreException
java.lang.ArrayIndexOutOfBoundsException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_04.htm [20/12/2001 10:59:37]
java.lang.Boolean (JDK 1.0)
[Chapter 25] 25.38 java.lang.NegativeArraySizeException (JDK 1.0)
Chapter 25 The java.lang Package
25.38 java.lang.NegativeArraySizeException (JDK 1.0) Signals an attempt to allocate an array with fewer than zero elements. public class NegativeArraySizeException extends RuntimeException { // Public Constructors public NegativeArraySizeException(); public NegativeArraySizeException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->NegativeArraySizeException
Thrown By: Array.newInstance()
java.lang.Math (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_38.htm [20/12/2001 10:59:38]
java.lang.NoClassDefFoundError (JDK 1.0)
[Chapter 30] 30.26 java.util.Vector (JDK 1.0)
Chapter 30 The java.util Package
30.26 java.util.Vector (JDK 1.0) This class implements an array of objects that grows in size as necessary. It is useful when you need to keep track of a number of objects but do not know in advance how many there will be. There are a number of methods for storing objects in and removing objects from the Vector. Other methods look up the object at specified positions in the Vector, or search for specified objects within the Vector. elements() returns an Enumeration of the objects stored in the Vector. size() returns the number of objects currently stored in the Vector. capacity() returns the number of elements that may be stored before the vector's internal storage must be reallocated. public class Vector extends Object implements Cloneable, Serializable { // Public Constructors public Vector(int initialCapacity, int capacityIncrement); public Vector(int initialCapacity); public Vector(); // Protected Instance Variables protected int capacityIncrement; protected int elementCount; protected Object[] elementData; // Public Instance Methods public final synchronized void addElement(Object obj); public final int capacity(); public synchronized Object clone(); // Overrides Object public final boolean contains(Object elem); public final synchronized void copyInto(Object[] anArray); public final synchronized Object elementAt(int index); public final synchronized Enumeration elements(); public final synchronized void ensureCapacity(int minCapacity); public final synchronized Object firstElement(); public final int indexOf(Object elem); public final synchronized int indexOf(Object elem, int index); public final synchronized void insertElementAt(Object obj, int index); public final boolean isEmpty(); public final synchronized Object lastElement(); public final int lastIndexOf(Object elem); public final synchronized int lastIndexOf(Object elem, int index); public final synchronized void removeAllElements(); public final synchronized boolean removeElement(Object obj); public final synchronized void removeElementAt(int index); public final synchronized void setElementAt(Object obj, int index); public final synchronized void setSize(int newSize); public final int size(); public final synchronized String toString(); // Overrides Object http://localhost/java/javaref/javanut/ch30_26.htm (1 of 2) [20/12/2001 10:59:38]
[Chapter 30] 30.26 java.util.Vector (JDK 1.0)
public final synchronized void trimToSize(); }
Extended By: Stack
java.util.TooManyListenersException (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_26.htm (2 of 2) [20/12/2001 10:59:38]
The java.util.zip Package
[Chapter 17] 17.4 java.applet.AudioClip (JDK 1.0)
Chapter 17 The java.applet Package
17.4 java.applet.AudioClip (JDK 1.0) This interface describes the essential methods that an audio clip must have. AppletContext.getAudioClip() and Applet.getAudioClip() both return an object that implements this interface. The current JDK implementations of this interface only work with sounds encoded in AU format. The AudioClip interface is in the java.applet package only because there is not a better place for it. public abstract interface AudioClip { // Public Instance Methods public abstract void loop(); public abstract void play(); public abstract void stop(); }
Returned By: Applet.getAudioClip(), AppletContext.getAudioClip()
java.applet.AppletStub (JDK 1.0)
http://localhost/java/javaref/javanut/ch17_04.htm [20/12/2001 10:59:38]
The java.awt Package
[Chapter 24] 24.28 java.io.InputStream (JDK 1.0)
Chapter 24 The java.io Package
24.28 java.io.InputStream (JDK 1.0) This abstract class is the superclass of all input streams. It defines the basic input methods that all input stream classes provide. read() reads a single byte or an array or subarray of bytes. It returns the byte read, or the number of bytes read, or -1 if the end-of-file has been reached. skip() skips a specified number of bytes of input. available() returns the number of bytes that can be read without blocking. close() closes the input stream and frees up any system resources associated with it. The stream should not be used after close() has been called. If markSupported() returns true for a given InputStream, that stream supports mark() and reset() methods. mark() marks the current position in the input stream so that reset() can return to that position as long as no more than the specified number of bytes have been read between the mark() and reset(). See also Reader. public abstract class InputStream extends Object { // Default Constructor: public InputStream() // Public Instance Methods public int available() throws IOException; public void close() throws IOException; public synchronized void mark(int readlimit); public boolean markSupported(); public abstract int read() throws IOException; public int read(byte[] b) throws IOException; public int read(byte[] b, int off, int len) throws IOException; public synchronized void reset() throws IOException; public long skip(long n) throws IOException; }
Extended By: ByteArrayInputStream, FileInputStream, FilterInputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream
http://localhost/java/javaref/javanut/ch24_28.htm (1 of 2) [20/12/2001 10:59:38]
[Chapter 24] 24.28 java.io.InputStream (JDK 1.0)
Passed To: BufferedInputStream(), CheckedInputStream(), DataInputStream(), FilterInputStream(), GZIPInputStream(), InflaterInputStream(), InputStreamReader(), LineNumberInputStream(), ObjectInputStream(), Properties.load(), PropertyResourceBundle(), PushbackInputStream(), Runtime.getLocalizedInputStream(), SequenceInputStream(), StreamTokenizer(), System.setIn(), URLConnection.guessContentTypeFromStream(), ZipInputStream()
Returned By: Class.getResourceAsStream(), ClassLoader.getResourceAsStream(), ClassLoader.getSystemResourceAsStream(), Process.getErrorStream(), Process.getInputStream(), Runtime.getLocalizedInputStream(), Socket.getInputStream(), SocketImpl.getInputStream(), URL.openStream(), URLConnection.getInputStream(), ZipFile.getInputStream()
Type Of: FilterInputStream.in, System.in
java.io.FilterWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_28.htm (2 of 2) [20/12/2001 10:59:38]
java.io.InputStreamReader (JDK 1.1)
[Chapter 23] 23.23 java.beans.Visibility (JDK 1.1)
Chapter 23 The java.beans Package
23.23 java.beans.Visibility (JDK 1.1) This interface is intended to be implemented by advanced beans that may run either with or without a GUI (graphical user interface) present. The methods it defines allow a bean to specify whether it requires a GUI and allows the environment to notify the bean whether a GUI is available. If a bean absolutely requires a GUI, it should return true from needsGui(). If a bean is running without a GUI, it should return true from avoidingGui(). If no GUI is available, the bean may be notified through a call to dontUseGui(), and if a GUI is available, the bean may be notified through a call to okToUseGui(). public abstract interface Visibility { // Public Instance Methods public abstract boolean avoidingGui(); public abstract void dontUseGui(); public abstract boolean needsGui(); public abstract void okToUseGui(); }
java.beans.VetoableChangeSupport (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_23.htm [20/12/2001 10:59:38]
The java.io Package
[Chapter 4] 4.3 The New AWT Event Model
Chapter 4 What's New in Java 1.1
4.3 The New AWT Event Model The Java 1.1 change that will probably affect Java programmers the most is the new event processing model adopted for the AWT windowing and graphical user interface (GUI) toolkit. If you created applets or GUIs with Java 1.0, you know that it was necessary to subclass GUI components in order to handle events. This model worked okay for simple programs, but proved increasingly awkward as programs became more complex. Furthermore, with the development of the JavaBeans API, the AWT package needed an event model that would allow AWT GUI components to serve as beans. For these reasons, Java 1.1 defines a new model for dispatching and handling events. As explained in Chapter 7, Events, the new event handling model is essentially a "callback" model. When you create a GUI component, you tell it what method or methods it should invoke when a particular event occurs on it (e.g., when the user clicks on a button or selects an item from a list). This model is very easy to use in C and C++ because those languages allow you to manipulate method pointers--to specify a callback, all you need to do is pass a pointer to the appropriate function. In Java, however, methods are not data and cannot be manipulated in this way. Only objects can be passed like this in Java, so to define a Java callback, you must define a class that implements some particular interface. Then, you can pass an instance of that class to a GUI component as a way of specifying the callback. When the desired event occurs, the GUI component invokes the appropriate method of the object you have specified. As you might imagine, this new event handling model can lead to the creation of many small helper classes. (Sometimes these helper classes are known as "adaptor classes" because they serve as the interface between the body of an application and the GUI for that application. They are the "adaptors" that allow the GUI to be "plugged in" to the application.) This proliferation of small classes could become quite a burden, were it not for the introduction of inner classes, which, as noted above, allows this kind of special-purpose class to be nested and defined exactly where it is needed within your program. Despite the major AWT event-handling changes, Java 1.1 does retain backwards compatibility with the event-handling model of Java 1.0. It is an all-or-nothing type of backwards compatibility, however--the two models are so different from each other that it is not really possible to mix them within the same application.
http://localhost/java/javaref/javanut/ch04_03.htm (1 of 2) [20/12/2001 10:59:39]
[Chapter 4] 4.3 The New AWT Event Model
Inner Classes
http://localhost/java/javaref/javanut/ch04_03.htm (2 of 2) [20/12/2001 10:59:39]
Deprecated Features
[Chapter 7] 7.3 The Java 1.1 Event Model
Chapter 7 Events
7.3 The Java 1.1 Event Model The Java 1.1 event model is used by both the AWT and by Java Beans. In this model, different classes of events are represented by different Java classes. Every event is a subclass of java.util.EventObject. AWT events, which is what we are concerned with here, are subclasses of java.awt.AWTEvent. For convenience, the various types of AWT events, such as MouseEvent and ActionEvent, are placed in the new java.awt.event package. Every event has a source object, which can be obtained with getSource(), and every AWT event has a type value, which can be obtained with getID(). This value is used to distinguish the various types of events that are represented by the same event class. For example, the FocusEvent has two possible types: FocusEvent.FOCUS_GAINED and FocusEvent.FOCUS_LOST. Event subclasses contain whatever data values are pertinent to the particular event type. For example, MouseEvent has getX(), getY(), and getClickCount() methods; it also inherits the getModifiers() and getWhen() methods, among others. The 1.1 event handling model is based on the concept of an "event listener." An object interested in receiving events is an event listener. An object that generates events (an event source) maintains a list of listeners that are interested in being notified when events occur, and provides methods that allow listeners to add themselves and remove themselves from this list of interested objects. When the event source object generates an event (or when a user input event occurs on the event source object), the event source notifies all the listener objects that the event has occurred. An event source notifies an event listener object by invoking a method on it and passing it an event object (an instance of a subclass of EventObject). In order for a source to invoke a method on a listener, all listeners must implement the required method. This is ensured by requiring that all event listeners for a particular type of event implement a corresponding interface. For example, event listener objects for ActionEvent events must implement the ActionListener interface. The java.awt.event package defines an event listener interface for each of the event types it defines. (Actually, for MouseEvent events, it defines two listener interfaces: MouseListener and MouseMotionListener.) All event listener interfaces themselves extend java.util.EventListener. This interface does not define any methods, but instead acts as a marker interface, clearly identifying all event listeners as such. An event listener interface may define more than one method. For example, an event class like MouseEvent represents several different types of mouse events, such as a button press event and a http://localhost/java/javaref/javanut/ch07_03.htm (1 of 4) [20/12/2001 10:59:39]
[Chapter 7] 7.3 The Java 1.1 Event Model
button release event, and these different event types cause different methods in the corresponding event listener to be invoked. By convention, the methods of an event listener are passed a single argument, which is an event object of the type that corresponds to the listener. This event object should contain all the information a program needs to respond to the event. Table 7.6 lists the event types defined in java.awt.event, the corresponding listener (or listeners), and the methods defined by each listener interface. Table 7.6: Java 1.1 Event Types, Listeners, and Listener Methods Event Class
Listener Interface
Listener Methods
ActionEvent ActionListener actionPerformed() AdjustmentEvent AdjustmentListener adjustmentValueChanged() ComponentEvent ComponentListener componentHidden() componentMoved() componentResized() componentShown() ContainerEvent ContainerListener componentAdded() componentRemoved() FocusEvent FocusListener focusGained() focusLost() ItemEvent ItemListener itemStateChanged() KeyEvent KeyListener keyPressed() keyReleased() keyTyped() MouseEvent MouseListener mouseClicked() mouseEntered() mouseExited() mousePressed() mouseReleased() _ _
TextEvent WindowEvent
MouseMotionListener mouseDragged() mouseMoved() TextListener textValueChanged() WindowListener windowActivated() windowClosed() windowClosing() windowDeactivated() windowDeiconified()
http://localhost/java/javaref/javanut/ch07_03.htm (2 of 4) [20/12/2001 10:59:39]
[Chapter 7] 7.3 The Java 1.1 Event Model
windowIconified() windowOpened() For each of the event listener interfaces that contains more than one method, java.awt.event defines a simple "adapter" class that provides an empty body for each of the methods in the interface. When you are only interested in one or two of the defined methods, it is sometimes easier to subclass the adapter class than it is to implement the interface. If you subclass the adapter, you only have to override the methods of interest, but if you implement the interface directly you have to define all of the methods, which means you must provide empty bodies for all the methods that are not of interest. These pre-defined no-op adapter classes bear the same name as the interfaces they implement, with "Listener" changed to "Adapter": MouseAdapter, WindowAdapter, etc. Once you have implemented a listener interface, or subclassed a adapter class, you must instantiate your new class to define an individual event listener object. You then register that listener with the appropriate event source. In AWT programs, an event source is always some sort of AWT component. Event listener registration methods follow a standard naming convention: if an event source generates events of type X, it has a method named addXListener() to add an event listener, and a method removeXListener() to remove a listener. One of the nice features of the 1.1 event model is that it is easy to determine the types of events a component can generate--just look for the event listener registration methods. For example, by inspecting the API of the Button object, you can determine that it generates ActionEvent events. Table 7.7 lists AWT components and the events they generate. Table 7.7: AWT Components and the Java 1.1 Events They Generate Component Button Checkbox CheckboxMenuItem Choice Component
Container List MenuItem Scrollbar TextComponent
Events Generated ActionEvent ItemEvent ItemEvent ItemEvent ComponentEvent FocusEvent KeyEvent
Meaning User clicked on the button User selected or deselected an item User selected or deselected an item User selected or deselected an item Component moved, resized, hidden, or shown Component gained or lost focus User pressed or released a key User pressed or released mouse button, mouse entered or exited component, or user moved or dragged mouse. Note: MouseEvent MouseEvent has two corresponding listeners, MouseListener and MouseMotionListener. ContainerEvent Component added to or removed from container ActionEvent User double-clicked on list item ItemEvent User selected or deselected an item ActionEvent User selected a menu item AdjustmentEvent User moved the scrollbar TextEvent User changed text
http://localhost/java/javaref/javanut/ch07_03.htm (3 of 4) [20/12/2001 10:59:39]
[Chapter 7] 7.3 The Java 1.1 Event Model
TextField
ActionEvent
Window
WindowEvent
User finished editing text Window opened, closed, iconified, deiconified, or close requested
Scribbling in Java 1.0
http://localhost/java/javaref/javanut/ch07_03.htm (4 of 4) [20/12/2001 10:59:39]
Scribbling in Java 1.1
[Chapter 7] 7.6 Inside the Java 1.1 Event Model
Chapter 7 Events
7.6 Inside the Java 1.1 Event Model The listener-based event model we've seen in the sections above is ideal for creating a GUI out of pre-defined AWT components or out of Java Beans. It becomes a little cumbersome, however, when developing custom AWT components. AWT components (but not beans) provide a lower-level interface to this event model that is sometimes more convenient to use. When an AWTEvent is delivered to a component, there is some default processing that goes on before the event is dispatched to the appropriate event listeners. When you define a custom component (by subclassing), you have the opportunity to override methods and intercept the event before it is sent to listener objects. When an AWTEvent is delivered to a component, it is passed to the processEvent() method. By default, processEvent() simply checks the class of the event object and dispatches the event to a class-specific method. For example, if the event object is an instance of FocusEvent, it dispatches it to a method named processFocusEvent(). Or, if the event is of type ActionEvent, it is dispatched to processActionEvent(). In other words, any event type XEvent is dispatched to a corresponding processXEvent() method. The exception is for MouseEvent events, which are dispatched either to processMouseEvent() or processMouseMotionEvent(), depending on the type of the mouse event that occurred. For any given component, it is the individual processXEvent() methods that are responsible for invoking the appropriate methods of all registered event listener objects. The processMouseEvent() method, for example, invokes the appropriate method for each registered MouseListener object. There is a one-to-one mapping between these methods and the event listener interfaces defined in java.awt.event. Each processXEvent() method corresponds to an XListener interface. As you can see, there is a clear analogy between the Java 1.0 event model and this Java 1.1 low-level event model. processEvent() is analogous to the Java 1.0 handleEvent() method, and methods like processKeyEvent() are analogous to the Java 1.0 keyDown() and keyUp() methods. As with the Java 1.0 model, there are two levels at which you can intercept events: you can override processEvent() itself or you can rely on the default version of processEvent() to dispatch the events based on their class and instead override the individual event methods, such as processFocusEvent() and processActionEvent(). There is one additional requirement to make this low-level Java 1.1 event model work. In order to receive events of a particular type for a component, you must tell the component that you are interested in receiving that type of event. If you do not do this, for efficiency, the component does not bother to deliver that type of event. When using event listeners, the act of registering a listener is enough to notify the component that you are interested in receiving events of that type. But when you use the low-level model, you must register your interest explicitly. You do this by calling the enableEvents() method of the component and passing a bit mask that specifies each of the event types you are interested in. The bit mask is formed by ORing together various EVENT_MASK constants defined by the AWTEvent class.
http://localhost/java/javaref/javanut/ch07_06.htm (1 of 3) [20/12/2001 10:59:40]
[Chapter 7] 7.6 Inside the Java 1.1 Event Model
Scribbling with Low-Level Event Handling Example 7.4 is another variation on the Scribble applet. This one uses the Java 1.1 low-level event-handling model. It overrides the event-specific methods processMouseEvent(), processMouseMotionEvent(), and processKeyEvent(). Note how it calls enableEvents() in its init() method to register interest in events of that type. Furthermore, it calls requestFocus() to ask that it be given the keyboard focus, so that it can receive key events. Notice also that it passes events it is not interested in to the superclass event-processing method. In this case, the superclass is not going to use those events, but this is still a good practice. Example 7.4: Scribble: Using the Low-Level Event Model import java.applet.*; import java.awt.*; import java.awt.event.*; public class Scribble4 extends Applet { private int lastx, lasty; /** Tell the system we're interested in mouse events, mouse motion events, * and keyboard events. This is required or events won't be sent. */ public void init() { this.enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.KEY_EVENT_MASK); this.requestFocus(); // Ask for keyboard focus so we get key events. } /** Invoked when a mouse event of some type occurs */ public void processMouseEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_PRESSED) { // Check the event type. lastx = e.getX(); lasty = e.getY(); } else super.processMouseEvent(e); // Pass unhandled events to superclass. } /** Invoked when a mouse motion event occurs */ public void processMouseMotionEvent(MouseEvent e) { if (e.getID() == MouseEvent.MOUSE_DRAGGED) { // check type int x = e.getX(), y = e.getY(); Graphics g = this.getGraphics(); g.drawLine(lastx, lasty, x, y); lastx = x; lasty = y; } else super.processMouseMotionEvent(e); } /** Called on key events: clear the screen when 'c' is typed. */ public void processKeyEvent(KeyEvent e) { if ((e.getID() == KeyEvent.KEY_TYPED) && (e.getKeyChar() == 'c')) { Graphics g = this.getGraphics(); g.setColor(this.getBackground()); g.fillRect(0, 0, this.getSize().width, this.getSize().height); } else super.processKeyEvent(e); // Pass unhandled events to our superclass.
http://localhost/java/javaref/javanut/ch07_06.htm (2 of 3) [20/12/2001 10:59:40]
[Chapter 7] 7.6 Inside the Java 1.1 Event Model
} } Another way to implement this example would be to override processEvent() directly instead of overriding the various methods that it invokes. If we did this, we'd end up with a large switch statement that separated events by type. When overriding processEvent(), it is particularly important to remember to pass unhandled events to super.processEvent() so that they can be dispatched correctly.
Scribbling with Inner Classes
http://localhost/java/javaref/javanut/ch07_06.htm (3 of 3) [20/12/2001 10:59:40]
New AWT Features
[Chapter 18] 18.2 java.awt.AWTEvent (JDK 1.1)
Chapter 18 The java.awt Package
18.2 java.awt.AWTEvent (JDK 1.1) This abstract class serves as the root event type for all AWT events in Java 1.1 and supersedes the Event class which was used in Java 1.0. Each AWTEvent has a source object, as all EventObject objects do. You can query the source of an event with the inherited getSource() method. The AWTEvent class adds an event type, or "id," for every AWT event. Use getID() to query the type of the event. Subclasses of AWTEvent define various constants for this type field. The various _MASK constants defined by this class allow Component.enableEvents() to be called by applets and custom components that want to receive various event types without having to register an EventListener object to receive them. public abstract class AWTEvent extends EventObject { // Public Constructors public AWTEvent(Event event); public AWTEvent(Object source, int id); // Constants public static final long ACTION_EVENT_MASK; public static final long ADJUSTMENT_EVENT_MASK; public static final long COMPONENT_EVENT_MASK; public static final long CONTAINER_EVENT_MASK; public static final long FOCUS_EVENT_MASK; public static final long ITEM_EVENT_MASK; public static final long KEY_EVENT_MASK; public static final long MOUSE_EVENT_MASK; public static final long MOUSE_MOTION_EVENT_MASK; public static final int RESERVED_ID_MAX; public static final long TEXT_EVENT_MASK; public static final long WINDOW_EVENT_MASK; // Protected Instance Variables protected boolean consumed; protected int id; // Public Instance Methods http://localhost/java/javaref/javanut/ch18_02.htm (1 of 2) [20/12/2001 10:59:40]
[Chapter 18] 18.2 java.awt.AWTEvent (JDK 1.1)
public int getID(); public String paramString(); public String toString(); // Overrides EventObject // Protected Instance Methods protected void consume(); protected boolean isConsumed(); }
Hierarchy: Object->EventObject(Serializable)->AWTEvent
Extended By: ActionEvent, AdjustmentEvent, ComponentEvent, ItemEvent, TextEvent
Passed To: Button.processEvent(), Checkbox.processEvent(), CheckboxMenuItem.processEvent(), Choice.processEvent(), Component.dispatchEvent(), Component.processEvent(), ComponentPeer.handleEvent(), Container.processEvent(), EventQueue.postEvent(), List.processEvent(), MenuComponent.dispatchEvent(), MenuComponent.processEvent(), MenuItem.processEvent(), Scrollbar.processEvent(), TextComponent.processEvent(), TextField.processEvent(), Window.processEvent()
Returned By: EventQueue.getNextEvent(), EventQueue.peekEvent()
java.awt.AWTError (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_02.htm (2 of 2) [20/12/2001 10:59:40]
java.awt.AWTEventMulticaster (JDK 1.1)
[Chapter 18] 18.4 java.awt.AWTException (JDK 1.0)
Chapter 18 The java.awt Package
18.4 java.awt.AWTException (JDK 1.0) Signals that an exception has occurred in the java.awt package. public class AWTException extends Exception { // Public Constructor public AWTException(String msg); }
Hierarchy: Object->Throwable(Serializable)->Exception->AWTException
java.awt.AWTEventMulticaster (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_04.htm [20/12/2001 10:59:40]
java.awt.Adjustable (JDK 1.1)
[Chapter 27] The java.math Package
Chapter 27
27. The java.math Package Contents: java.math.BigDecimal (JDK 1.1) java.math.BigInteger (JDK 1.1) The java.math package, new in Java 1.1, contains classes for arbitrary-precision integer and floating-point arithmetic. Arbitrary-length integers are required for cryptography, and arbitrary-precision floating-point values are useful for financial applications that need to be careful about rounding errors. The class hierarchy of this extremely small package is shown in Figure 27.1. Figure 27.1: The java.math package
27.1 java.math.BigDecimal (JDK 1.1) This subclass of java.lang.Number represents a floating-point number of arbitrary size and precision. Its methods duplicate the functionality of the standard Java arithmetic operators. The compareTo() method compares the value of two BigDecimal objects and returns -1, 0, or 1 to indicate the result of the comparison. BigDecimal objects are represented as an integer of arbitrary size and an integer scale that specifies the number of decimal places in the value. When working with BigDecimal values, you can explicitly specify the amount of precision (the number of decimal places) you are interested in. Also, whenever a BigDecimal method may discard precision (in a division operation, for example), you are required to specify what sort of rounding should be performed on the digit to the left of the discarded digit or digits. The eight constants defined by this class specify the available rounding modes. Because the BigDecimal class provides arbitrary precision and gives you explicit control over rounding and the number of decimal places you are interested in, it can be useful when dealing with quantities that represent money, or in other circumstances where the tolerance for rounding errors is low. public class BigDecimal extends Number { // Public Constructors
http://localhost/java/javaref/javanut/ch27_01.htm (1 of 3) [20/12/2001 10:59:40]
[Chapter 27] The java.math Package
public BigDecimal(String val) throws NumberFormatException; public BigDecimal(double val) throws NumberFormatException; public BigDecimal(BigInteger val); public BigDecimal(BigInteger val, int scale) throws NumberFormatException; // Constants public static final int ROUND_CEILING; public static final int ROUND_DOWN; public static final int ROUND_FLOOR; public static final int ROUND_HALF_DOWN; public static final int ROUND_HALF_EVEN; public static final int ROUND_HALF_UP; public static final int ROUND_UNNECESSARY; public static final int ROUND_UP; // Class Methods public static BigDecimal valueOf(long val, int scale) throws NumberFormatException; public static BigDecimal valueOf(long val); // Public Instance Methods public BigDecimal abs(); public BigDecimal add(BigDecimal val); public int compareTo(BigDecimal val); public BigDecimal divide(BigDecimal val, int scale, int roundingMode) throws ArithmeticException, IllegalArgumentException; public BigDecimal divide(BigDecimal val, int roundingMode) throws ArithmeticException, IllegalArgumentException; public double doubleValue(); // Defines Number public boolean equals(Object x); // Overrides Object public float floatValue(); // Defines Number public int hashCode(); // Overrides Object public int intValue(); // Defines Number public long longValue(); // Defines Number public BigDecimal max(BigDecimal val); public BigDecimal min(BigDecimal val); public BigDecimal movePointLeft(int n); public BigDecimal movePointRight(int n); public BigDecimal multiply(BigDecimal val); public BigDecimal negate(); public int scale(); public BigDecimal setScale(int scale, int roundingMode) throws ArithmeticException, IllegalArgumentException; public BigDecimal setScale(int scale) throws ArithmeticException, IllegalArgumentException; public int signum(); public BigDecimal subtract(BigDecimal val); public BigInteger toBigInteger(); public String toString(); // Overrides Object }
http://localhost/java/javaref/javanut/ch27_01.htm (2 of 3) [20/12/2001 10:59:40]
[Chapter 27] The java.math Package
Hierarchy: Object->Number(Serializable)->BigDecimal
java.lang.reflect.Modifier (JDK 1.1)
java.math.BigInteger (JDK 1.1)
http://localhost/java/javaref/javanut/ch27_01.htm (3 of 3) [20/12/2001 10:59:40]
[Chapter 27] 27.2 java.math.BigInteger (JDK 1.1)
Chapter 27 The java.math Package
27.2 java.math.BigInteger (JDK 1.1) This subclass of java.lang.Number represents integers that can be arbitrarily large--i.e., integers that are not limited to the 64 bits available with the long data type. BigInteger defines methods that duplicate the functionality of the standard Java arithmetic and bit-manipulation operators. The compareTo() method compares two BigInteger objects, and returns -1, 0, or 1 to indicate the result of the comparison. The gcd(), modPow(), modInverse(), and isProbablePrime() methods perform advanced operations and are used primarily in cryptography and related algorithms. public class BigInteger extends Number { // Public Constructors public BigInteger(byte[] val) throws NumberFormatException; public BigInteger(int signum, byte[] magnitude) throws NumberFormatException; public BigInteger(String val, int radix) throws NumberFormatException; public BigInteger(String val) throws NumberFormatException; public BigInteger(int numBits, Random rndSrc) throws IllegalArgumentException; public BigInteger(int bitLength, int certainty, Random rnd); // Class Methods public static BigInteger valueOf(long val); // Public Instance Methods public BigInteger abs(); public BigInteger add(BigInteger val) throws ArithmeticException; public BigInteger and(BigInteger val); public BigInteger andNot(BigInteger val); public int bitCount(); public int bitLength(); public BigInteger clearBit(int n) throws ArithmeticException; public int compareTo(BigInteger val); public BigInteger divide(BigInteger val) throws ArithmeticException; public BigInteger[] divideAndRemainder(BigInteger val) throws ArithmeticException; public double doubleValue(); // Defines Number public boolean equals(Object x); // Overrides Object public BigInteger flipBit(int n) throws ArithmeticException; public float floatValue(); // Defines Number public BigInteger gcd(BigInteger val); public int getLowestSetBit(); public int hashCode(); // Overrides Object public int intValue(); // Defines Number public boolean isProbablePrime(int certainty); http://localhost/java/javaref/javanut/ch27_02.htm (1 of 2) [20/12/2001 10:59:41]
[Chapter 27] 27.2 java.math.BigInteger (JDK 1.1)
public public public public public public public public public public public public public public public public public public public public public public
long longValue(); // Defines Number BigInteger max(BigInteger val); BigInteger min(BigInteger val); BigInteger mod(BigInteger m); BigInteger modInverse(BigInteger m) throws ArithmeticException; BigInteger modPow(BigInteger exponent, BigInteger m); BigInteger multiply(BigInteger val); BigInteger negate(); BigInteger not(); BigInteger or(BigInteger val); BigInteger pow(int exponent) throws ArithmeticException; BigInteger remainder(BigInteger val) throws ArithmeticException; BigInteger setBit(int n) throws ArithmeticException; BigInteger shiftLeft(int n); BigInteger shiftRight(int n); int signum(); BigInteger subtract(BigInteger val); boolean testBit(int n) throws ArithmeticException; byte[] toByteArray(); String toString(int radix); String toString(); // Overrides Object BigInteger xor(BigInteger val);
}
Hierarchy: Object->Number(Serializable)->BigInteger
Passed To: BigDecimal()
Returned By: BigDecimal.toBigInteger()
java.math.BigDecimal (JDK 1.1)
http://localhost/java/javaref/javanut/ch27_02.htm (2 of 2) [20/12/2001 10:59:41]
The java.net Package
[Chapter 28] The java.net Package
Chapter 28
28. The java.net Package Contents: java.net.ConnectException (JDK 1.1) java.net.ContentHandler (JDK 1.0) java.net.ContentHandlerFactory (JDK 1.0) java.net.DatagramPacket (JDK 1.0) java.net.DatagramSocket (JDK 1.0) java.net.DatagramSocketImpl (JDK 1.1) java.net.FileNameMap (JDK 1.1) java.net.HttpURLConnection (JDK 1.1) java.net.InetAddress (JDK 1.0) java.net.MalformedURLException (JDK 1.0) java.net.MulticastSocket (JDK 1.1) java.net.NoRouteToHostException (JDK 1.1) java.net.ProtocolException (JDK 1.0) java.net.ServerSocket (JDK 1.0) java.net.Socket (JDK 1.0) java.net.SocketException (JDK 1.0) java.net.SocketImpl (JDK 1.0) java.net.SocketImplFactory (JDK 1.0) java.net.UnknownHostException (JDK 1.0) java.net.UnknownServiceException (JDK 1.0) java.net.URL (JDK 1.0) java.net.URLConnection (JDK 1.0) java.net.URLEncoder (JDK 1.0) java.net.URLStreamHandler (JDK 1.0) java.net.URLStreamHandlerFactory (JDK 1.0) The java.net package provides a powerful and flexible infrastructure for networking. Figure 28.1 shows the class hierarchy for this package. Many of the classes in this package are part of the networking
http://localhost/java/javaref/javanut/ch28_01.htm (1 of 3) [20/12/2001 10:59:41]
[Chapter 28] The java.net Package
infrastructure and are not used by normal applications; these complicated classes can make the package a difficult one to understand. In this overview we describe only the classes that an application might normally use. Figure 28.1: The java.net package
The URL class represents an Internet Uniform Resource Locator. It provides a very simple interface to networking--the object referred to by the URL can be downloaded with a single call, or streams may be opened to read from or write to the object. At a slightly more complex level, the URLConnection object may be obtained from a given URL http://localhost/java/javaref/javanut/ch28_01.htm (2 of 3) [20/12/2001 10:59:41]
[Chapter 28] The java.net Package
object. The URLConnection class provides additional methods that allow you to work with URLs in more sophisticated ways. If you want to do more than simply download an object referenced by a URL, you can do your own networking with the Socket class. This class allows you to connect to a specified port on a specified Internet host and read and write data using the InputStream and OutputStream classes of the java.io package. If you want to implement a server to accept connections from clients, you can use the related ServerSocket class. Both Socket and ServerSocket use the InetAddress address class, which represents an Internet address. The java.net package allows you to do low-level networking with DatagramPacket objects which may be sent and received over the network through a DatagramSocket object. In Java 1.1, the package has been extended to include a MulticastSocket class that supports multicast networking.
28.1 java.net.BindException (JDK 1.1) This exception signals that a socket could not be bound to a local address and port. This often means that the port is already in use. public class BindException extends SocketException { // Public Constructors public BindException(String msg); public BindException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->SocketException->BindException
java.math.BigInteger (JDK 1.1)
http://localhost/java/javaref/javanut/ch28_01.htm (3 of 3) [20/12/2001 10:59:41]
java.net.ConnectException (JDK 1.1)
[Chapter 2] 2.14 Miscellaneous Differences
Chapter 2 How Java Differs from C
2.14 Miscellaneous Differences A number of miscellaneous differences between Java and C are described in the sections that follow. Miscellaneous differences that were mentioned elsewhere, such as the lack of the goto statement and the sizeof operator, are not repeated here.
Local Variable Declarations A feature that Java has borrowed from C++ is the ability to declare and initialize local variables anywhere in a method body or other block of code. Declarations and their initializers no longer have to be the first statements in any block--you can declare them where it is convenient and fits well with the structure of your code. Don't let this freedom make you sloppy, however! For someone reading your program, it is nice to have variable declarations grouped together in one place. As a rule of thumb, put your declarations at the top of the block, unless you have some good organizational reason for putting them elsewhere.
Forward References For compiler efficiency, C requires that variables and functions must be defined, or at least declared, before they can be used or called. That is, forward references are not allowed in C. Java does not make this restriction, and by lifting it, it also does away with the whole concept of a variable or function declaration that is separate from the definition. Java allows very flexible forward references. A method may refer to a variable or another method of its class, regardless of where in the current class the variable or method is defined. Similarly, it may refer to any class, regardless of where in the current file (or outside of the file) that class is defined. The only place that forward references are not allowed is in variable initialization. A variable initializer (for local variables, class variables, or instance variables) may not refer to other variables that have not yet been declared and initialized.
http://localhost/java/javaref/javanut/ch02_14.htm (1 of 4) [20/12/2001 10:59:42]
[Chapter 2] 2.14 Miscellaneous Differences
Method Overloading A technique that Java borrows from C++ is called method overloading. Overloaded methods are methods that have the same name, but have different signatures. In other words, they take different types of arguments, a different number of arguments, or the same type of arguments in different positions in the argument list. You cannot overload a method by changing only its return type. Two methods with the same name may have different return types, but only if the method arguments also differ. Similarly, two overloaded methods may throw different exceptions, but only if their arguments differ as well. Method overloading is commonly used in Java to define a number of related functions with the same name, but different arguments. Overloaded methods usually perform the same basic operation, but allow the programmer to specify arguments in different ways depending on what is convenient in a given situation. Method overloading is discussed in more detail in the next chapter.
The void Keyword The void keyword is used in Java, as in C, to indicate that a function returns no value. (As we will see in the next section, constructor methods are an exception to this rule.) Java differs from C (and is similar to C++) in that methods that take no arguments are declared with empty parentheses, not with the void keyword. Java does not have any void * type, nor does it use a (void) cast in order to ignore the result returned by a call to a non-void method.
Modifiers Java defines a number of modifier keywords that may be applied to variable and/or method declarations to provide additional information or place restrictions on the variable or method: final The final keyword is a modifier that may be applied to classes, methods, and variables. It has a similar, but not identical, meaning in each case. A final class may never be subclassed. A final method may never be overridden. A final variable may never have its value set. In Java 1.1, this modifier may also be applied to local variables and method parameters. This modifier is discussed in more detail in the next chapter. native native is a modifier that may be applied to method declarations. It indicates that the method is implemented elsewhere in C, or in some other platform-dependent fashion. A native method should have a semicolon in place of its body. synchronized We saw the synchronized keyword in a previous section where it was a statement that marked a critical section of code. The same keyword can also be used as a modifier for class or instance methods. It indicates that the method modifies the internal state of the class or the internal state of an instance of the class in a way that is not thread-safe. Before running a synchronized class method, Java obtains a lock on the class, to ensure that no other threads can modif the class
http://localhost/java/javaref/javanut/ch02_14.htm (2 of 4) [20/12/2001 10:59:42]
[Chapter 2] 2.14 Miscellaneous Differences
concurrently. Before running a synchronized instance method, Java obtains a lock on the instance that invoked the method, ensuring that no other thread can modify the object at the same time. transient The transient keyword is a modifier that may be applied to instance fields in a class. This modifier is legal but unused in Java 1.0. In Java 1.1, it indicates a field that is not part of an object's persistent state and thus does not need to be serialized with the object. volatile The volatile keyword is a modifier that may be applied to fields. It specifies that the field is used by synchronized threads and that the compiler should not attempt to perform optimizations with it. For example, it should read the variable's value from memory every time and not attempt to save a copy of it on the stack.
No Structures or Unions Java does not support C struct or union types. Note, however, that a class is essentially the same thing as a struct, but with more features. And you can simulate the important features of a union by subclassing.
No Enumerated Types Java does not support the C enum keyword for defining types that consist of one of a specified number of named values. This is somewhat surprising for a strongly-typed language like Java. Enumerated types can be partially simulated with the use of static final constant values.
No Method Types C allows you to store the address of a function in a variable and to pass function addresses to other functions. You cannot do this in Java: methods are not data, and cannot be manipulated by Java programs. Note, however, that objects are data, and that objects can define methods. [9] So, when you need to pass a method to another method, you declare a class that defines the desired method and pass an instance of that class. See, for example, the FilenameFilter interface in the java.io package. [9] An interesting way to think about objects in Java is as a kind of method that defines multiple entry points.
No Bitfields Java does not support the C ability to define variables that occupy particular bits within struct and union types. This feature of C is usually only used to interface directly to hardware devices, which is never necessary with Java's platform-independent programming model.
http://localhost/java/javaref/javanut/ch02_14.htm (3 of 4) [20/12/2001 10:59:42]
[Chapter 2] 2.14 Miscellaneous Differences
No typedef Java does not support the C typedef keyword to define aliases for type names. Java has a much simpler type naming scheme than C does, however, and so there is no need for something like typedef.
No Variable-Length Argument Lists Java does not allow you to define methods that take a variable number of arguments, as C does. This is because Java is a strongly typed language and there is no way to do appropriate type checking for a method with variable arguments. Method overloading allows you to simulate C "varargs" functions for simple cases, but there is no general replacement for this C feature.
Exceptions and Exception Handling
http://localhost/java/javaref/javanut/ch02_14.htm (4 of 4) [20/12/2001 10:59:42]
Classes and Objects in Java
[Chapter 30] The java.util Package
Chapter 30
30. The java.util Package Contents: java.util.Calendar (JDK 1.1) java.util.Date (JDK 1.0) java.util.Dictionary (JDK 1.0) java.util.EmptyStackException (JDK 1.0) java.util.Enumeration (JDK 1.0) java.util.EventListener (JDK 1.1) java.util.EventObject (JDK 1.1) java.util.GregorianCalendar (JDK 1.1) java.util.Hashtable (JDK 1.0) java.util.ListResourceBundle (JDK 1.1) java.util.Locale (JDK 1.1) java.util.MissingResourceException (JDK 1.1) java.util.NoSuchElementException (JDK 1.0) java.util.Observable (JDK 1.0) java.util.Observer (JDK 1.0) java.util.Properties (JDK 1.0) java.util.PropertyResourceBundle (JDK 1.1) java.util.Random (JDK 1.0) java.util.ResourceBundle (JDK 1.1) java.util.SimpleTimeZone (JDK 1.1) java.util.Stack (JDK 1.0) java.util.StringTokenizer (JDK 1.0) java.util.TimeZone (JDK 1.1) java.util.TooManyListenersException (JDK 1.1) java.util.Vector (JDK 1.0) The java.util package defines a number of useful classes. This package should not be considered a "utility" package separate from the rest of the language; in fact, Java depends directly on several of the classes in this package. Figure 30.1 shows the class hierarchy of this package. Figure 30.1: The java.util package
http://localhost/java/javaref/javanut/ch30_01.htm (1 of 3) [20/12/2001 10:59:42]
[Chapter 30] The java.util Package
The Hashtable class is one of the most useful in the package--it implements a hashtable or associative array. It allows arbitrary objects to be stored and retrieved by arbitrary keys. The Properties subclass of Hashtable is used to store the Java system properties list. Vector is another extremely useful class. It implements an array of objects that grows as needed when objects are added. The Enumeration interface provides a simple and consistent way to loop through all the elements contained within some kind of object or data structure. The Date class represents a date and time, using a millisecond representation. In Java 1.1, the Calendar class manipulates dates using more familiar units such as months, days, hours, and minutes. The TimeZone class is also used in conjunction with dates. In Java 1.1, ResourceBundle and its subclasses, ListResourceBundle and http://localhost/java/javaref/javanut/ch30_01.htm (2 of 3) [20/12/2001 10:59:42]
[Chapter 30] The java.util Package
PropertyResourceBundle, represent a "bundle" of localized resources that are read in by an internationalized program at runtime. The remaining classes are also useful. BitSet implements an arbitrary-size array of bits. Random generates and returns pseudo-random numbers in a variety of forms. StringTokenizer parses a string into tokens. Stack implements a last-in-first-out stack on which objects may be pushed, and from which they may be popped. And the Observer interface and Observable class provide infrastructure for implementing the object-oriented model-view paradigm in Java.
30.1 java.util.BitSet (JDK 1.0) This class defines an arbitrarily large set of bits. Instance methods allow you to set, clear, and query individual bits in the set, and also to perform bitwise boolean arithmetic on the bits in BitSet objects. This class can be used as an extremely compact array of boolean values, although reading and writing those values is slower than normal array access. public final class BitSet extends Object implements Cloneable, Serializable { // Public Constructors public BitSet(); public BitSet(int nbits); // Public Instance Methods public void and(BitSet set); public void clear(int bit); public Object clone(); // Overrides Object public boolean equals(Object obj); // Overrides Object public boolean get(int bit); public int hashCode(); // Overrides Object public void or(BitSet set); public void set(int bit); public int size(); public String toString(); // Overrides Object public void xor(BitSet set); }
Passed To: BitSet.and(), BitSet.or(), BitSet.xor()
java.text.StringCharacterIterator (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_01.htm (3 of 3) [20/12/2001 10:59:42]
java.util.Calendar (JDK 1.1)
[Chapter 25] 25.5 java.lang.Boolean (JDK 1.0)
Chapter 25 The java.lang Package
25.5 java.lang.Boolean (JDK 1.0) This class provides an immutable object wrapper around the boolean primitive type. Note that the TRUE and FALSE constants are Boolean objects; they are not the same as the true and false boolean values. In Java 1.1, this class defines a Class constant that represents the boolean type. booleanValue() returns the boolean value of a Boolean object. The class method getBoolean() retrieves the boolean value of a named property from the system property list. The class method valueOf() parses a string and returns the Boolean value it represents. public final class Boolean extends Object implements Serializable { // Public Constructors public Boolean(boolean value); public Boolean(String s); // Constants public static final Boolean FALSE; public static final Boolean TRUE; 1.1public static final Class TYPE; // Class Methods public static boolean getBoolean(String name); public static Boolean valueOf(String s); // Public Instance Methods public boolean booleanValue(); public boolean equals(Object obj); // Overrides Object public int hashCode(); // Overrides Object public String toString(); // Overrides Object }
Returned By: Boolean.valueOf()
http://localhost/java/javaref/javanut/ch25_05.htm (1 of 2) [20/12/2001 10:59:42]
[Chapter 25] 25.5 java.lang.Boolean (JDK 1.0)
Type Of: Boolean.FALSE, Boolean.TRUE
java.lang.ArrayStoreException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_05.htm (2 of 2) [20/12/2001 10:59:42]
java.lang.Byte (JDK 1.1)
[Chapter 18] 18.6 java.awt.BorderLayout (JDK 1.0)
Chapter 18 The java.awt Package
18.6 java.awt.BorderLayout (JDK 1.0) This class implements the LayoutManager interface to lay out Component objects in a Container. The BorderLayout arranges components that have been added to their Container (using the Container.add() method) with the names "North," "South," "East," "West," and "Center." These named components are arranged along the edges and in the center of the container. The hgap and vgap arguments to the BorderLayout constructor specify the desired horizontal and vertical spacing between adjacent components. Note that applications should never call the LayoutManager methods of this class directly; the Container for which the BorderLayout is registered does this. public class BorderLayout extends Object implements LayoutManager2, Serializable { // Public Constructors public BorderLayout(); public BorderLayout(int hgap, int vgap); // Constants 1.1 public static final String CENTER; 1.1 public static final String EAST; 1.1 public static final String NORTH; 1.1 public static final String SOUTH; 1.1 public static final String WEST; // Public Instance Methods 1.1 public void addLayoutComponent(Component comp, Object constraints); // From LayoutManager2 # public void addLayoutComponent(String name, Component comp); // From LayoutManager 1.1 public int getHgap(); 1.1 public float getLayoutAlignmentX(Container parent); // From LayoutManager2 1.1 public float getLayoutAlignmentY(Container parent); // From LayoutManager2 1.1 public int getVgap(); 1.1 public void invalidateLayout(Container target); // From LayoutManager2 public void layoutContainer(Container target); // From LayoutManager 1.1 public Dimension maximumLayoutSize(Container target); // From LayoutManager2 public Dimension minimumLayoutSize(Container target); // From LayoutManager public Dimension preferredLayoutSize(Container target); // From LayoutManager public void removeLayoutComponent(Component comp); // From LayoutManager 1.1 public void setHgap(int hgap); 1.1 public void setVgap(int vgap); public String toString(); // Overrides Object }
http://localhost/java/javaref/javanut/ch18_06.htm (1 of 2) [20/12/2001 10:59:42]
[Chapter 18] 18.6 java.awt.BorderLayout (JDK 1.0)
Hierarchy: Object->BorderLayout(LayoutManager2(LayoutManager), Serializable)
java.awt.Adjustable (JDK 1.1)
java.awt.Button (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_06.htm (2 of 2) [20/12/2001 10:59:42]
[Chapter 10] Java Beans
Chapter 10
10. Java Beans Contents: Bean Basics A Simple Bean A More Complex Bean Custom Events Specifying Bean Information Defining a Simple Property Editor Defining a Complex Property Editor Defining a Bean Customizer Naming Patterns and Conventions The JavaBeans API provides a framework for defining reusable, embeddable, modular software components. The JavaBeans Specification includes the following definition of a bean: "a reusable software component that can be manipulated visually in a builder tool." As you can see, this is a rather loose definition; beans can take a variety of forms. At the simplest level, individual AWT components (in Java 1.1) are all beans, while at a much higher level, an embeddable spreadsheet application might also function as a bean. Most beans, however, will probably fall somewhere between these two extremes. One of the goals of the JavaBeans model is interoperability with similar component frameworks. So, for example, a native Windows program can, with an appropriate bridge or wrapper object, use a Java bean as if it were a COM or ActiveX component. The details of this sort of interoperability are beyond the scope of this chapter, however. Beans can be used at three levels, by three different categories of programmers: ● If you are developing GUI editors, application builders, or other "beanbox" tools, you need the JavaBeans API to manipulate beans within these tools. beanbox is the name of the sample bean manipulation program provided by Sun in its Beans Development Kit (BDK). The term is a useful one, and I'll use it to describe any kind of graphical design tool or application builder that manipulates beans. ● If you are writing actual beans, you need the JavaBeans API to write code that can be used in any conforming beanbox. ● If you are writing applications that use beans developed by other programmers, or using a beanbox http://localhost/java/javaref/javanut/ch10_01.htm (1 of 3) [20/12/2001 10:59:43]
[Chapter 10] Java Beans
tool to combine those beans into an application, you do not actually need to be familiar with the JavaBeans API. You only need to be familiar with the documentation for individual beans that you are using. This chapter explains how to use the JavaBeans API at the second level, or in other words, it describes how to write beans. It covers the following topics: ● Basic bean concepts and terminology ● Requirements for the simplest beans ● Packaging beans in JAR files ● Providing additional information about beans with the BeanInfo class ● Defining property editors to allow custom editing of bean properties ● Defining bean customizers to allow customization of an entire bean ● The various naming conventions and requirements imposed by the JavaBeans model
10.1 Bean Basics We begin our discussion of beans with some basic concepts and terminology. Any object that conforms to certain basic rules can be a bean; there is no Bean class that all beans are required to subclass. Many beans are AWT components, but it is also quite possible, and often useful, to write "invisible" beans that do not have an on-screen appearance. (Just because a bean does not have an on-screen appearance in a finished application does not mean that it won't be visually manipulated by a beanbox tool, however.) A bean exports properties, events, and methods. A property is a piece of the bean's internal state that can be programmatically set and queried, usually through a standard pair of get and set accessor methods. A bean may generate events in the same way that an AWT component, such as a Button, generates ActionEvent events. The JavaBeans API uses the same event model as the Java 1.1 AWT does. See Chapter 7, Events, for a full discussion of this model. A bean defines an event if it provides methods for adding and removing event listener objects from a list of interested listeners for that event. Finally, the methods exported by a bean are simply any public methods defined by the bean, excluding those methods used to get and set property values and register and remove event listeners. In addition to the regular sort of properties described above, the JavaBeans API also provides support for "indexed properties," "bound properties," and "constrained properties." An indexed property is any property that has an array value and for which the bean provides methods to get and set individual elements of the array, as well as methods to get and set the entire array. A bound property is one that sends out a notification event when its value changes, while a constrained property is one that sends out a notification event when its value changes and allows the change to be vetoed by listeners. Because Java allows dynamic loading of classes, beanbox programs can load arbitrary beans. The beanbox tool determines the properties, events, and methods a bean supports by using an "introspection" mechanism that is based on the java.lang.reflect reflection mechanism for obtaining information about the members of a class. A bean can also provide an auxiliary BeanInfo class that provides additional information about the bean. The BeanInfo class provides this additional information in the form of a number of FeatureDescriptor objects, each one describing a single feature of the bean.
http://localhost/java/javaref/javanut/ch10_01.htm (2 of 3) [20/12/2001 10:59:43]
[Chapter 10] Java Beans
FeatureDescriptor has a number of subclasses: BeanDescriptor, PropertyDescriptor, IndexedPropertyDescriptor, EventSetDescriptor, MethodDescriptor, and ParameterDescriptor. One of the primary tasks of a beanbox application is to allow the user to customize a bean by setting property values. A beanbox defines "property editors" for commonly used property types, such as numbers, strings, fonts, and colors. If a bean has properties of more complicated types, however, it may need to define a PropertyEditor class that enables the beanbox to let the user set values for that property. In addition, a complex bean may not be satisfied with the property-by-property customization mechanism provided by most beanboxes. Such a bean may want to define a Customizer class, which creates a graphical interface that allows the user to configure a bean in some useful way. A particularly complex bean may even define customizers that serve as "wizards" that guide the user step-by-step through the customization process.
Advanced Serialization
http://localhost/java/javaref/javanut/ch10_01.htm (3 of 3) [20/12/2001 10:59:43]
A Simple Bean
[Chapter 29] The java.text Package
Chapter 29
29. The java.text Package Contents: java.text.CharacterIterator (JDK 1.1) java.text.ChoiceFormat (JDK 1.1) java.text.CollationElementIterator (JDK 1.1) java.text.CollationKey (JDK 1.1) java.text.Collator (JDK 1.1) java.text.DateFormat (JDK 1.1) java.text.DateFormatSymbols (JDK 1.1) java.text.DecimalFormat (JDK 1.1) java.text.DecimalFormatSymbols (JDK 1.1) java.text.FieldPosition (JDK 1.1) java.text.Format (JDK 1.1) java.text.MessageFormat (JDK 1.1) java.text.NumberFormat (JDK 1.1) java.text.ParseException (JDK 1.1) java.text.ParsePosition (JDK 1.1) java.text.RuleBasedCollator (JDK 1.1) java.text.SimpleDateFormat (JDK 1.1) java.text.StringCharacterIterator (JDK 1.1) The java.text package consists of classes and interfaces that are useful for writing internationalized programs that handle local customs, such as date and time formatting and string alphabetization, correctly. This package is new in Java 1.1. Figure 29.1 shows its class hierarchy. The NumberFormat class formats numbers, monetary quantities, and percentages as appropriate for the default or specified locale. DateFormat formats dates and times in a locale-specific way. The concrete DecimalFormat and SimpleDateFormat subclasses of these classes can be used for customized number, date, and time formatting. MessageFormat allows substitution of dynamic values, including formatted numbers and dates, into static message strings. ChoiceFormat formats a number using an enumerated set of string values. Collator compares strings according to the customary sorting order for a locale. BreakIterator scans text to find word, line, and sentence boundaries following locale-specfic rules. Figure 29.1: The java.text package
http://localhost/java/javaref/javanut/ch29_01.htm (1 of 3) [20/12/2001 10:59:43]
[Chapter 29] The java.text Package
29.1 java.text.BreakIterator (JDK 1.1) This class is used to determine character, word, sentence, and line breaks in a block of text in a way that is independent of locale and text-encoding. As an abstract class, BreakIterator cannot be instantiated directly. Instead, you must use one of the class methods getCharacterInstance(), getWordInstance(), getSentenceInstance(), or getLineInstance() to return an instance of a nonabstract subclass of BreakIterator. These various "factory" methods return a BreakIterator object that is configured to locate the requested boundary types, and is localized to work for the optionally specified locale. Once you have obtained an appropriate BreakIterator object, you use setText() to specify the text that it is to locate boundaries in. To locate boundaries in a Java String object, simply specify the string. To locate boundaries in text that uses some other encoding, you must specify a CharacterIterator object for that text so that the BreakIterator object can locate the individual characters of the text. Having set the text to be searched, you can determine the character positions of characters, words, sentences, or line breaks with the first(), last(), next(), previous(), current(), and following() methods, which perform the obvious functions. Note that these methods do not return text itself, but merely the position of the appropriate word, sentence, or line break. public abstract class BreakIterator extends Object implements Cloneable, Serializable { // Protected Constructor protected BreakIterator(); // Constants public static final int DONE; // Class Methods public static synchronized Locale[] getAvailableLocales(); public static BreakIterator getCharacterInstance(); http://localhost/java/javaref/javanut/ch29_01.htm (2 of 3) [20/12/2001 10:59:43]
[Chapter 29] The java.text Package
public static BreakIterator getCharacterInstance(Locale where); public static BreakIterator getLineInstance(); public static BreakIterator getLineInstance(Locale where); public static BreakIterator getSentenceInstance(); public static BreakIterator getSentenceInstance(Locale where); public static BreakIterator getWordInstance(); public static BreakIterator getWordInstance(Locale where); // Public Instance Methods public Object clone(); // Overrides Object public abstract int current(); public abstract int first(); public abstract int following(int offset); public abstract CharacterIterator getText(); public abstract int last(); public abstract int next(int n); public abstract int next(); public abstract int previous(); public void setText(String newText); public abstract void setText(CharacterIterator newText); }
Returned By: BreakIterator.getCharacterInstance(), BreakIterator.getLineInstance(), BreakIterator.getSentenceInstance(), BreakIterator.getWordInstance()
java.net.URLStreamHandlerFactory (JDK 1.0)
http://localhost/java/javaref/javanut/ch29_01.htm (3 of 3) [20/12/2001 10:59:43]
java.text.CharacterIterator (JDK 1.1)
[Chapter 18] 18.14 java.awt.Color (JDK 1.0)
Chapter 18 The java.awt Package
18.14 java.awt.Color (JDK 1.0) The Color object describes a color. The Color() constructors describe a color as red, green, and blue components between 0 and 255, or as floating-point values between 0.0 and 1.0. The class method Color.getHSBColor() creates a color using the hue/saturation/brightness color model. brighter() and darker() are useful methods to create shading effects. The getColor() methods look up a color name in the properties database and convert the resulting integer color value into a Color object. Two of these methods provide a default value to be used in case the specified color name is not found. public class Color extends Object implements Serializable { // Public Constructors public Color(int r, int g, int b); public Color(int rgb); public Color(float r, float g, float b); // Constants public static final Color black; public static final Color blue; public static final Color cyan; public static final Color darkGray; public static final Color gray; public static final Color green; public static final Color lightGray; public static final Color magenta; public static final Color orange; public static final Color pink; public static final Color red; public static final Color white; public static final Color yellow; // Class Methods public static int HSBtoRGB(float hue, float saturation, float brightness); public static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals); 1.1 public static Color decode(String nm) throws NumberFormatException; public static Color getColor(String nm); public static Color getColor(String nm, Color v); public static Color getColor(String nm, int v); public static Color getHSBColor(float h, float s, float b); // Public Instance Methods public Color brighter(); public Color darker();
http://localhost/java/javaref/javanut/ch18_14.htm (1 of 2) [20/12/2001 10:59:43]
[Chapter 18] 18.14 java.awt.Color (JDK 1.0)
public public public public public public public
boolean equals(Object obj); // Overrides Object int getBlue(); int getGreen(); int getRGB(); int getRed(); int hashCode(); // Overrides Object String toString(); // Overrides Object
}
Extended By: SystemColor
Passed To: Color.getColor(), Component.setBackground(), Component.setForeground(), ComponentPeer.setBackground(), ComponentPeer.setForeground(), Graphics.drawImage(), Graphics.setColor(), Graphics.setXORMode()
Returned By: Color.brighter(), Color.darker(), Color.decode(), Color.getColor(), Color.getHSBColor(), Component.getBackground(), Component.getForeground(), Graphics.getColor()
Type Of: Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow
java.awt.Choice (JDK 1.0)
java.awt.Component (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_14.htm (2 of 2) [20/12/2001 10:59:43]
[Chapter 24] The java.io Package
Chapter 24
24. The java.io Package Contents: java.io.BufferedOutputStream (JDK 1.0) java.io.BufferedReader (JDK 1.1) java.io.BufferedWriter (JDK 1.1) java.io.ByteArrayInputStream (JDK 1.0) java.io.ByteArrayOutputStream (JDK 1.0) java.io.CharArrayReader (JDK 1.1) java.io.CharArrayWriter (JDK 1.1) java.io.CharConversionException (JDK 1.1) java.io.DataInput (JDK 1.0) java.io.DataInputStream (JDK 1.0) java.io.DataOutput (JDK 1.0) java.io.DataOutputStream (JDK 1.0) java.io.EOFException (JDK 1.0) java.io.Externalizable (JDK 1.1) java.io.File (JDK 1.0) java.io.FileDescriptor (JDK 1.0) java.io.FileInputStream (JDK 1.0) java.io.FileNotFoundException (JDK 1.0) java.io.FileOutputStream (JDK 1.0) java.io.FileReader (JDK 1.1) java.io.FileWriter (JDK 1.1) java.io.FilenameFilter (JDK 1.0) java.io.FilterInputStream (JDK 1.0) java.io.FilterOutputStream (JDK 1.0) java.io.FilterReader (JDK 1.1) java.io.FilterWriter (JDK 1.1) java.io.InputStream (JDK 1.0) java.io.InputStreamReader (JDK 1.1) java.io.InterruptedIOException (JDK 1.0) java.io.InvalidClassException (JDK 1.1) java.io.InvalidObjectException (JDK 1.1) java.io.IOException (JDK 1.0) java.io.LineNumberInputStream (JDK 1.0; Deprecated.) java.io.LineNumberReader (JDK 1.1) java.io.NotActiveException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_01.htm (1 of 5) [20/12/2001 10:59:44]
[Chapter 24] The java.io Package
java.io.NotSerializableException (JDK 1.1) java.io.ObjectInput (JDK 1.1) java.io.ObjectInputStream (JDK 1.1) java.io.ObjectInputValidation (JDK 1.1) java.io.ObjectOutput (JDK 1.1) java.io.ObjectOutputStream (JDK 1.1) java.io.ObjectStreamClass (JDK 1.1) java.io.ObjectStreamException (JDK 1.1) java.io.OptionalDataException (JDK 1.1) java.io.OutputStream (JDK 1.0) java.io.OutputStreamWriter (JDK 1.1) java.io.PipedInputStream (JDK 1.0) java.io.PipedOutputStream (JDK 1.0) java.io.PipedReader (JDK 1.1) java.io.PipedWriter (JDK 1.1) java.io.PrintStream (JDK 1.0) java.io.PrintWriter (JDK 1.1) java.io.PushbackInputStream (JDK 1.0) java.io.PushbackReader (JDK 1.1) java.io.RandomAccessFile (JDK 1.0) java.io.Reader (JDK 1.1) java.io.SequenceInputStream (JDK 1.0) java.io.Serializable (JDK 1.1) java.io.StreamCorruptedException (JDK 1.1) java.io.StreamTokenizer (JDK 1.0) java.io.StringBufferInputStream (JDK 1.0; Deprecated.) java.io.StringReader (JDK 1.1) java.io.StringWriter (JDK 1.1) java.io.SyncFailedException (JDK 1.1) java.io.UnsupportedEncodingException (JDK 1.1) java.io.UTFDataFormatException (JDK 1.0) java.io.WriteAbortedException (JDK 1.1) java.io.Writer (JDK 1.1) The java.io package contains a relatively large number of classes, but, as you can see from Figure 24.1 and Figure 24.2, the classes form a fairly structured hierarchy. Most of the package consists of byte streams--subclasses of InputStream or OutputStream--and (in Java 1.1) character streams--subclasses of Reader or Writer. Each of these stream types has a very specific purpose, and despite its size, java.io is a straightforward package to understand and to use. Before we consider the stream classes in the package, we'll consider the important non-stream classes. File represents a file or directory name in a system independent way, and provides methods for listing directories, querying file attributes, and for renaming and deleting files. FilenameFilter is an interface that defines a method that accepts or rejects specified filenames. It is used by the java.awt.FileDialog dialog box and by the File class to specify what types of files should be included in directory listings. RandomAccessFile allows you to read or write from or to arbitrary locations of a file. Often, though, you'll prefer sequential access to a file and should use one of the stream classes. InputStream and OutputStream are abstract classes that define methods for reading and writing bytes. Their subclasses allow bytes to be read from and written to a variety of sources and sinks. FileInputStream and FileOutputStream read from and write to files. ByteArrayInputStream and ByteArrayOutputStream read from and write to an array of bytes in memory. PipedInputStream reads bytes from a PipedOutputStream, and
http://localhost/java/javaref/javanut/ch24_01.htm (2 of 5) [20/12/2001 10:59:44]
[Chapter 24] The java.io Package
PipedOutputStream writes bytes to a PipedInputStream. These classes work together to implement a "pipe" for communication between threads. FilterInputStream and FilterOutputStream are special--they filter input and output bytes. When a FilterInputStream is created, an InputStream is specified for it to filter. When you call the read() method of a FilterInputStream, it calls the read() method of its specified stream, processes the bytes it reads somehow, and then returns the filtered bytes. Similarly, you specify an OutputStream to be filtered when you create a FilterOutputStream. Calling the write() method of a FilterOutputStream causes it to process your bytes in some way and then pass those filtered bytes to the write() method of its OutputStream. Figure 24.1: The java.io package
http://localhost/java/javaref/javanut/ch24_01.htm (3 of 5) [20/12/2001 10:59:44]
[Chapter 24] The java.io Package
Figure 24.2: The exception classes of the java.io package
FilterInputStream and FilterOutputStream do not perform any filtering themselves; this is done by their subclasses. BufferedInputStream and BufferedOutputStream provide input and output buffering and can increase I/O efficiency. DataInputStream reads raw bytes from a stream and interprets them in various binary formats. It has various methods to read primitive Java data types in their standard binary formats. DataOutputStream allows you to write Java primitive data types in binary format. In Java 1.1, the byte streams just described are complemented by an analogous set of character input and output streams. Reader is the superclass of all character input streams, and Writer is the superclass of all character output streams. These character streams supersede the byte streams for all textual I/O. They are more efficient than the byte streams, and they correctly handle the conversion between local encodings and Unicode text, making them invaluable for internationalized programs. Most of the Reader and Writer streams have obvious byte stream analogs. BufferedReader is a commonly used stream. It provides buffering for efficiency, and also has a readLine() method to read one line of text at a time. PrintWriter is another very common stream--its methods allow output of a textual representation of any primitive Java type or of any object (via the object's toString() method). See Chapter 11, Internationalization for a discussion of the use of character streams in internationalized programs. The ObjectInputStream and ObjectOutputStream classes are special. These byte stream classes are new in Java 1.1 and are part of the Object Serialization API. See Chapter 9, Object Serialization for further details.
24.1 java.io.BufferedInputStream (JDK 1.0) This class is a FilterInputStream that provides input data buffering--efficiency is increased by reading in large amounts of data and storing them in an internal buffer. When data is requested, it is usually available from the buffer. Thus, most calls to read data do not have to make a call to actually read data from a disk, network, or other slow source. Create a BufferedInputStream by specifying the InputStream that is to have buffering applied in the call to the constructor. See also BufferedReader. public class BufferedInputStream extends FilterInputStream {
http://localhost/java/javaref/javanut/ch24_01.htm (4 of 5) [20/12/2001 10:59:44]
[Chapter 24] The java.io Package
// Public Constructors public BufferedInputStream(InputStream in); public BufferedInputStream(InputStream in, int size); // Protected Instance Variables protected byte[] buf; protected int count; protected int marklimit; protected int markpos; protected int pos; // Public Instance Methods public synchronized int available() throws IOException; // Overrides FilterInputStream public synchronized void mark(int readlimit); // Overrides FilterInputStream public boolean markSupported(); // Overrides FilterInputStream public synchronized int read() throws IOException; // Overrides FilterInputStream public synchronized int read(byte[] b, int off, int len) throws IOException; // Overrides FilterInputStream public synchronized void reset() throws IOException; // Overrides FilterInputStream public synchronized long skip(long n) throws IOException; // Overrides FilterInputStream }
Hierarchy: Object->InputStream->FilterInputStream->BufferedInputStream
java.beans.Visibility (JDK 1.1)
java.io.BufferedOutputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_01.htm (5 of 5) [20/12/2001 10:59:44]
[Chapter 24] 24.2 java.io.BufferedOutputStream (JDK 1.0)
Chapter 24 The java.io Package
24.2 java.io.BufferedOutputStream (JDK 1.0) This class is a FilterOutputStream that provides output data buffering--output efficiency is increased by storing values to be written in a buffer and actually writing them out only when the buffer fills up or when the flush() method is called. Create a BufferedOutputStream by specifying the OutputStream that is to have buffering applied in the call to the constructor. See also BufferedWriter. public class BufferedOutputStream extends FilterOutputStream { // Public Constructors public BufferedOutputStream(OutputStream out); public BufferedOutputStream(OutputStream out, int size); // Protected Instance Variables protected byte[] buf; protected int count; // Public Instance Methods public synchronized void flush() throws IOException; // Overrides FilterOutputStream public synchronized void write(int b) throws IOException; // Overrides FilterOutputStream public synchronized void write(byte[] b, int off, int len) throws IOException; // Overrides FilterOutputStream }
Hierarchy: Object->OutputStream->FilterOutputStream->BufferedOutputStream
java.io.BufferedInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_02.htm [20/12/2001 10:59:45]
java.io.BufferedReader (JDK 1.1)
[Chapter 24] 24.3 java.io.BufferedReader (JDK 1.1)
Chapter 24 The java.io Package
24.3 java.io.BufferedReader (JDK 1.1) This class applies buffering to a character input stream, thereby improving the efficiency of character input. You create a BufferedReader by specifying some other character input stream that it is to buffer input from. (You can also specify a buffer size at this time, although the default size is usually fine.) Typically you use this sort of buffering when you are using a FileReader or InputStreamReader. BufferedReader defines the standard set of Reader methods, and also provides a readLine() method that reads a line of text (not including the line-terminators) and returns it as a String. BufferedReader is the character-stream analog of BufferedInputStream. It also provides a replacement for the deprecated readLine() method of DataInputStream, which did not properly convert bytes into characters. public class BufferedReader extends Reader { // Public Constructors public BufferedReader(Reader in, int sz); public BufferedReader(Reader in); // Public Instance Methods public void close() throws IOException; // Defines Reader public void mark(int readAheadLimit) throws IOException; // Overrides Reader public boolean markSupported(); // Overrides Reader public int read() throws IOException; // Overrides Reader public int read(char[] cbuf, int off, int len) throws IOException; // Defines Reader public String readLine() throws IOException; public boolean ready() throws IOException; // Overrides Reader public void reset() throws IOException; // Overrides Reader public long skip(long n) throws IOException; // Overrides Reader }
Hierarchy: Object->Reader->BufferedReader
Extended By: LineNumberReader
java.io.BufferedOutputStream (JDK 1.0)
java.io.BufferedWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_03.htm (1 of 2) [20/12/2001 10:59:45]
[Chapter 24] 24.3 java.io.BufferedReader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_03.htm (2 of 2) [20/12/2001 10:59:45]
[Chapter 24] 24.4 java.io.BufferedWriter (JDK 1.1)
Chapter 24 The java.io Package
24.4 java.io.BufferedWriter (JDK 1.1) This class applies buffering to a character output stream, improving output efficiency by coalescing many small write requests into a single larger request. You create a BufferedWriter by specifying some other character output stream to which it sends its buffered and coalesced output. (You can also specify a buffer size at this time, although the default size is usually satisfactory.) Typically you use this sort of buffering when you are using a FileWriter or OutputStreamWriter. BufferedWriter defines the standard write(), flush(), and close() methods that all output streams define, but it also adds a newLine() method, which outputs the platform-dependent line separator (usually a newline character, a carriage return character, or both) to the stream. BufferedWriter is the character-stream analog of BufferedOutputStream. public class BufferedWriter extends Writer { // Public Constructors public BufferedWriter(Writer out); public BufferedWriter(Writer out, int sz); // Public Instance Methods public void close() throws IOException; // Defines Writer public void flush() throws IOException; // Defines Writer public void newLine() throws IOException; public void write(int c) throws IOException; // Overrides Writer public void write(char[] cbuf, int off, int len) throws IOException; // Defines Writer public void write(String s, int off, int len) throws IOException; // Overrides Writer }
Hierarchy: Object->Writer->BufferedWriter
java.io.BufferedReader (JDK 1.1)
java.io.ByteArrayInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_04.htm [20/12/2001 10:59:45]
[Chapter 18] 18.7 java.awt.Button (JDK 1.0)
Chapter 18 The java.awt Package
18.7 java.awt.Button (JDK 1.0) This class represents a GUI pushbutton that displays a specified textual label. Use setActionCommand() to specify an identifying string that is included in the ActionEvent events generated by the button. public class Button extends Component { // Public Constructors public Button(); public Button(String label); // Public Instance Methods 1.1 public synchronized void addActionListener(ActionListener l); public void addNotify(); // Overrides Component 1.1 public String getActionCommand(); public String getLabel(); 1.1 public synchronized void removeActionListener(ActionListener l); 1.1 public void setActionCommand(String command); public synchronized void setLabel(String label); // Protected Instance Methods protected String paramString(); // Overrides Component 1.1 protected void processActionEvent(ActionEvent e); 1.1 protected void processEvent(AWTEvent e); // Overrides Component }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Button
Passed To: Toolkit.createButton()
java.awt.BorderLayout (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_07.htm [20/12/2001 10:59:45]
java.awt.Canvas (JDK 1.0)
[Chapter 22] The java.awt.peer Package
Chapter 22
22. The java.awt.peer Package Contents: java.awt.peer.CanvasPeer (JDK 1.0) java.awt.peer.CheckboxMenuItemPeer (JDK 1.0) java.awt.peer.CheckboxPeer (JDK 1.0) java.awt.peer.ChoicePeer (JDK 1.0) java.awt.peer.ComponentPeer (JDK 1.0) java.awt.peer.ContainerPeer (JDK 1.0) java.awt.peer.DialogPeer (JDK 1.0) java.awt.peer.FileDialogPeer (JDK 1.0) java.awt.peer.FontPeer (JDK 1.1) java.awt.peer.FramePeer (JDK 1.0) java.awt.peer.LabelPeer (JDK 1.0) java.awt.peer.LightweightPeer (JDK 1.1) java.awt.peer.ListPeer (JDK 1.0) java.awt.peer.MenuBarPeer (JDK 1.0) java.awt.peer.MenuComponentPeer (JDK 1.0) java.awt.peer.MenuItemPeer (JDK 1.0) java.awt.peer.MenuPeer (JDK 1.0) java.awt.peer.PanelPeer (JDK 1.0) java.awt.peer.PopupMenuPeer (JDK 1.1) java.awt.peer.ScrollPanePeer (JDK 1.1) java.awt.peer.ScrollbarPeer (JDK 1.0) java.awt.peer.TextAreaPeer (JDK 1.0) java.awt.peer.TextComponentPeer (JDK 1.0) java.awt.peer.TextFieldPeer (JDK 1.0) java.awt.peer.WindowPeer (JDK 1.0) The java.awt.peer package consists entirely of interface definitions. The hierarchy of these interfaces is shown in Figure 22.1. Each java.awt.peer interface corresponds to one of the
http://localhost/java/javaref/javanut/ch22_01.htm (1 of 3) [20/12/2001 10:59:46]
[Chapter 22] The java.awt.peer Package
java.awt Component or MenuComponent classes, and as you can see from the figure, the hierarchy of this package is identical to the hierarchy of those portions of the java.awt package. The interfaces in this package define the methods that must be supported by the GUI components on a specific platform. Porting the java.awt GUI components to a new platform is a matter of implementing each of the methods in each of the interfaces in this package on top of the native GUI components of that platform. The Toolkit object in the java.awt package collects the implementations of these peer interfaces for a given platform. Toolkit contains methods that create instances of each of the interfaces in this package. Normal applications never need to instantiate these peers directly; instead they use the java.awt Component classes, which create peers as needed. Because these peer interfaces are rarely used, and because the methods are quite similar to those of the corresponding java.awt component, there is no additional commentary for the individual interface definitions below. Figure 22.1: The java.awt.peer package
http://localhost/java/javaref/javanut/ch22_01.htm (2 of 3) [20/12/2001 10:59:46]
[Chapter 22] The java.awt.peer Package
22.1 java.awt.peer.ButtonPeer (JDK 1.0) public abstract interface ButtonPeer extends ComponentPeer { // Public Instance Methods public abstract void setLabel(String label); }
Returned By: Toolkit.createButton()
java.awt.image.ReplicateScaleFilter (JDK 1.1)
http://localhost/java/javaref/javanut/ch22_01.htm (3 of 3) [20/12/2001 10:59:46]
java.awt.peer.CanvasPeer (JDK 1.0)
[Chapter 16] native2ascii
Chapter 16 JDK Tools
native2ascii Name native2ascii---Convert Java source code to ASCII
Availability JDK 1.1 and later.
Synopsis native2ascii [ options ] [ inputfile [ outputfile ]]
Description javac can only process files encoded in ASCII, with any other characters encoded using the \uxxxx Unicode notation. native2ascii is a simple program that reads a Java source file encoded using a local encoding and converts it to the ASCII-plus-encoded-Unicode form required by javac. The inputfile and outputfile are optional. If unspecified, standard input and standard output are used, making native2ascii suitable for use in pipes.
Options -encoding encoding-name Specifies the encoding used by source files. If this option is not specified, the encoding is taken from the file.encoding system property. -reverse
http://localhost/java/javaref/javanut/ch16_10.htm (1 of 2) [20/12/2001 10:59:46]
[Chapter 16] native2ascii
Specifies that the conversion should be done in reverse--from encoded \uxxxx characters to characters in the native encoding.
See Also java.io.InputStreamReader, java.io.OutputStreamWriter
jdb
http://localhost/java/javaref/javanut/ch16_10.htm (2 of 2) [20/12/2001 10:59:46]
serialver
[Chapter 25] 25.16 java.lang.Compiler (JDK 1.0)
Chapter 25 The java.lang Package
25.16 java.lang.Compiler (JDK 1.0) The static methods of this class provide an interface to the just-in-time (JIT) byte-code to native code compiler in use by the Java interpreter. If no JIT compiler is in use by the VM, these methods do nothing. compileClass() asks the JIT compiler to compile the specified class. compileClasses() asks the JIT compiler to compile all classes that match the specified name. These methods return true if the compilation was successful, or false if it failed or if there is no JIT compiler on the system. enable() and disable() turn just-in-time compilation on and off. command() asks the JIT compiler to perform some compiler-specific operation. This is a hook for vendor extensions. No standard operations have been defined. public final class Compiler extends Object { // No Constructor // Class Methods public static native Object command(Object any); public static native boolean compileClass(Class clazz); public static native boolean compileClasses(String string); public static native void disable(); public static native void enable(); }
java.lang.Cloneable (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_16.htm [20/12/2001 10:59:47]
java.lang.Double (JDK 1.0)
[Chapter 25] 25.67 java.lang.VerifyError (JDK 1.0)
Chapter 25 The java.lang Package
25.67 java.lang.VerifyError (JDK 1.0) Signals that a class has not passed the byte-code verification procedures. public class VerifyError extends LinkageError { // Public Constructors public VerifyError(); public VerifyError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->VerifyError
java.lang.UnsatisfiedLinkError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_67.htm [20/12/2001 10:59:47]
java.lang.VirtualMachineError (JDK 1.0)
[Chapter 25] 25.6 java.lang.Byte (JDK 1.1)
Chapter 25 The java.lang Package
25.6 java.lang.Byte (JDK 1.1) This class provides an object wrapper around the byte primitive type. It defines useful constants for the minimum and maximum values that can be stored by the byte type, and also a Class object constant that represents the byte type. It also provides various methods for converting Byte values to and from strings and other numeric types. Most of the static methods of this class are used to convert a String to a Byte object or a byte value: the four parseByte() and valueOf() methods parse a number from the specified string, using an optionally specified radix, and return it in one of these two forms. The decode() method parses a byte specified in base 10, base 8, or base 16 and returns it as a Byte. If the string begins with "0x" or "#", it is interpreted as a hexadecimal number. If it begins with "0", it is interpreted as an octal number. Otherwise, it is interpreted as a decimal number. Note that this class has two different toString() methods. One is static and converts a byte primitive value to a String. The other is the usual toString() method that converts a Byte object to a string. Most of the remaining methods convert a Byte to various primitive numeric types. public final class Byte extends Number { // Public Constructors public Byte(byte value); public Byte(String s) throws NumberFormatException; // Constants public static final byte MAX_VALUE; public static final byte MIN_VALUE; public static final Class TYPE; // Class Methods public static Byte decode(String nm) throws NumberFormatException; public static byte parseByte(String s) throws NumberFormatException; public static byte parseByte(String s, int radix) throws NumberFormatException; public static String toString(byte b); public static Byte valueOf(String s, int radix) throws NumberFormatException; public static Byte valueOf(String s) throws NumberFormatException; // Public Instance Methods public byte byteValue(); // Overrides Number public double doubleValue(); // Defines Number public boolean equals(Object obj); // Overrides Object public float floatValue(); // Defines Number public int hashCode(); // Overrides Object public int intValue(); // Defines Number public long longValue(); // Defines Number
http://localhost/java/javaref/javanut/ch25_06.htm (1 of 2) [20/12/2001 10:59:47]
[Chapter 25] 25.6 java.lang.Byte (JDK 1.1)
public short shortValue(); // Overrides Number public String toString(); // Overrides Object }
Hierarchy: Object->Number(Serializable)->Byte
Returned By: Byte.decode(), Byte.valueOf()
java.lang.Boolean (JDK 1.0)
java.lang.Character (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_06.htm (2 of 2) [20/12/2001 10:59:47]
[Chapter 24] 24.5 java.io.ByteArrayInputStream (JDK 1.0)
Chapter 24 The java.io Package
24.5 java.io.ByteArrayInputStream (JDK 1.0) This class is a subclass of InputStream in which input data come from a specified array of byte values. This is useful when you want to read data in memory as if it were coming from a file or pipe or socket. Note that the specified array of bytes is not copied when a ByteArrayInputStream is created. See also CharArrayReader. public class ByteArrayInputStream extends InputStream { // Public Constructors public ByteArrayInputStream(byte[] buf); public ByteArrayInputStream(byte[] buf, int offset, int length); // Protected Instance Variables protected byte[] buf; protected int count; 1.1 protected int mark; protected int pos; // Public Instance Methods public synchronized int available(); // Overrides InputStream 1.1 public void mark(int markpos); // Overrides InputStream 1.1 public boolean markSupported(); // Overrides InputStream public synchronized int read(); // Defines InputStream public synchronized int read(byte[] b, int off, int len); // Overrides InputStream public synchronized void reset(); // Overrides InputStream public synchronized long skip(long n); // Overrides InputStream }
Hierarchy: Object->InputStream->ByteArrayInputStream
java.io.BufferedWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_05.htm [20/12/2001 10:59:47]
java.io.ByteArrayOutputStream (JDK 1.0)
[Chapter 24] 24.6 java.io.ByteArrayOutputStream (JDK 1.0)
Chapter 24 The java.io Package
24.6 java.io.ByteArrayOutputStream (JDK 1.0) This class is a subclass of OutputStream in which data that are written are stored in an internal byte array. The internal array grows as necessary, and can be retrieved with toByteArray() or toString(). The reset() method discards any data currently stored in the internal array and begins storing data from the beginning again. See also CharArrayWriter. public class ByteArrayOutputStream extends OutputStream { // Public Constructors public ByteArrayOutputStream(); public ByteArrayOutputStream(int size); // Protected Instance Variables protected byte[] buf; protected int count; // Public Instance Methods public synchronized void reset(); public int size(); public synchronized byte[] toByteArray(); public String toString(); // Overrides Object 1.1 public String toString(String enc) throws UnsupportedEncodingException; # public String toString(int hibyte); public synchronized void write(int b); // Defines OutputStream public synchronized void write(byte[] b, int off, int len); // Overrides OutputStream public synchronized void writeTo(OutputStream out) throws IOException; }
Hierarchy: Object->OutputStream->ByteArrayOutputStream
java.io.ByteArrayInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_06.htm [20/12/2001 10:59:48]
java.io.CharArrayReader (JDK 1.1)
[Chapter 24] 24.9 java.io.CharConversionException (JDK 1.1)
Chapter 24 The java.io Package
24.9 java.io.CharConversionException (JDK 1.1) This exception signals an error when converting bytes to characters or vice versa. public class CharConversionException extends IOException { // Public Constructors public CharConversionException(); public CharConversionException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->CharConversionException
java.io.CharArrayWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_09.htm [20/12/2001 10:59:48]
java.io.DataInput (JDK 1.0)
[Chapter 3] Classes and Objects in Java
Chapter 3
3. Classes and Objects in Java Contents: Introduction to Classes and Objects Object Creation Class Variables Class Methods Object Destruction Subclasses and Inheritance Overriding Methods Data Hiding and Encapsulation Abstract Classes and Interfaces C++ Features Not Found in Java Summary Java is an object-oriented language. "Object-oriented" is a term that has become so commonly used as to have practically no concrete meaning. This chapter explains just what "object-oriented" means for Java. It covers: ● Classes and objects in Java ● Creating objects ● Garbage collection to free up unused objects ● The difference between class (or static) variables and instance variables, and the difference between class (or static) methods and instance methods ● Extending a class to create a subclass ● Overriding class methods and dynamic method lookup ● Abstract classes ● Interface types and their implementation by classes If you are a C++ programmer, or have other object-oriented programming experience, many of the concepts in this list should be familiar to you. If you do not have object-oriented experience, don't fear: This chapter assumes no knowledge of object-oriented concepts. We saw in the last chapter that close analogies can be drawn between Java and C. Unfortunately for C++ programmers, the same is not true for Java and C++. Java uses object-oriented programming concepts that are familiar to C++ programmers, and it even borrows from C++ syntax in a number of places, but the analogies between Java and C++ are not nearly as strong as those between Java and C. [1] C++ programmers may have http://localhost/java/javaref/javanut/ch03_01.htm (1 of 4) [20/12/2001 10:59:48]
[Chapter 3] Classes and Objects in Java
an easier time with this chapter than C programmers will, but they should still read it carefully and try not to form preconceptions about Java based on their knowledge of C++. [1] As we'll see, Java supports garbage collection and dynamic method lookup. This actually makes it a closer relative, beneath its layer of C-like syntax, to languages like Smalltalk than to C++.
3.1 Introduction to Classes and Objects A class is a collection of data and methods that operate on that data. [2] The data and methods, taken together, usually serve to define the contents and capabilities of some kind of object. [2] A method is the object-oriented term for a procedure or a function. You'll see it used a lot in this book. Treat it as a synonym for "procedure." For example, a circle can be described by the x, y position of its center and by its radius. There are a number of things we can do with circles: compute their circumference, compute their area, check whether points are inside them, and so on. Each circle is different (i.e., has a different center or radius), but as a class, circles have certain intrinsic properties that we can capture in a definition. Example 3.1 shows how we could partially define the class of circles in Java. Notice that the class definition contains data and methods (procedures) within the same pair of curly brackets. [3] [3] C++ programmers should note that methods go inside the class definition in Java, not outside with the :: operator as they usually do in C++. Example 3.1: The Class of Circles, Partially Captured in Java Code public class Circle { public double x, y; // The coordinates of the center public double r; // The radius // Methods that return the circumference and area of the circle public double circumference() { return 2 * 3.14159 * r; } public double area() { return 3.14159 * r*r; } }
Objects Are Instances of a Class Now that we've defined (at least partially) the class Circle, we want to do something with it. We can't do anything with the class of circles itself--we need a particular circle to work with. We need an instance of the class, a single circle object. By defining the Circle class in Java, we have created a new data type. We can declare variables of that type: Circle c; But this variable c is simply a name that refers to a circle object; it is not an object itself. In Java, all objects must be created dynamically. This is almost always done with the new keyword:
http://localhost/java/javaref/javanut/ch03_01.htm (2 of 4) [20/12/2001 10:59:48]
[Chapter 3] Classes and Objects in Java
Circle c; c = new Circle(); Now we have created an instance of our Circle class--a circle object--and have assigned it to the variable c, which is of type Circle.
Accessing Object Data Now that we've created an object, we can use its data fields. The syntax should be familiar to C programmers: Circle c = new Circle(); c.x = 2.0; // Initialize our circle to have center (2, 2) and radius 1.0. c.y = 2.0; c.r = 1.0;
Using Object Methods This is where things get interesting! To access the methods of an object, we use the same syntax as accessing the data of an object: Circle c = new Circle(); double a; c.r = 2.5; a = c.area(); Take a look at that last line. We did not say: a = area(c); We said: a = c.area(); This is why it is called "object-oriented" programming; the object is the focus here, not the function call. This is probably the single most important feature of the object-oriented paradigm. Note that we don't have to pass an argument to c.area(). The object we are operating on, c, is implicit in the syntax. Take a look at Example 3.1 again: you'll notice the same thing in the definition of the area() method--it doesn't take an argument. It is implicit in the language that a method operates on an instance of the class within which it is defined. Thus our area() method can use the r field of the class freely--it is understood that it is referring to the radius of whatever Circle instance invokes the method.
How It Works What's going on here? How can a method that takes no arguments know what data to operate on? In fact, the area() method does have an argument! area() is implemented with an implicit argument that is not shown in the method declaration. The implicit argument is named this, and refers to "this object"--the Circle object through which the method is invoked. this is often called the "this pointer." [4]
http://localhost/java/javaref/javanut/ch03_01.htm (3 of 4) [20/12/2001 10:59:48]
[Chapter 3] Classes and Objects in Java
[4] "this pointer" is C++ terminology. Since Java does not support pointers, I prefer the term "this reference." The implicit this argument is not shown in method signatures because it is usually not needed--whenever a Java method accesses the fields in its class, it is implied that it is accessing fields in the object referred to by the this argument. The same is true, as we'll see, when a method in a class invokes other methods in the class--it is implicit that the methods are being invoked for the this object. We can use the this keyword explicitly when we want to make explicit that a method is accessing its own variables and/or methods. For example, we could rewrite the area() method like this: public double area() { return 3.14159 * this.r * this.r; } In a method this simple, it is not necessary to be explicit. In more complicated cases, however, you may find that it increases the clarity of your code to use an explicit this where it is not strictly required. An instance where the this keyword is required is when a method argument or a local variable in a method has the same name as one of the fields of the class. In this case, you must use this to access the field. If you used the field name alone, you would end up accessing the argument or local variable with the same name. We'll see examples of this in the next section.
Miscellaneous Differences
http://localhost/java/javaref/javanut/ch03_01.htm (4 of 4) [20/12/2001 10:59:48]
Object Creation
[Chapter 3] 3.10 C++ Features Not Found in Java
Chapter 3 Classes and Objects in Java
3.10 C++ Features Not Found in Java Throughout this chapter, we've noted similarities and differences between Java and C++ in footnotes. Java shares enough concepts and features with C++ to make it an easy language for C++ programmers to pick up. There are several features of C++ that have no parallel in Java, however. In general, Java does not adopt those features of C++ that make the language significantly more complicated. These omissions from Java (or simplifications of C++) are described below. C++ supports "multiple inheritance" of method implementations from more than one superclass at a time. While this seems like a very useful feature, adding it to the language actually turns out to introduce many complexities. The Java language designers chose to avoid the added complexity by using interfaces instead. Thus, a class in Java can only inherit method implementations from a single superclass, but it can inherit method declarations from any number of interfaces. In practice, this is not any particular hardship. C++ supports (though not yet in a very standardized way) templates that allow you, for example, to implement a Stack class and then instantiate it as Stack or Stack<double> to produce two separate types: a stack of integers and a stack of floating-point values. Java has no such facility. However, the fact that every class in Java is a subclass of Object means that every object can be cast to an instance of Object. Thus, in Java, it is often sufficient to define a data structure (such as a Stack class) that operates on Object values--the objects can be cast back to their actual type whenever necessary. C++ allows you to define operators that perform arbitrary operations on instances of your classes. In effect, it allows you to extend the syntax of the language. This is a nifty feature, called operator overloading, that makes for very elegant examples. In practice, however, it tends to make code hard to understand. After much debate, the Java language designers decided to omit such "operator overloading" from the language. Note, though, that the use of the + operator for string concatenation in Java is at least reminiscent of operator overloading. C++ allows you to define "conversion functions" for a class that automatically invoke an appropriate constructor method when a value is assigned to a variable of that class. This is simply a syntactic shortcut (similar to overriding the assignment operator) and is not included in Java. In C++, objects are by default manipulated by value; you must use & to specify a variable or function argument that is automatically manipulated by reference. In Java, all objects are manipulated by
http://localhost/java/javaref/javanut/ch03_10.htm (1 of 2) [20/12/2001 10:59:49]
[Chapter 3] 3.10 C++ Features Not Found in Java
reference, so there is no need for this & syntax.
Abstract Classes and Interfaces
http://localhost/java/javaref/javanut/ch03_10.htm (2 of 2) [20/12/2001 10:59:49]
Summary
[Chapter 30] 30.9 java.util.GregorianCalendar (JDK 1.1)
Chapter 30 The java.util Package
30.9 java.util.GregorianCalendar (JDK 1.1) This concrete subclass of Calendar implements the "standard" solar calendar with years numbered from the birth of Christ, which is used in most locales throughout the world. You do not typically use this class directly, but instead obtain a Calendar object suitable for the default locale by calling Calendar.getInstance(). See Calendar for details on working with Calendar objects. There is a discontinuity in the Gregorian calendar that represents the historical switch from the Julian calendar to the Gregorian calendar. By default GregorianCalendar assumes that this switch occurs on October 15, 1582. Most programs need not be concerned with this. public class GregorianCalendar extends Calendar { // Public Constructors public GregorianCalendar(); public GregorianCalendar(TimeZone zone); public GregorianCalendar(Locale aLocale); public GregorianCalendar(TimeZone zone, Locale aLocale); public GregorianCalendar(int year, int month, int date); public GregorianCalendar(int year, int month, int date, int hour, int minute); public GregorianCalendar(int year, int month, int date, int hour, int minute, int second); // Constants public static final int AD; public static final int BC; // Public Instance Methods public void add(int field, int amount); // Defines Calendar public boolean after(Object when); // Defines Calendar public boolean before(Object when); // Defines Calendar public Object clone(); // Overrides Calendar public boolean equals(Object obj); // Defines Calendar public int getGreatestMinimum(int field); // Defines Calendar public final Date getGregorianChange(); public int getLeastMaximum(int field); // Defines Calendar public int getMaximum(int field); // Defines Calendar public int getMinimum(int field); // Defines Calendar public synchronized int hashCode(); // Overrides Object public boolean isLeapYear(int year); public void roll(int field, boolean up); // Defines Calendar public void setGregorianChange(Date date); // Protected Instance Methods
http://localhost/java/javaref/javanut/ch30_09.htm (1 of 2) [20/12/2001 10:59:49]
[Chapter 30] 30.9 java.util.GregorianCalendar (JDK 1.1)
protected void computeFields(); // Defines Calendar protected void computeTime(); // Defines Calendar }
Hierarchy: Object->Calendar(Serializable, Cloneable)->GregorianCalendar
java.util.EventObject (JDK 1.1)
java.util.Hashtable (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_09.htm (2 of 2) [20/12/2001 10:59:49]
[Chapter 21] 21.13 java.awt.image.RGBImageFilter (JDK 1.0)
Chapter 21 The java.awt.image Package
21.13 java.awt.image.RGBImageFilter (JDK 1.0) This abstract class is an ImageFilter that provides an easy way to implement filters that modify the colors of an image. To create a color filter that modifies the colors of an image, you should subclass RGBImageFilter and provide a definition of filterRGB() that converts the input pixel value (in the default RGB color model) to an output value. If the conversion does not depend on the location of the pixel, set the canFilterIndexColorModel variable to true so that the RGBImageFilter can save time by filtering the colormap of an image that uses an IndexColorModel instead of filtering each pixel of the image. public abstract class RGBImageFilter extends ImageFilter { // Default Constructor: public RGBImageFilter() // Protected Instance Variables protected boolean canFilterIndexColorModel; protected ColorModel newmodel; protected ColorModel origmodel; // Public Instance Methods public IndexColorModel filterIndexColorModel(IndexColorModel icm); public abstract int filterRGB(int x, int y, int rgb); public void filterRGBPixels(int x, int y, int w, int h, int[] pixels, int off, int scansize); public void setColorModel(ColorModel model); // Overrides ImageFilter public void setPixels(int x, int y, int w, int h, ColorModel model, public void setPixels'u'byte[] pixels, int off, int scansize); // Overrides ImageFilter public void setPixels(int x, int y, int w, int h, ColorModel model, public void setPixels'u'int[] pixels, int off, int scansize); // Overrides ImageFilter public void substituteColorModel(ColorModel oldcm, ColorModel newcm); }
Hierarchy: Object->ImageFilter(ImageConsumer, Cloneable)->RGBImageFilter
java.awt.image.PixelGrabber (JDK 1.0)
java.awt.image.ReplicateScaleFilter (JDK 1.1)
http://localhost/java/javaref/javanut/ch21_13.htm [20/12/2001 10:59:49]
[Chapter 24] 24.16 java.io.File (JDK 1.0)
Chapter 24 The java.io Package
24.16 java.io.File (JDK 1.0) This class supports a platform-independent definition of file and directory names. It also provides methods to list the files in a directory, to check the existence, readability, writeability, type, size, and modification time of files and directories, to make new directories, to rename files and directories, and to delete files and directories. The constants defined by this class are the platform-dependent directory and path separator characters, available as a String or char. getName() returns the name of the File with any directory names omitted. getPath() returns the full name of the file, including the directory name. getParent() returns the directory of the File. If the File is an absolute specification, then getAbsolutePath() returns the complete filename. Otherwise, if the File is a relative file specification, it returns the relative filename appended to the current working directory. isAbsolute() tests whether the File is an absolute specification. exists(), canWrite(), canRead(), isFile(), and isDirectory() perform the obvious tests on the specified File. length() returns the length of the file. lastModified() returns the modification time of the file (which should be used for comparison with other file times only, and not interpreted as any particular time format). list() returns the name of all entries in a directory that are not rejected by an optional FilenameFilter. mkdir() creates a directory. mkdirs() creates all the directories in a File specification. renameTo() renames a file or directory. delete() deletes a file or directory. Note that there is no method to create a file; that is done with a FileOutputStream. public class File extends Object implements Serializable { // Public Constructors public File(String path); public File(String path, String name); public File(File dir, String name); // Constants public static final String pathSeparator; public static final char pathSeparatorChar; public static final String separator; public static final char separatorChar;
http://localhost/java/javaref/javanut/ch24_16.htm (1 of 2) [20/12/2001 10:59:49]
[Chapter 24] 24.16 java.io.File (JDK 1.0)
// Public Instance Methods public boolean canRead(); public boolean canWrite(); public boolean delete(); public boolean equals(Object obj); // Overrides Object public boolean exists(); public String getAbsolutePath(); 1.1 public String getCanonicalPath() throws IOException; public String getName(); public String getParent(); public String getPath(); public int hashCode(); // Overrides Object public native boolean isAbsolute(); public boolean isDirectory(); public boolean isFile(); public long lastModified(); public long length(); public String[] list(); public String[] list(FilenameFilter filter); public boolean mkdir(); public boolean mkdirs(); public boolean renameTo(File dest); public String toString(); // Overrides Object }
Passed To: File(), File.renameTo(), FileInputStream(), FilenameFilter.accept(), FileOutputStream(), FileReader(), FileWriter(), RandomAccessFile(), ZipFile()
java.io.Externalizable (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_16.htm (2 of 2) [20/12/2001 10:59:49]
java.io.FileDescriptor (JDK 1.0)
[Chapter 18] 18.8 java.awt.Canvas (JDK 1.0)
Chapter 18 The java.awt Package
18.8 java.awt.Canvas (JDK 1.0) This class is a Component that does no default drawing or event handling on its own. You can subclass it to display any kind of drawing or image, and to handle any kind of user input event. Canvas inherits the event handling methods of its superclass. In Java 1.1, you can also subclass Component directly to create a "lightweight component," instead of having to subclass Canvas. public class Canvas extends Component { // Public Constructor 1.1 public Canvas(); // Public Instance Methods public void addNotify(); // Overrides Component public void paint(Graphics g); // Overrides Component }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Canvas
Passed To: Toolkit.createCanvas()
java.awt.Button (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_08.htm [20/12/2001 10:59:50]
java.awt.CardLayout (JDK 1.0)
[Chapter 22] 22.2 java.awt.peer.CanvasPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.2 java.awt.peer.CanvasPeer (JDK 1.0) public interface CanvasPeer extends ComponentPeer { }
Returned By: Toolkit.createCanvas()
java.awt.peer.ButtonPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_02.htm [20/12/2001 10:59:50]
java.awt.peer.CheckboxMenuItemPeer (JDK 1.0)
[Chapter 2] 2.4 No Preprocessor
Chapter 2 How Java Differs from C
2.4 No Preprocessor Java does not include any kind of preprocessor like the C cpp preprocessor. It may seem hard to imagine programming without #define, #include, and #ifdef, but in fact, Java really does not require these constructs.
Defining Constants Any variable declared final in Java is a constant--its value must be specified with an initializer when it is declared, and that value may never be changed. The Java equivalent of a C #define'ed constant is a static final variable declared within a class definition. If the compiler can compute the value of such a static final variable at compile-time, it uses the computed value to pre-compute other compile-time constants that refer to the value. The variable java.lang.Math.PI is an example of such a constant. It is declared like this: public final class Math { ... public static final double PI = 3.14159.....; ... } Note two things about this example. First, the C convention of using CAPITAL letters for constants is also a Java convention. Second, note the advantage Java constants have over C preprocessor constants: Java constants have globally unique hierarchic names, while constants defined with the C preprocessor always run the risk of a name collision. Also, Java constants are strongly typed and allow better type-checking by the compiler than C preprocessor constants.
Defining Macros The C preprocessor allows you to define macros--a construct that looks like a function invocation but that is actually replaced directly with C code, saving the overhead of a function call. Java has no equivalent to this sort of macro, but compiler technology has advanced to a point where macros are rarely necessary any more. A good Java compiler should automatically be able to "inline" short Java methods where appropriate.
http://localhost/java/javaref/javanut/ch02_04.htm (1 of 2) [20/12/2001 10:59:50]
[Chapter 2] 2.4 No Preprocessor
Including Files Java does not have a #include directive, but it does not need one. Java defines a mapping of fully qualified class names (like java.lang.Math) to a directory and file structure (like java/lang/Math.class). This means that when the Java compiler needs to read in a specified class file, it knows exactly where to find it and does not need a special directive to tell it where to look. Furthermore, Java does not make the distinction between declaring a variable or procedure and defining it that C does. This means that there is no need for C-style header files or function prototypes--a single Java object file serves as the interface definition and implementation for a class. Java does have an import statement, which is superficially similar to the C preprocessor #include directive. What this statement does, however, is tell the compiler that the current file is using the specified classes, or classes from the specified package, and allows us to refer to those classes with abbreviated names. For example, since the compiler implicitly imports all the classes of the java.lang package, we can refer to the constant java.lang.Math.PI by the shorter name Math.PI.
Conditional Compilation Java does not have any form of the C #ifdef or #if directives to perform conditional compilation. In theory, conditional compilation is not necessary in Java since it is a platform-independent language, and thus there are no platform dependencies that require the technique. In practice, however, conditional compilation is still often useful in Java--to provide slightly different user interfaces on different platforms, for example, or to support optional inclusion of debugging code in programs. While Java does not define explicit constructs for conditional compilation, a good Java compiler (such as Sun's javac) performs conditional compilation implicitly--that is, it does not compile code if it can prove that the code will never be executed. Generally, this means that code within an if statement testing an expression that is always false is not included. Thus, placing code within an if (false) block is equivalent to surrounding it with #if 0 and #endif in C. Conditional compilation also works with constants, which, as we saw above, are static final variables. A class might define the constant like this: private static final boolean DEBUG = false; With such a constant defined, any code within an if (DEBUG) block is not actually compiled into the class file. To activate debugging for the class, it is only necessary to change the value of the constant to true and recompile the class.
Comments
http://localhost/java/javaref/javanut/ch02_04.htm (2 of 2) [20/12/2001 10:59:50]
Unicode and Character Escapes
[Chapter 18] 18.9 java.awt.CardLayout (JDK 1.0)
Chapter 18 The java.awt Package
18.9 java.awt.CardLayout (JDK 1.0) This class is a LayoutManager that makes each of the components it manages as large as the container and ensures that only one is visible at a time. The standard LayoutManager methods are called by the Container object, and should not be called directly by applet or application code. first(), last(), next(), previous(), and show() make a particular Component in the Container visible. The names with which the components are added to the container are used only by the show() method. public class CardLayout extends Object implements LayoutManager2, Serializable { // Public Constructors public CardLayout(); public CardLayout(int hgap, int vgap); // Public Instance Methods 1.1 public void addLayoutComponent(Component comp, Object constraints); // From LayoutManager2 # public void addLayoutComponent(String name, Component comp); // From LayoutManager public void first(Container parent); 1.1 public int getHgap(); 1.1 public float getLayoutAlignmentX(Container parent); // From LayoutManager2 1.1 public float getLayoutAlignmentY(Container parent); // From LayoutManager2 1.1 public int getVgap(); 1.1 public void invalidateLayout(Container target); // From LayoutManager2 public void last(Container parent); public void layoutContainer(Container parent); // From LayoutManager 1.1 public Dimension maximumLayoutSize(Container target); // From LayoutManager2 public Dimension minimumLayoutSize(Container parent); // From LayoutManager public void next(Container parent); public Dimension preferredLayoutSize(Container parent); // From LayoutManager public void previous(Container parent); public void removeLayoutComponent(Component comp); // From LayoutManager 1.1 public void setHgap(int hgap); 1.1 public void setVgap(int vgap); public void show(Container parent, String name); public String toString(); // Overrides Object }
http://localhost/java/javaref/javanut/ch18_09.htm (1 of 2) [20/12/2001 10:59:50]
[Chapter 18] 18.9 java.awt.CardLayout (JDK 1.0)
Hierarchy: Object->CardLayout(LayoutManager2(LayoutManager), Serializable)
java.awt.Canvas (JDK 1.0)
java.awt.Checkbox (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_09.htm (2 of 2) [20/12/2001 10:59:50]
[Chapter 3] 3.6 Subclasses and Inheritance
Chapter 3 Classes and Objects in Java
3.6 Subclasses and Inheritance The Circle class we've defined is good for abstract mathematical manipulation. For some applications this is exactly what we need. For other applications, we want to be able to manipulate circles and draw them on the screen. This means we need a new class, GraphicCircle, that has all the functionality of Circle, but also has the ability to be drawn. We want to implement GraphicCircle so that it can make use of the code we've already written for Circle. One way to do that is the following: public class GraphicCircle { // Here is the mathematical circle. public Circle c; // Here are the old methods. public double area() { return c.area(); } public double circumference() { return c.circumference(); } // The new graphic variables and methods go here. public Color outline, fill; public void draw(DrawWindow dw) { /* code omitted */ } } This approach would work, but it is not particularly elegant. The problem is that we have to write stubs for methods like area() and circumference() that have nothing to do with drawing circles. It would be nice if we didn't have to do this.
Extending a Class In fact, we don't have to do it this way. Java allows us to define GraphicCircle as an extension, or subclass of Circle. Example 3.10 shows how. Note that this example assumes we have two other classes of objects defined: Color, which represents a color, and DrawWindow, a class that has the window into which drawing is done and that defines the primitive methods to do the drawing. Example 3.10: Subclassing a Class public class GraphicCircle extends Circle { // We automatically inherit the variables and methods of // Circle, so we only have to put the new stuff here. // We've omitted the GraphicCircle constructor, for now. Color outline, fill;
http://localhost/java/javaref/javanut/ch03_06.htm (1 of 6) [20/12/2001 10:59:51]
[Chapter 3] 3.6 Subclasses and Inheritance
public void draw(DrawWindow dw) { dw.drawCircle(x, y, r, outline, fill); } } The extends keyword tells Java that GraphicCircle is a subclass of Circle, and that it inherits the fields and methods of that class. [7] The definition of the draw() method shows variable inheritance--this method uses the Circle variables x, y, and r as if they were defined right in GraphicCircle itself. [7] Except for private fields and methods. We'll discuss private members of a class later. C++ programmers should note that extends is the Java equivalent of the : operator in C++--both indicate the superclass of a class. GraphicCircle also inherits the methods of Circle. Thus, if we have a GraphicCircle object referred to by variable gc, we can say: double area = gc.area(); This works just as if the area() method were defined in GraphicCircle itself. Another feature of subclassing is that every GraphicCircle object is also a perfectly legal Circle object. Thus, if gc refers to a GraphicCircle object, we can assign it to a Circle variable, and we can forget all about its extra graphic capabilities: Circle c = gc;.
Final Classes When a class is declared with the final modifier, it means that it cannot be extended or subclassed. java.lang.System is an example of a final class. Declaring a class final prevents unwanted extensions to the class. But it also allows the compiler to make some optimizations when invoking the methods of a class. We'll explore this in more detail when we talk about method overriding later in this chapter.
Superclasses, Object, and the Class Hierarchy In our example, GraphicCircle is a subclass of Circle. We can also say that Circle is the superclass of GraphicCircle. The superclass of a class is specified in its extends clause: public class GraphicCircle extends Circle { ... } Every class you define has a superclass. If you do not specify the superclass with an extends clause, the superclass is the class Object. Object is a special class for a couple of reasons: ● It is the only class that does not have a superclass. ● The methods defined by Object can be called by any Java object. Because every class has a superclass, classes in Java form a class hierarchy, which can be represented as a tree with Object at its root. Figure 3.1 shows a class hierarchy diagram which includes our Circle and GraphicCircle classes, as well as some of the standard classes from the Java API. Figure 3.1: A class hierarchy diagram
http://localhost/java/javaref/javanut/ch03_06.htm (2 of 6) [20/12/2001 10:59:51]
[Chapter 3] 3.6 Subclasses and Inheritance
The complete class hierarchy for the Java API is diagrammed in the figures of Part V, API Quick Reference.
Subclass Constructors In Example 3.10 we left out the constructor method for our new GraphicCircle class. Let's implement that now. Here's one way: public GraphicCircle(double x, double y, double r, Color outline, Color fill) { this.x = x; this.y = y; this.r = r; this.outline = outline; this.fill = fill; } This constructor relies on the fact that GraphicCircle inherits all the variables of Circle and simply initializes those variables itself. But this duplicates the code of the Circle constructor, and if Circle did more elaborate initialization, it could become quite wasteful. Furthermore, if the Circle class had internal private fields (discussed later), we wouldn't be able to initialize them like this. What we need is a way of calling a Circle constructor from within our GraphicCircle constructor. Example 3.11 shows how we can do this. Example 3.11: Invoking a Superclass's Constructor public GraphicCircle(double x, double y, double r, Color outline, Color fill) { super(x, y, r); this.outline = outline; this.fill = fill; } super is a reserved word in Java. One of its uses is that shown in the example--to invoke the constructor method of a superclass. Its use is analogous to the use of the this keyword to invoke one constructor method of a class from
http://localhost/java/javaref/javanut/ch03_06.htm (3 of 6) [20/12/2001 10:59:51]
[Chapter 3] 3.6 Subclasses and Inheritance
within another. Using super to invoke a constructor is subject to the same restrictions as using this to invoke a constructor: ● super may only be used in this way within a constructor method. ● The call to the superclass constructor must appear as the first statement within the constructor method. It must appear even before variable declarations.
Constructor Chaining When you define a class, Java guarantees that the class's constructor method is called whenever an instance of that class is created. It also guarantees that the constructor is called when an instance of any subclass is created. In order to guarantee this second point, Java must ensure that every constructor method calls its superclass constructor method. If the first statement in a constructor is not an explicit call to a constructor of the superclass with the super keyword, then Java implicitly inserts the call super()--that is, it calls the superclass constructor with no arguments. If the superclass does not have a constructor that takes no arguments, this causes a compilation error. There is one exception to the rule that Java invokes super() implicitly if you do not do so explicitly. If the first line of a constructor, C1, uses the this() syntax to invoke another constructor, C2, of the class, Java relies on C2 to invoke the superclass constructor, and does not insert a call to super() into C1. Of course, if C2 itself uses this() to invoke a third constructor, C2 does not call super() either, but somewhere along the chain, a constructor either explicitly or implicitly invokes the superclass constructor, which is what is required. Consider what happens when we create a new instance of the GraphicCircle class. First, the GraphicCircle constructor shown in Example 3.11 is invoked. This constructor explicitly invokes a Circle constructor and that Circle constructor implicitly calls super() to invoke the constructor of its superclass, Object. The body of the Object constructor runs first, followed by the body of the Circle constructor, and finally followed by the body of the GraphicCircle constructor. What this all means is that constructor calls are "chained"--any time an object is created, a sequence of constructor methods are invoked, from subclass to superclass on up to Object at the root of the class hierarchy. Because a superclass constructor is always invoked as the first statement of its subclass constructor, the body of the Object constructor always runs first, followed by the body of its subclass, and on down the class hierarchy to the class that is being instantiated.
The Default Constructor There is one missing piece in the description of constructor chaining above. If a constructor does not invoke a superclass constructor, Java does so implicitly. But what if a class is declared without any constructor at all? In this case, Java implicitly adds a constructor to the class. This default constructor does nothing but invoke the superclass constructor. For example, if we did not declare a constructor for the GraphicCircle class, Java would have implicitly inserted this constructor: public GraphicCircle() { super(); } Note that if the superclass, Circle(), did not declare a no-argument constructor, then this automatically inserted default constructor would cause a compilation error. If a class does not define a no-argument constructor, then all of its subclasses must define constructors that explicitly invoke the superclass constructor with the necessary arguments. It can be confusing when Java implicitly calls a constructor or inserts a constructor definition into a class--something is happening that does not appear in your code! Therefore, it is good coding style, whenever you rely on an implicit http://localhost/java/javaref/javanut/ch03_06.htm (4 of 6) [20/12/2001 10:59:51]
[Chapter 3] 3.6 Subclasses and Inheritance
superclass constructor call or on a default constructor, to insert a comment noting this fact. Your comments might look like those in the following example: class A { int i; public A() { // Implicit call to super(); here. i = 3; } } class B extends A { // Default constructor: public B() { super(); } } If a class does not declare any constructor, it is given a publicly constructor by default. Classes that do not want to be publically instantiated, should declare a protected constructor to prevent the insertion of this public constructor. Classes that never want to be instantiated at all should define a private constructor.
Finalizer Chaining? You might assume that since Java chains constructor methods that it also automatically chains the finalizer methods for an object. In other words, you may think that the finalizer method of a class automatically invokes the finalizer of its superclass. In fact, Java does not do this. In practice, finalizer methods are relatively rare, and the need for finalizer chaining rarely arises. If a class B with a finalizer method is a subclass of a class A with its own finalizer method, then B's finalizer should be sure to invoke A's finalizer, explicitly creating a chain of finalizers. This is a little tricky, since finalizers always have the same name (finalize()), and we haven't yet learned how to invoke a method in the superclass when that method is also defined in the subclass. We'll return to the issue of finalizer chaining when we learn how.
Shadowed Variables Suppose that our GraphicCircle class has a new variable that specifies the resolution, in dots per inch, of the DrawWindow object in which it is going to be drawn. And further, suppose that it names that new variable r: public class GraphicCircle extends Circle { Color outline, fill; float r; // New variable. Resolution in dots-per-inch. public GraphicCircle(double x, double y, double rad, Color o, Color f) { super(x, y, rad); outline = o; fill = f; } public void setResolution(float resolution) { r = resolution; } public void draw(DrawWindow dw) { dw.drawCircle(x, y, r, outline, fill); } } Now, with this resolution variable declared, when we use the variable r in the GraphicCircle class, we are no longer referring to the radius of the circle. The resolution variable r in GraphicCircle shadows the radius variable r in Circle. [8] [8] This is a contrived example, of course--we could simply rename the variable and avoid the issue. Typically we would rename the variable: variable shadowing is a necessary part of Java syntax, but is not a useful programming technique. Your code will be easier to understand if you avoid shadowed http://localhost/java/javaref/javanut/ch03_06.htm (5 of 6) [20/12/2001 10:59:51]
[Chapter 3] 3.6 Subclasses and Inheritance
variables. So, how can we refer to the radius variable defined in the Circle class when we need it? Recall that using a variable, such as r, in the class in which it is defined is shorthand for: this.r
// Refers to the GraphicCircle resolution variable.
As you might guess, you can refer to a variable r defined in the superclass like this: super.r
// Refers to the Circle radius variable.
Another way you can do this is to cast this to the appropriate class and then access the variable: ((Circle) this).r This cast is exactly what the super keyword does when used like this. You can use this casting technique when you need to refer to a shadowed variable defined in a class that is not the immediate superclass. For example, if C is a subclass of B, which is a subclass of A, and class C shadows a variable x that is also defined in classes A and B, then you can refer to these different variables from class C as follows: x this.x super.x ((B)this).x ((A)this).x super.super.x
// // // // // //
Variable Variable Variable Variable Variable Illegal;
x in x in x in x in x in does
class C. class C. class B. class B. class A. not refer to x in class A.
Note that you cannot refer to a shadowed variable x in the superclass of a superclass with super.super.x. Java does not recognize this syntax.
Shadowed Methods? Just as a variable defined in one class can shadow a variable with the same name in a superclass, you might expect that a method in one class could shadow a method with the same name (and same arguments) in a superclass. In a sense, they do: "shadowed" methods are called overridden methods. But method overriding is significantly different than variable shadowing; it is discussed in the sections that follow.
Object Destruction
http://localhost/java/javaref/javanut/ch03_06.htm (6 of 6) [20/12/2001 10:59:51]
Overriding Methods
[Chapter 2] 2.13 Exceptions and Exception Handling
Chapter 2 How Java Differs from C
2.13 Exceptions and Exception Handling Exception handing is a significant new feature of Java. [6] There are a number of new terms associated with exception handling. First, an exception is a signal that indicates that some sort of exceptional condition (such as an error) has occurred. To throw an exception is to signal an exceptional condition. To catch an exception is to handle it--to take whatever actions are necessary to recover from it. [6] It is similar to, but not quite the same as, exception handling in C++. Exceptions propagate up through the lexical block structure of a Java method, and then up the method call stack. If an exception is not caught by the block of code that throws it, it propagates to the next higher enclosing block of code. If it is not caught there, it propagates up again. If it is not caught anywhere in the method, it propagates to the invoking method, where it again propagates through the block structure. If an exception is never caught, it propagates all the way to the main() method from which the program started, and causes the Java interpreter to print an error message and a stack trace and exit. As we'll see in the subsections below, exceptions make error handling (and "exceptional condition" handling) more regular and logical by allowing you to group all your exception handling code into one place. Instead of worrying about all of the things that can go wrong with each line of your code, you can concentrate on the algorithm at hand and place all your error handling code (that is, your exception catching code) in a single place.
Exception Objects An exception in Java is an object that is an instance of some subclass of java.lang.Throwable. Throwable has two standard subclasses: java.lang.Error and java.lang.Exception. [7] Exceptions that are subclasses of Error generally indicate linkage problems related to dynamic loading, or virtual machine problems such as running out of memory. They should almost always be considered unrecoverable, and should not be caught. While the distinction is not always clear, exceptions that are subclasses of Exception indicate conditions that may be caught and recovered from. They include such exceptions as java.io.EOFException, which signals the end of a file, and java.lang.ArrayAccessOutOfBounds, which indicates that a program has tried to read past the end of an array. [7] We'll use the term "exception" to refer to any subclass of Throwable, whether it is actually an Exception or an Error. Since exceptions are objects, they can contain data and define methods. The Throwable object, at the top of the exception class hierarchy, includes a String message in its definition and this field is inherited by all
http://localhost/java/javaref/javanut/ch02_13.htm (1 of 7) [20/12/2001 10:59:52]
[Chapter 2] 2.13 Exceptions and Exception Handling
exception classes. This field is used to store a human-readable error message that describes the exceptional condition. It is set when the exception object is created by passing an argument to the constructor method. The message can be read from the exception with the Throwable.getMessage() method. Most exceptions contain only this single message, but a few add other data. The java.io.InterruptedIOException, for example, adds the following field: public int bytesTransferred; This field specifies how much of the I/O was complete before the exceptional condition occurred.
Exception Handling The try/catch/finally statement is Java's exception handling mechanism. try establishes a block of code that is to have its exceptions and abnormal exits (through break, continue, return, or exception propagation) handled. The try block is followed by zero or more catch clauses that catch and handle specified types of exceptions. The catch clauses are optionally followed by a finally block that contains "clean-up" code. The statements of a finally block are guaranteed to be executed, regardless of how the code in the try block exits. A detailed example of the try/catch/finally syntax is shown in Example 2.2. Example 2.2: The try/catch/finally Statement try { // Normally this code runs from the top of the block to the bottom // without problems. But it sometimes may raise exceptions or // exit the block via a break, continue, or return statement. } catch (SomeException e1) { // Handle an exception object e1 of type SomeException // or of a subclass of that type. } catch (AnotherException e2) { // Handle an exception object e2 of type AnotherException // or of a subclass of that type. } finally { // Always execute this code, after we leave the try clause, // regardless of whether we leave it: // 1) Normally, after reaching the bottom of the block. // 2) With an exception that is handled by a catch. // 3) With an exception that is not handled. // 4) Because of a break, continue, or return statement. }
try The try clause simply establishes a block of code that is to have its exceptions and abnormal exits (through break, continue, return, or exception propagation) handled. The try clause by itself doesn't do anything interesting; it is the catch and finally clauses that do the exception handling and clean-up http://localhost/java/javaref/javanut/ch02_13.htm (2 of 7) [20/12/2001 10:59:52]
[Chapter 2] 2.13 Exceptions and Exception Handling
operations.
catch A try block may be followed by zero or more catch clauses that specify code to handle various types of exceptions. catch clauses have an unusual syntax: each is declared with an argument, much like a method argument. This argument must be of type Throwable or a subclass. When an exception occurs, the first catch clause that has an argument of the appropriate type is invoked. The type of the argument must match the type of the exception object, or it must be a superclass of the exception. This catch argument is valid only within the catch block, and refers to the actual exception object that was thrown. The code within a catch block should take whatever action is necessary to cope with the exceptional condition. If the exception was a java.io.FileNotFoundException exception, for example, you might handle it by asking the user to check his or her spelling and try again. Note that it is not required to have a catch clause for every possible exception--in some cases the correct response is to allow the exception to propagate up and be caught by the invoking method. In other cases, such as a programming error signaled by NullPointerException, the correct response is to not catch the exception at all, but to allow it to propagate and to have the Java interpreter exit with a stack trace and an error message.
finally The finally clause is generally used to clean up (close files, release resources, etc.) after the try clause. What is useful about the finally clause is that the code in a finally block is guaranteed to be executed, if any portion of the try block is executed, regardless of how the code in the try block completes. In the normal case, control reaches the end of the try block and then proceeds to the finally block, which performs any necessary cleanup. If control leaves the try block because of a return, continue, or break statement, the contents of the finally block are executed before control transfers to its new destination. If an exception occurs in the try block and there is a local catch block to handle the exception, control transfers first to the catch block, and then to the finally block. If there is not a local catch block to handle the exception, control transfers first to the finally block, and then propagates up to the nearest catch clause that can handle the exception. Note that if a finally block itself transfers control with a return, continue, or break statement, or by raising an exception, the pending control transfer is abandoned, and this new transfer is processed. Also note that try and finally can be used together without exceptions or any catch clauses. In this case, the finally block is simply cleanup code that is guaranteed to be executed regardless of any break, continue, or return statements within the try clause.
Declaring Exceptions Java requires that any method that can cause a "normal exception" to occur must either catch the exception or specify the type of the exception with a throws clause in the method declaration. [8] Such a throws clause might look like these: [8] C++ programmers should note that Java uses throws where C++ uses throw.
http://localhost/java/javaref/javanut/ch02_13.htm (3 of 7) [20/12/2001 10:59:52]
[Chapter 2] 2.13 Exceptions and Exception Handling
public void open_file() throws IOException { // Statements here that might generate an uncaught java.io.IOException } public void myfunc(int arg) throws MyException1, MyException2 { ... } Note that the exception class specified in a throws clause may be a superclass of the exception type that is actually thrown. Thus if a method throws exceptions a, b, and c, all of which are subclasses of d, the throws clause may specify all of a, b, and c, or it may simply specify d. We said above that the throws clause must be used to declare any "normal exceptions." This oxymoronic phrase refers to any subclass of Throwable that is not a subclass of Error or a subclass of RuntimeException. Java does not require these types of exceptions to be declared because practically any method can conceivably generate them, and it would quickly become tedious to properly declare them all. For example, every method running on a buggy Java interpreter can throw an InternalError exception (a subclass of Error) and it doesn't make sense to have to declare this in a throws clause for every method. Similarly, as far as the Java compiler is concerned, any method that accesses an array can generate an ArrayIndexOutOfBoundsException exception (a subclass of RuntimeException). The standard exceptions that you often have to declare are java.io.IOException and a number of its more specific subclasses. java.lang.InterruptedException and several other less commonly used exceptions must also be declared. How do you know when you have to declare a throws clause? One way is to pay close attention to the documentation for the methods you call--if any "normal exceptions" can be thrown, either catch them or declare them. Another way to know what exceptions you've got to declare is to declare none and wait for the compilation errors--the compiler will tell you what to put in your throws clause!
Defining and Generating Exceptions You can signal your own exceptions with the throw statement. The throw keyword must be followed by an object that is Throwable or a subclass. Often, exception objects are allocated in the same statement that they are thrown in: throw new MyException("my exceptional condition occurred."); When an exception is thrown, normal program execution stops and the interpreter looks for a catch clause that can handle the exception. Execution propagates up through enclosing statements and through invoking functions until such a handler is found. Any finally blocks that are passed during this propagation are executed. Using exceptions is a good way to signal and handle errors in your own code. By grouping all your error handling and recover code together within the try/catch/finally structure, you will end up with cleaner code that is easier to understand. Sometimes, when you are throwing an exception, you can use one of the exception classes already defined by Java API. Often, though, you will want to define and throw your own exception types. Example 2.3 shows how you can define your own exception types, throw them, and handle them. It also helps clarify how exceptions propagate. It is a long example, but worth studying in some detail. You'll know you understand exception handling if you can answer the following: What happens when this program is invoked with no argument; with a string argument; and with integer arguments 0, 1, 2, and 99?
http://localhost/java/javaref/javanut/ch02_13.htm (4 of 7) [20/12/2001 10:59:52]
[Chapter 2] 2.13 Exceptions and Exception Handling
Example 2.3: Defining, Throwing, and Handling Exceptions // Here we define some exception types of our own. // Exception classes generally have constructors but no data or // other methods. All these do is call their superclass constructors. class MyException extends Exception { public MyException() { super(); } public MyException(String s) { super(s); } } class MyOtherException extends Exception { public MyOtherException() { super(); } public MyOtherException(String s) { super(s); } } class MySubException extends MyException { public MySubException() { super(); } public MySubException(String s) { super(s); } } public class throwtest { // This is the main() method. Note that it uses two // catch clauses to handle two standard Java exceptions. public static void main(String argv[]) { int i; // First, convert our argument to an integer. // Make sure we have an argument and that it is convertible. try { i = Integer.parseInt(argv[0]); } catch (ArrayIndexOutOfBoundsException e) { // argv is empty System.out.println("Must specify an argument"); return; } catch (NumberFormatException e) { // argv[0] isn't an integer System.out.println("Must specify an integer argument"); return; } // Now, pass that integer to method a(). a(i); } // This method invokes b(), which is declared to throw // one type of exception. We handle that one exception. public static void a(int i) { try { b(i); } catch (MyException e) { // Point 1 // Here we handle MyException and its subclass MySubException.
http://localhost/java/javaref/javanut/ch02_13.htm (5 of 7) [20/12/2001 10:59:52]
[Chapter 2] 2.13 Exceptions and Exception Handling
if (e instanceof MySubException) System.out.print("MySubException: "); else System.out.print("MyException: "); System.out.println(e.getMessage()); System.out.println("Handled at point 1"); } } // This method invokes c(), and handles one of the two exception // types that that method can throw. The other exception type is // not handled, and is propagated up and declared in this method's // throws clause. This method also has a finally clause to finish // up the work of its try clause. Note that the finally clause is // executed after a local catch clause, but before a containing // catch clause or one in an invoking procedure. public static void b(int i) throws MyException { int result; try { System.out.print("i = " + i); result = c(i); System.out.print(" c(i) = " + result); } catch (MyOtherException e) { // Point 2 // Handle MyOtherException exceptions: System.out.println("MyOtherException: " + e.getMessage()); System.out.println("Handled at point 2"); } finally { // Terminate the output we printed above with a newline. System.out.print("\n"); } } // This method computes a value or throws an exception. // The throws clause only lists two exceptions, because // one of the exceptions thrown is a subclass of another. public static int c(int i) throws MyException, MyOtherException { switch (i) { case 0: // processing resumes at point 1 above throw new MyException("input too low"); case 1: // processing resumes at point 1 above throw new MySubException("input still too low"); case 99: // processing resumes at point 2 above throw new MyOtherException("input too high"); default: return i*i; }
http://localhost/java/javaref/javanut/ch02_13.htm (6 of 7) [20/12/2001 10:59:52]
[Chapter 2] 2.13 Exceptions and Exception Handling
} }
Statements
http://localhost/java/javaref/javanut/ch02_13.htm (7 of 7) [20/12/2001 10:59:52]
Miscellaneous Differences
[Chapter 3] 3.7 Overriding Methods
Chapter 3 Classes and Objects in Java
3.7 Overriding Methods When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, not the superclass' old definition. Method overriding is an important and useful technique in object-oriented programming. Suppose we define a subclass Ellipse of our Circle class. [9] Then it would be important for Ellipse to override the area() and circumference() methods of Circle. Ellipse would have to implement new versions of these functions because the formulas that apply to circles don't work for ellipses. [9] This is admittedly a strange thing to do, since, mathematically, a circle is a kind of ellipse, and it is customary to derive a more specific class from a more general one. Nevertheless, it is a useful example here. Before we go any further with the discussion of method overriding, be sure that you understand the difference between method overriding and method overloading, which we discussed earlier. As you probably recall, method overloading refers to the practice of defining multiple methods (in the same class) with the same name but with differing argument lists. This is very different from method overriding, and it is important not to get them confused!
Overriding Is Not Shadowing Although Java treats the variables and methods of a class analogously in many ways, method overriding is not like variable shadowing at all: You can refer to shadowed variables simply by casting an object to the appropriate type. You cannot invoke overridden methods with this technique, however. Example 3.12 illustrates this crucial difference. Example 3.12: Method Overriding versus Variable Shadowing class A int int } class B int
{ i = 1; f() { return i; } extends A { i = 2;
http://localhost/java/javaref/javanut/ch03_07.htm (1 of 4) [20/12/2001 10:59:52]
// Shadows variable i in class A.
[Chapter 3] 3.7 Overriding Methods
int f() { return -i; } // Overrides method f in class A. } public class override_test { public static void main(String args[]) { B b = new B(); System.out.println(b.i); // Refers to B.i; prints 2. System.out.println(b.f()); // Refers to B.f(); prints -2. A a = (A) b; // Cast b to an instance of class A. System.out.println(a.i); // Now refers to A.i; prints 1; System.out.println(a.f()); // Still refers to B.f(); prints -2; } } While this difference between method overriding and variable shadowing may seem surprising at first, a little thought makes the purpose clear. Suppose we have a bunch of Circle and Ellipse (a subclass of Circle) objects that we are manipulating. To keep track of the circles and ellipses, we store them in an array of type Circle[], casting all the Ellipse objects to Circle objects before we store them. Then, when we loop through the elements of this array, we don't have to know or care whether the element is actually a Circle or an Ellipse. What we do care very much about, however, is that the correct value is computed when we invoke the area() method of any element of the array. That is, we don't want to use the formula for the area of a circle when the object is actually an ellipse! Seen in this context, it is not surprising at all that method overriding is handled differently by Java than variable shadowing.
final Methods If a method is declared final, it means that the method declaration is the "final" one--that it cannot be overridden. static methods and private methods (which we haven't learned about yet) cannot be overridden either, nor can the methods of a final class. If a method cannot be overridden, the compiler may perform certain optimizations on it, as we'll see below.
Dynamic Method Lookup If we have an array of Circle and Ellipse objects, how does the compiler know to call the Circle area() method or the Ellipse area() method for any given item in the array? The compiler does not know this; it can't. The compiler knows that it does not know, however, and produces code that uses "dynamic method lookup" at run-time. When the interpreter runs the code, it looks up the appropriate area() method to call for each of the objects. That is, when the interpreter interprets the expression s.area(), it dynamically looks for an area() method associated with the particular object referred to by the variable s. It does not simply use the area() method that is statically associated with the type of the variable s. [10] [10] C++ programmers should note that dynamic method lookup is what C++ does for virtual functions. An important difference between Java and C++ is that Java does not have a virtual keyword; methods in Java are "virtual" by default. Dynamic method lookup is fast, but it is not as fast as invoking a method directly. Fortunately, there are a number of cases in which Java does not need to use dynamic method lookup. static methods cannot be http://localhost/java/javaref/javanut/ch03_07.htm (2 of 4) [20/12/2001 10:59:52]
[Chapter 3] 3.7 Overriding Methods
overridden, so they are always invoked directly. private methods (which we haven't learned about yet) are not inherited by subclasses and so cannot be overridden by subclasses; this means the Java compiler can safely invoke them without dynamic method lookup as well. final methods are invoked directly for the same reason: they cannot be overridden. Finally, when a method of a final class is invoked through an instance of the class or a subclass of it, then it, too, can be invoked without the overhead of dynamic lookup. These static, final, and private methods that can be invoked directly are also candidates for inlining--i.e., if the methods are short, the compiler may simply insert the method body into the code rather than inserting a call to the method.
Invoking an Overridden Method We've seen the important differences between method overriding and variable shadowing. Nevertheless, the Java syntax for invoking an overridden method is very similar to the syntax for accessing a shadowed variable: both use the super keyword. Example 3.13 illustrates this. Example 3.13: Invoking an Overridden Method class A int int } class B int int
{ i = 1; f() { return i; }
// A very simple method.
extends A { i; f() { i = super.i + 1; return super.f() + i;
// // // //
This variable shadows i in A. This method overrides f() in A. It retrieves A.i this way. And it invokes A.f() this way.
} } Recall that when you use super to refer to a shadowed variable, it is the same as casting this to the superclass type and accessing the variable through that. On the other hand, using super to invoke an overridden method is not the same as casting this. In this case, super has the special purpose of turning off dynamic method lookup and invoking the specific method that the superclass defines or inherits. In Example 3.13 we use super to invoke an overridden method that is actually defined in the immediate superclass. super also works perfectly well to invoke overridden methods that are defined further up the class hierarchy. This is because the overridden method is inherited by the immediate superclass, and so the super syntax does in fact refer to the correct method. To make this more concrete, suppose class A defines method f, and that B is a subclass of A, and that C is a subclass of B that overrides method f. Then you can still use: super.f() to invoke the overridden method from within class C. This is because class B inherits method f from class A. If classes A, B, and C all define method f, however, then calling super.f() in class C invokes class B's definition of the method. In this case, there is no way to invoke A.f() from within class C.
http://localhost/java/javaref/javanut/ch03_07.htm (3 of 4) [20/12/2001 10:59:52]
[Chapter 3] 3.7 Overriding Methods
super.super.f() is not legal Java syntax! It is important to note that super can only be used to invoke overridden methods from within the class that does the overriding. With our Circle and Ellipse classes, for example, there is no way to write a program (with or without super) that invokes the Circle area() method on an object of type Ellipse. The only way to do this is to use super in a method within the Ellipse class. Finally, note that this form of super does not have to occur in the first statement in a method, as it does when used to invoke a superclass constructor method.
Finalizer Chaining Revisited Now that we've discussed method overriding and how to invoke an overridden method, we can return to the issue of the finalizer method that we left dangling earlier on. In Java, constructor methods are automatically chained, but finalizer methods are not. If you define a finalize() method to free resources allocated by your class, you may be overriding a finalize() method in a superclass that frees resources allocated by that class. If your finalizer method does not invoke the superclass finalizer, the superclass finalizer never gets called, and resources are not deallocated when they should be. To prevent this, you should be sure to invoke the superclass finalize() method. The best time to do this is usually after your finalize() method has done all of its deallocation. It is a good idea to add the following call: super.finalize(); as the last line of all your finalizer methods. You should do this even if you know that none of your class's superclasses have finalizer methods, because future implementations of the class may include one.
Subclasses and Inheritance
http://localhost/java/javaref/javanut/ch03_07.htm (4 of 4) [20/12/2001 10:59:52]
Data Hiding and Encapsulation
[Chapter 11] 11.2 Unicode
Chapter 11 Internationalization
11.2 Unicode Java uses the Unicode character encoding. Java 1.0 used Unicode version 1.1, while Java 1.1 has adopted the newer Unicode 2.0 standard. Unicode is a 16-bit character encoding established by the Unicode Consortium, which describes the standard as follows (see http://unicode.org): The Unicode Worldwide Character Standard is a character coding system designed to support the interchange, processing, and display of the written texts of the diverse languages of the modern world. In addition, it supports classical and historical texts of many written languages. In its current version (2.0), the Unicode standard contains 38,885 distinct coded characters derived from 25 supported scripts. These characters cover the principal written languages of the Americas, Europe, the Middle East, Africa, India, Asia, and Pacifica. In the canonical form of the Unicode encoding, which is what Java char and String types use, every character occupies two bytes. The Unicode characters \u0020 to \u007E are equivalent to the ASCII and ISO8859-1 (Latin-1) characters 0x20 through 0x7E. The Unicode characters \u00A0 to \u00FF are identical to the ISO8859-1 characters 0xA0 to 0xFF. Thus there is a trivial mapping between Latin-1 and Unicode characters. A number of other portions of the Unicode encoding are based on pre-existing standards, such as ISO8859-5 (Cyrillic) and ISO8859-8 (Hebrew), though the mappings between these standards and Unicode may not be as trivial as the Latin-1 mapping. Note that Unicode support is quite limited on many platforms. One of the difficulties with the use of Unicode is the poor availability of fonts to display all of the Unicode characters. Figure 11.1 shows the characters that are available on a typical configuration of the U.S. English Windows 95 platform. Note the special box glyph used to indicate undefined characters. Figure 11.1: Some Unicode characters and their encodings
http://localhost/java/javaref/javanut/ch11_02.htm (1 of 6) [20/12/2001 10:59:53]
[Chapter 11] 11.2 Unicode
Unicode is similar to, but not the same as, ISO 10646, the UCS (Universal Character Set) encoding. UCS is a 2- or 4-byte encoding originally intended to contain all national standard character encodings. For example, it was to include the separate Chinese, Japanese, Korean, and Vietnamese encodings for Han ideographic characters. Unicode, in contrast, "unifies" these disparate encodings into a single set of Han characters that work for all four countries. Unicode has been so successful, however, that ISO 10646 has adopted it in place of non-unified encodings. Thus, ISO 10646 is effectively Unicode, with the option of two extra bytes for expansion purposes. Unicode is a trademark of the Unicode Consortium. Version 2.0 of the standard is defined by the book The Unicode Standard, Version 2.0 (published by Addison-Wesley, ISBN 0-201-48345-9). Further information about the Unicode standard and the Unicode Consortium can be obtained at http://unicode.org/. Table 11.1 provides an overview of the Unicode 2.0 encoding. http://localhost/java/javaref/javanut/ch11_02.htm (2 of 6) [20/12/2001 10:59:53]
[Chapter 11] 11.2 Unicode
Table 11.1: Outline of the Unicode 2.0 Encoding Start 0000 0000 0080 0100 0180 0250 02B0 0300 0370 0400
End 1FFF 007F 00FF 017F 024F 02AF 02FF 036F 03FF 04FF
Description Alphabets Basic Latin Latin-1 Supplement Latin Extended-A Latin Extended-B IPA Extensions Spacing Modifier Letters Combining Diacritical Marks Greek Cyrillic
0530 0590 0600 0900 0980 0A00 0A80 0B00 0B80 0C00 0C80 0D00 0E00 0E80 0F00 10A0 1100 1E00
058F 05FF 06FF 097F 09FF 0A7F 0AFF 0B7F 0BFF 0C7F 0CFF 0D7F 0E7F 0EFF 0FBF 10FF 11FF 1EFF
Armenian Hebrew Arabic Devanagari Bengali Gurmukhi Gujarati Oriya Tamil Telugu Kannada Malayalam Thai Lao Tibetan Georgian Hangul Jamo Latin Extended Additional
1F00 2000 2000 2070
1FFF 2FFF 206F 209F
Greek Extended Symbols and Punctuation General Punctuation Superscripts and Subscripts
http://localhost/java/javaref/javanut/ch11_02.htm (3 of 6) [20/12/2001 10:59:53]
[Chapter 11] 11.2 Unicode
20A0 20D0 2100 2150 2190 2200 2300 2400 2440 2460 2500 2580
20CF 20FF 214F 218F 21FF 22FF 23FF 243F 245F 24FF 257F 259F
Currency Symbols Combining Marks for Symbols Letterlike Symbols Number Forms Arrows Mathematical Operators Miscellaneous Technical Control Pictures Optical Character Recognition Enclosed Alphanumerics Box Drawing Block Elements
25A0 2600 2700 3000 3000 3040 30A0 3100 3130 3190 3200 3300
25FF 26FF 27BF 33FF 303F 309F 30FF 312F 318F 319F 32FF 33FF
AC00 D800 D800 DB80 DC00
D7A3 DFFF DB7F DBFF DFFF
Geometric Shapes Miscellaneous Symbols Dingbats CJK Auxiliary CJK Symbols and Punctuation Hiragana Katakana Bopomofo Hangul Compatibility Jamo Kanbun Enclosed CJK Letters and Months CJK Compatibility CJK Unified Ideographs Han characters used in China, Japan, Korea, Taiwan, and Vietnam Hangul Syllables Surrogates High Surrogates High Private Use Surrogates Low Surrogates
E000 F900 F900 FB00
F8FF FFFF FAFF FB4F
Private Use Miscellaneous CJK Compatibility Ideographs Alphabetic Presentation Forms
4E00 9FFF
http://localhost/java/javaref/javanut/ch11_02.htm (4 of 6) [20/12/2001 10:59:53]
[Chapter 11] 11.2 Unicode
FB50 FE20 FE30 FE50 FE70 FEFF FF00 FFF0
FDFF FE2F FE4F FE6F FEFE FEFF FFEF FFFF
Arabic Presentation Forms-A Combining Half Marks CJK Compatibility Forms Small Form Variants Arabic Presentation Forms-B Specials Halfwidth and Fullwidth Forms Specials
Unicode and Local Encodings While Java programs use Unicode text internally, Unicode is not the customary character encoding for most countries or locales. Thus, an important requirement for Java programs is to be able to convert text from the local encoding to Unicode as it is read (from a file or network, for example) and to be able to convert text from Unicode to the local encoding as it is written. In Java 1.0, this requirement is not well supported. In Java 1.1, however, the conversion can be done with the java.io.InputStreamReader and java.io.OutputStreamWriter classes, respectively. These classes load an appropriate ByteToCharConverter or CharToByteConverter class to perform the conversion. Note that these converter classes are part of the sun.io package and are not for public use (although an explicit conversion interface may be defined in a later release of Java).
The UTF-8 Encoding The canonical two-bytes per character encoding is useful for the manipulation of character data and is the internal representation used throughout Java. However, because a large amount of text used by Java programs is 8-bit text, and because there are so many existing computer systems that support only 8-bit characters, the 16-bit canonical form is usually not the most efficient way to store Unicode text nor the most portable way to transmit it. Because of this, other encodings called "transformation formats" have been developed. Java provides simple support for the UTF-8 encoding with the DataInputStream.readUTF() and DataOutputStream.writeUTF() methods. UTF-8 is a variable-width or "multi-byte" encoding format; this means that different characters require different numbers of bytes. In UTF-8, the standard ASCII characters occupy only one byte, and remain untouched by the encoding (i.e., a string of ASCII characters is a legal UTF-8 string). As a tradeoff, however, other Unicode characters occupy two or three bytes. In UTF-8, Unicode characters between \u0000 and \u007F occupy a single byte, which has a value of between 0x00 and 0x7F, and which always has its high-order bit set to 0. Characters between \u0080 and \u07FF occupy two bytes, and characters between \u0800 and \uFFFF occupy three bytes. The first byte of a two-byte character always has high-order bits 110, and the first byte of a three-byte character always has high-order bits 1110. Since single-byte characters always have 0 as their high-order bit, the one-, two-, and three-byte characters can easily be distinguished from each other.
http://localhost/java/javaref/javanut/ch11_02.htm (5 of 6) [20/12/2001 10:59:53]
[Chapter 11] 11.2 Unicode
The second and third bytes of two- and three-byte characters always have high-order bits 10, which distinguishes them from one-byte characters, and also distinguishes them from the first byte of a two- or three-byte sequence. This is important because it allows a program to locate the start of a character in a multi-byte sequence. The remaining bits in each character (i.e., the bits that are not part of one of the required high-order bit sequences) are used to encode the actual Unicode character data. In the single-byte form, there are seven bits available, suitable for encoding characters up to \u007F. In the two-byte form, there are 11 data bits available, which is enough to encode values to \u07FF, and in the three-byte form there are 16 available data bits, which is enough to encode all 16-bit Unicode characters. Table 11.2 summarizes the UTF-8 encoding. Table 11.2: The UTF-8 Encoding Start Character End Character Required Data Bits Binary Byte Sequence (x = data bits) \u0000 \u007F 7 0xxxxxxx \u0080 \u07FF 11 110xxxxx 10xxxxxx \u0800
\uFFFF
16
1110xxxx 10xxxxxx 10xxxxxx
The UTF-8 has the following desirable features: ● All ASCII characters are one-byte UTF-8 characters. A legal ASCII string is a legal UTF-8 string. ● Any non-ASCII character (i.e., any character with the high-order bit set) is part of a multi-byte character. ● The first byte of any UTF-8 character indicates the number of additional bytes in the character. ● The first byte of a multi-byte character is easily distinguished from the subsequent bytes. Thus, it is easy to locate the start of a character from an arbitrary position in a data stream. ● It is easy to convert between UTF-8 and Unicode. ● The UTF-8 encoding is relatively compact. For text with a large percentage of ASCII characters, it is more compact than Unicode. In the worst case, a UTF-8 string is only 50% larger than the corresponding Unicode string. Java actually uses a slightly modified form of UTF-8. The Unicode character \u0000 is encoded using a two-byte sequence, so that an encoded Unicode string never contains null characters.
A Word About Locales
http://localhost/java/javaref/javanut/ch11_02.htm (6 of 6) [20/12/2001 10:59:53]
Character Encodings
[Chapter 25] 25.7 java.lang.Character (JDK 1.0)
Chapter 25 The java.lang Package
25.7 java.lang.Character (JDK 1.0) This class provides an immutable object wrapper around the primitive char data type. charValue() returns the char value of a Character object. A number of class methods provide the Java/Unicode equivalent of the C character macros for checking the type of characters and converting to uppercase and lowercase letters. getType() returns the character type. The return value is one of the constants defined by the class, which represents a number of broad Unicode character categories. digit() returns the integer equivalent of a given character for a given radix (e.g., radix 16 for hexadecimal). forDigit() returns the character that corresponds to the specified value for the specified radix. public final class Character extends Object implements Serializable { // Public Constructor public Character(char value); // Constants public static final int MAX_RADIX, MIN_RADIX; public static final char MAX_VALUE, MIN_VALUE; 1.1public static final Class TYPE; // Character Type Constants 1.1public static final byte COMBINING_SPACING_MARK, CONNECTOR_PUNCTUATION, CONTROL; 1.1public static final byte CURRENCY_SYMBOL, DASH_PUNCTUATION, DECIMAL_DIGIT_NUMBER; 1.1public static final byte ENCLOSING_MARK, END_PUNCTUATION, FORMAT; 1.1public static final byte LETTER_NUMBER, LINE_SEPARATOR, LOWERCASE_LETTER; 1.1public static final byte MATH_SYMBOL, MODIFIER_LETTER, MODIFIER_SYMBOL; 1.1public static final byte NON_SPACING_MARK, OTHER_LETTER, OTHER_NUMBER; 1.1public static final byte OTHER_PUNCTUATION, OTHER_SYMBOL, PARAGRAPH_SEPARATOR; 1.1public static final byte PRIVATE_USE, SPACE_SEPARATOR, START_PUNCTUATION; 1.1public static final byte SURROGATE, TITLECASE_LETTER, UNASSIGNED; 1.1public static final byte UPPERCASE_LETTER; // Class Methods public static int digit(char ch, int radix); public static char forDigit(int digit, int radix); 1.1public static int getNumericValue(char ch); 1.1public static int getType(char ch); public static boolean isDefined(char ch); public static boolean isDigit(char ch); 1.1public static boolean isISOControl(char ch); 1.1public static boolean isIdentifierIgnorable(char ch); 1.1public static boolean isJavaIdentifierPart(char ch); 1.1public static boolean isJavaIdentifierStart(char ch);
http://localhost/java/javaref/javanut/ch25_07.htm (1 of 2) [20/12/2001 10:59:54]
[Chapter 25] 25.7 java.lang.Character (JDK 1.0)
# #
public static boolean isJavaLetter(char ch); public static boolean isJavaLetterOrDigit(char ch); public static boolean isLetter(char ch); public static boolean isLetterOrDigit(char ch); public static boolean isLowerCase(char ch); # public static boolean isSpace(char ch); 1.1public static boolean isSpaceChar(char ch); public static boolean isTitleCase(char ch); 1.1public static boolean isUnicodeIdentifierPart(char ch); 1.1public static boolean isUnicodeIdentifierStart(char ch); public static boolean isUpperCase(char ch); 1.1public static boolean isWhitespace(char ch); public static char toLowerCase(char ch); public static char toTitleCase(char ch); public static char toUpperCase(char ch); // Public Instance Methods public char charValue(); public boolean equals(Object obj); // Overrides Object public int hashCode(); // Overrides Object public String toString(); // Overrides Object }
java.lang.Byte (JDK 1.1)
java.lang.Class (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_07.htm (2 of 2) [20/12/2001 10:59:54]
[Chapter 4] 4.6 Internationalization
Chapter 4 What's New in Java 1.1
4.6 Internationalization Internationalization [1] is the process of enabling a program to run internationally. That is, an internationalized program has the flexibility to run correctly in any country. Once a program has been internationalized, enabling it to run in a particular country and/or language is merely a matter of "localizing" it for that country and language, or locale. [1] This word is sometimes abbreviated I18N, because there are 18 letters between the first I and the last N. You might think that the main task of localization is the matter of translating a program's user-visible text into a local language. While this is an important task, it is not by any means the only one. Other concerns include displaying dates and times in the customary format for the locale, displaying number and currency values in the customary format for the locale, and sorting strings in the customary order for the locale. Underlying all these localization issues is the even more fundamental issue of character encodings. Almost every useful program must perform input and output of text, and before we can even think about textual I/O, we must be able to work with the local character encoding standard. This hurdle to internationalization lurks slightly below the surface, and is not very "programmer-visible." Nevertheless, it is one of the most important and difficult issues in internationalization. As described in Chapter 11, Internationalization, Java 1.1 provides facilities that address all of these internationalization issues. If you write programs that correctly make use of these facilities, the task of localizing your program for a new country really does boil down to the relatively simple matter of hiring a translator to convert your program's messages. With the expansion of the global economy, and particularly of the global Internet, writing internationalized programs is going to become more and more important, and you should begin to take advantage of Java's internationalization capabilities right away. There are several distinct pieces to the problem of internationalization, and Java's solution to this problem also comes in distinct pieces. The first issue in internationalization is the matter of knowing what locale a program is running in. A locale is typically defined as a political, geographical, or cultural region that has a distinct language or distinct conventions for things such as date and time formats. The notion of a locale is encapsulated in Java 1.1 by the Locale class, which is part of the java.util package. Every Java program has a default locale, which is inherited from the operating system (where it may be set by the user). A program can simply rely on this default, or it can change the default.
http://localhost/java/javaref/javanut/ch04_06.htm (1 of 3) [20/12/2001 10:59:54]
[Chapter 4] 4.6 Internationalization
Additionally, all Java methods that rely on the default locale also have variants that allow you to explicitly specify a locale. Typically, though, using the default locale is exactly what you want to do. Once a program knows what locale it is running in, the most fundamental internationalization issue, as noted above, is the ability to read and write localized text. Since Java uses the Unicode encoding for its characters and strings, any character of any commonly-used modern written language is representable in a Java program, which puts Java at a huge advantage over older languages such as C and C++. Thus, working with localized text is merely a matter of converting from the local character encoding to Unicode when reading text, such as a file or input from the user, and converting from Unicode to the local encoding when writing text. Java's solution to this problem is in the java.io package, in the form of a new suite of character-based input and output streams (known as "readers" and "writers") that complement the existing byte-based input and output streams. The FileReader class, for example, is a character-based input stream used to read characters (which are not the same as bytes in all languages) from a file. The FileReader class assumes that the specified file is encoded using the default character encoding for the default locale, so it converts characters from the local encoding to Unicode characters as it reads them. In most cases, this assumption is a good one, so all you need to do to internationalize the character set handling of your program is to switch from a FileInputStream to a FileReader object, and make similar switches for text output as well. On the other hand, if you need to read a file that is encoded using some character set other than the default character set of the default locale, you can use a FileInputStream to read the bytes of the file, and then use an InputStreamReader to convert the stream of bytes to a stream of characters. When you create an InputStreamReader, you specify the name of the encoding in use, and it performs the appropriate conversion automatically. As you can see, internationalizing the character set of your programs is a simple matter of switching from byte I/O streams to character I/O streams. Internationalizing other aspects of your program requires a little more effort. The classes in the java.text package are designed to allow you to internationalize your handling of numbers, dates, times, string comparisons, and so on. NumberFormat is used to convert numbers, monetary amounts, and percentages to an appropriate textual format for a locale. Similarly, the DateFormat class, along with the Calendar and TimeZone classes from the java.util package, are used to display dates and times in a locale-specific way. The Collator class is used to compare strings according to the alphabetization rules of a given locale, and the BreakIterator class is used to locate word, line, and sentence boundaries. The final major problem of internationalization is making your program flexible enough to display messages (or any type of user-visible text, such as the labels on GUI buttons) to the user in an appropriate language for the current locale. Typically, this means that the program cannot use hard-coded messages and must instead read in a set of messages at run-time, based on the locale setting. Java provides an easy way to do this. You define your messages as key/value pairs in a ResourceBundle subclass. Then, you create a subclass of ResourceBundle for each language or locale your application supports, naming each class following a convention that includes the locale name. At run-time, you can use the ResourceBundle.getBundle() method to load the appropriate ResourceBundle class for the current locale. The ResourceBundle contains the messages your application uses, each associated with a key, that serves as the message name. Using this technique, your application can look up a locale-dependent message translation based on a locale-independent message name. Note that this technique is useful for things other than textual messages. It can be used to http://localhost/java/javaref/javanut/ch04_06.htm (2 of 3) [20/12/2001 10:59:54]
[Chapter 4] 4.6 Internationalization
internationalize icons, or any other locale-dependent object used by your application. There is one final twist to this problem of internationalizing messages. Often, we want to output messages such as, "Error at line 5 of file hello.java.", where parts of the message are static, and parts are dynamically generated at run-time (such as the line number and filename above). This is further complicated by the fact that when we translate such messages the values we substitute in at run-time may appear in a different order. For example, in some different English speaking locale, we might want to display the line above as: "hello.java: error at line 5". The MessageFormat class of the java.text package allows you to substitute dynamic values into static messages in a very flexible way and helps tremendously with this situation, particularly when used in conjunction with resource bundles.
Other AWT Improvements
http://localhost/java/javaref/javanut/ch04_06.htm (3 of 3) [20/12/2001 10:59:54]
Object Serialization
[Chapter 11] Internationalization
Chapter 11
11. Internationalization Contents: A Word About Locales Unicode Character Encodings Handling Local Customs Localizing User-Visible Messages Formatted Messages Internationalization is the process of making a program flexible enough to run correctly in any locale, as discussed in Chapter 4, What's New in Java 1.1. The required corollary to internationalization is localization--the process of arranging for a program to run in a specific locale. There are several distinct steps to the task of internationalization. Java 1.1 addresses these steps with several different mechanisms: ● A program must be able to read, write, and manipulate localized text. Java uses the Unicode character encoding, which by itself is a huge step towards internationalization. In addition, in Java 1.1 the InputStreamReader and OutputStreamWriter classes convert text from a locale-specific encoding to Unicode and from Unicode to a locale-specific encoding, respectively. ● A program must conform to local customs when displaying dates and times, formatting numbers, and sorting strings. Java addresses these issues with the classes in the new java.text package. ● A program must display all user-visible text in the local language. Translating the messages a program displays is always one of the main tasks in localizing a program. A more important task is writing the program so that all user-visible text is fetched at runtime, rather than hard-coded directly into the program. Java 1.1 facilitates this process with the ResourceBundle class and its subclasses in the java.util package. This chapter discusses all three of these aspects of internationalization.
http://localhost/java/javaref/javanut/ch11_01.htm (1 of 2) [20/12/2001 10:59:54]
[Chapter 11] Internationalization
11.1 A Word About Locales A locale represents a geographic, political, or cultural region. In Java 1.1, locales are represented by the java.util.Locale class. A locale is frequently defined by a language, which is represented by its standard lowercase two-letter code, such as en (English) or fr (French). Sometimes, however, language alone is not sufficient to uniquely specify a locale, and a country is added to the specification. A country is represented by an uppercase two-letter code. For example, the United States English locale (en_US) is distinct from the British English locale (en_GB), and the French spoken in Canada (fr_CA) is different from the French spoken in France (fr_FR). Occasionally, the scope of a locale is further narrowed with the addition of a system-dependent "variant" string. The Locale class maintains a static default locale, which can be set and queried with Locale.setDefault() and Locale.getDefault(). Locale-sensitive methods in Java 1.1 typically come in two forms. One uses the default locale and the other uses a Locale object that is explicitly specified as an argument. A program can create and use any number of non-default Locale objects, although it is more common simply to rely on the default locale, which is inherited from the underlying default locale on the native platform. Locale-sensitive classes in Java often provide a method to query the list of locales that they support. Finally, note that AWT components in Java 1.1 have a locale property, so it is possible for different components to use different locales. (Most components, however, are not locale-sensitive; they behave the same in any locale.)
Naming Patterns and Conventions
http://localhost/java/javaref/javanut/ch11_01.htm (2 of 2) [20/12/2001 10:59:54]
Unicode
[Chapter 11] 11.3 Character Encodings
Chapter 11 Internationalization
11.3 Character Encodings Text representation has traditionally been one of the most difficult problems of internationalization. Java 1.1, however, solves this problem quite elegantly and hides the difficult issues. Java uses Unicode internally, so it can represent essentially any character in any commonly used written language. As noted above, the remaining task is to convert Unicode to and from locale-specific encodings. Java 1.1 includes quite a few internal "byte-to-char" converters and "char-to-byte" converters that handle converting locale-specific character encodings to Unicode and vice versa. While the converters themselves are not public, they are accessed through the InputStreamReader and OutputStreamWriter classes, which are two of the new character streams included in the java.io package. Any program can automatically handle locale-specific encodings simply by using these new character stream classes to do their textual input and output. (And in addition to automatic encoding conversion, the program also benefits from the greatly improved efficiency of these new classes over the byte streams of Java 1.0.) Example 11.1 shows a simple program that works with character encodings. It converts a file from one specified encoding to another by converting from the first encoding to Unicode and then from Unicode to the second encoding. Note that most of the program is taken up with the mechanics of parsing argument lists, handling exceptions, and so on. Only a few lines are required to create the InputStreamReader and OutputStreamWriter classes that perform the two halves of the conversion. Also note that exceptions are handled by calling LocalizedError.display(). This method is not part of the Java 1.1 API; it is a custom method shown in Example 11.6 at the end of this chapter. Example 11.1: Working with Character Encodings import java.io.*; /** A program to convert from one character encoding to another. */ public class ConvertEncoding { public static void main(String[] args) { String from = null, to = null; String infile = null, outfile = null; for(int i = 0; i < args.length; i++) { // Parse command-line arguments. if (i == args.length-1) usage(); // All legal args require another. if (args[i].equals("-from")) from = args[++i]; else if (args[i].equals("-to")) to = args[++i]; else if (args[i].equals("-in")) infile = args[++i]; else if (args[i].equals("-out")) outfile = args[++i]; else usage(); } try { convert(infile, outfile, from, to); } // Attempt conversion. http://localhost/java/javaref/javanut/ch11_03.htm (1 of 2) [20/12/2001 10:59:55]
[Chapter 11] 11.3 Character Encodings
catch (Exception e) { LocalizedError.display(e); System.exit(1); }
// Handle possible exceptions. // Defined at the end of this chapter.
} public static void usage() { System.err.println("Usage: java ConvertEncoding \n" + "Options:\n\t-from <encoding>\n\t-to <encoding>\n\t" + "-in \n\t-out "); System.exit(1); } public static void convert(String infile, String outfile, String from, String to) throws IOException, UnsupportedEncodingException { // Set up byte streams. InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; // Use default encoding if no encoding is specified. if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = System.getProperty("file.encoding"); // Set up character streams. Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); // Copy characters from input to output. The InputStreamReader converts // from the input encoding to Unicode, and the OutputStreamWriter converts // from Unicode to the output encoding. Characters that cannot be // represented in the output encoding are output as '?' char[] buffer = new char[4096]; int len; while((len = r.read(buffer)) != -1) // Read a block of input. w.write(buffer, 0, len); // And write it out. r.close(); // Close the input. w.flush(); // Flush and close output. w.close(); } }
Unicode
http://localhost/java/javaref/javanut/ch11_03.htm (2 of 2) [20/12/2001 10:59:55]
Handling Local Customs
[Chapter 24] 24.66 java.io.UnsupportedEncodingException (JDK 1.1)
Chapter 24 The java.io Package
24.66 java.io.UnsupportedEncodingException (JDK 1.1) This exception signals that a requested character encoding is not supported by the current Java Virtual Machine. public class UnsupportedEncodingException extends IOException { // Public Constructors public UnsupportedEncodingException(); public UnsupportedEncodingException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->UnsupportedEncodingException
Thrown By: ByteArrayOutputStream.toString(), InputStreamReader(), OutputStreamWriter(), String(), String.getBytes()
java.io.SyncFailedException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_66.htm [20/12/2001 10:59:55]
java.io.UTFDataFormatException (JDK 1.0)
[Chapter 13] 13.2 Character Escape Sequences
Chapter 13 Java Syntax
13.2 Character Escape Sequences Java uses the escape sequences listed in Table 13.2 to represent certain special character values. These escape sequences may appear in any Java char or String literal. Table 13.2: Java Escape Characters Escape Sequence \b \t \n \f \r \" \' \\
Character Value Backspace Horizontal tab Newline Form feed Carriage return Double quote Single quote Backslash
\xxx
The character corresponding to the octal value xxx, where xxx is between 000 and 0377.
\uxxxx
The Unicode character with encoding xxxx, where xxxx is one to four hexidecimal digits. Unicode escapes are distinct from the other escape types listed here; they are described below in more detail.
Java characters, strings, and identifiers (e.g., field, method, and class names) are composed of 16-bit Unicode characters. The Unicode \u escape sequence may be used anywhere in a Java program (not only in char and String literals) to represent a Unicode character. Unicode \u escape sequences are processed before the other escape sequences described in Character Escape Sequences, and thus the two types of escape sequences can have very different semantics. A Unicode escape is simply an alternative way to represent a character which may not be displayable on non-Unicode systems. The character escapes, however, can represent special characters in a way that prevents the usual interpretation of those characters by the compiler.
http://localhost/java/javaref/javanut/ch13_02.htm (1 of 2) [20/12/2001 10:59:55]
[Chapter 13] 13.2 Character Escape Sequences
Primitive Data Types
http://localhost/java/javaref/javanut/ch13_02.htm (2 of 2) [20/12/2001 10:59:55]
Operators
[Chapter 29] 29.2 java.text.CharacterIterator (JDK 1.1)
Chapter 29 The java.text Package
29.2 java.text.CharacterIterator (JDK 1.1) This interface defines an API for portably iterating through the characters that comprise a string of text, regardless of the encoding of that text. Such an API is necessary because the number of bytes per character is different for different encodings, and some encodings even use variable-width characters within the same string of text. In addition to allowing iteration, a class that implements the CharacterIterator interface for non-Unicode text also performs translation of characters from their native encoding to standard Java Unicode characters. CharacterIterator is similar to java.util.Enumeration, but is somewhat more complex than that interface. The first() and last() methods return the first and last characters in the text, and the next() and prev() methods allow you to loop forward or backwards through the characters of the text. These methods return the DONE constant when they go beyond the first or last character in the text--a test for this constant can be used to terminate a loop. The CharacterIterator interface also allows random access to the characters in a string of text. The getBeginIndex() and getEndIndex() methods return the character positions for the start and end of the string, and setIndex() sets the current position. getIndex() returns the index of the current position, and current() returns the character at that position. public abstract interface CharacterIterator extends Cloneable { // Constants public static final char DONE; // Public Instance Methods public abstract Object clone(); // Overrides Object public abstract char current(); public abstract char first(); public abstract int getBeginIndex(); public abstract int getEndIndex(); public abstract int getIndex(); public abstract char last(); public abstract char next(); public abstract char previous(); public abstract char setIndex(int position); } http://localhost/java/javaref/javanut/ch29_02.htm (1 of 2) [20/12/2001 10:59:55]
[Chapter 29] 29.2 java.text.CharacterIterator (JDK 1.1)
Implemented By: StringCharacterIterator
Passed To: BreakIterator.setText()
Returned By: BreakIterator.getText()
java.text.BreakIterator (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_02.htm (2 of 2) [20/12/2001 10:59:55]
java.text.ChoiceFormat (JDK 1.1)
[Chapter 24] 24.7 java.io.CharArrayReader (JDK 1.1)
Chapter 24 The java.io Package
24.7 java.io.CharArrayReader (JDK 1.1) This class is a character input stream that uses a character array as the source of the characters it returns. You create a CharArrayReader by specifying the character array, or portion of an array, that it is to read from. CharArrayReader defines the usual Reader methods, and supports the mark() and reset() methods. Note that the character array you pass to the CharArrayReader is not copied by this class. This means that changes you make to the elements of the array after you create the input stream do affect the values read from the array. CharArrayReader() is the character-array analog of ByteArrayInputStream, and is similar to StringReader. public class CharArrayReader extends Reader { // Public Constructors public CharArrayReader(char[] buf); public CharArrayReader(char[] buf, int offset, int length); // Protected Instance Variables protected char[] buf; protected int count; protected int markedPos; protected int pos; // Public Instance Methods public void close(); // Defines Reader public void mark(int readAheadLimit) throws IOException; // Overrides Reader public boolean markSupported(); // Overrides Reader public int read() throws IOException; // Overrides Reader public int read(char[] b, int off, int len) throws IOException; // Defines Reader public boolean ready() throws IOException; // Overrides Reader public void reset() throws IOException; // Overrides Reader public long skip(long n) throws IOException; // Overrides Reader }
Hierarchy: Object->Reader->CharArrayReader
java.io.ByteArrayOutputStream (JDK 1.0)
java.io.CharArrayWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_07.htm (1 of 2) [20/12/2001 10:59:57]
[Chapter 24] 24.7 java.io.CharArrayReader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_07.htm (2 of 2) [20/12/2001 10:59:57]
[Chapter 24] 24.8 java.io.CharArrayWriter (JDK 1.1)
Chapter 24 The java.io Package
24.8 java.io.CharArrayWriter (JDK 1.1) This class is a character output stream that uses an internal character array as the destination of characters written to it. When you create a CharArrayWriter, you may optionally specify an initial size for the character array, but you do not specify the character array itself--this array is managed internally by the CharArrayWriter, and grows as necessary to accommodate all the characters written to it. The toString() and toCharArray() methods return a copy of all characters written to the stream, either as a string or as an array of characters. CharArrayWriter defines the standard write(), flush(), and close() methods that all Writer subclasses do. It also defines a few other useful methods. size() returns the number of characters that have been written to the stream. reset() resets the stream to its initial state, with an empty character array; this is more efficient than creating a new CharArrayWriter. Finally, writeTo() writes the contents of the internal character array to some other specified character stream. CharArrayWriter is the character-stream analog of ByteArrayOutputStream, and is quite similar to StringWriter. public class CharArrayWriter extends Writer { // Public Constructors public CharArrayWriter(); public CharArrayWriter(int initialSize); // Protected Instance Variables protected char[] buf; protected int count; // Public Instance Methods public void close(); // Defines Writer public void flush(); // Defines Writer public void reset(); public int size(); public char[] toCharArray(); public String toString(); // Overrides Object public void write(int c); // Overrides Writer public void write(char[] c, int off, int len); // Defines Writer public void write(String str, int off, int len); // Overrides Writer public void writeTo(Writer out) throws IOException; }
Hierarchy: Object->Writer->CharArrayWriter
http://localhost/java/javaref/javanut/ch24_08.htm (1 of 2) [20/12/2001 10:59:57]
[Chapter 24] 24.8 java.io.CharArrayWriter (JDK 1.1)
java.io.CharArrayReader (JDK 1.1)
java.io.CharConversionException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_08.htm (2 of 2) [20/12/2001 10:59:57]
[Chapter 25] 25.57 java.lang.String (JDK 1.0)
Chapter 25 The java.lang Package
25.57 java.lang.String (JDK 1.0) The String class represents a string of characters. A String object is created by the Java compiler whenever it encounters a string in doublequotes--this method of creation is usually simpler than using a constructor. A number of the methods of this class provide useful string manipulation functions. length() returns the number of characters in a string. charAt() extracts a character from a string. compareTo() compares two strings. equalsIgnoreCase() tests string for equality, ignoring case. startsWith() and endsWith() compare the start and end of a string to a specified value. indexOf() and lastIndexOf() search forward and backwards in a string for a specified character or substring. substring() returns a substring of a string. replace() creates a new copy of the string with one character replaced by another. toUpperCase() and toLowerCase() convert the case of a string. trim() strips whitespace from the start and end of a string. concat() concatenates two strings, which can also be done with the + operator. Note that String objects are immutable--there is no setCharAt() method to change the contents. The methods above that return a String do not modify the string they are passed, but instead return a modified copy of the string. Use a StringBuffer if you want to manipulate the contents of a string, or use toCharArray() to convert a string to an array of char values. The static valueOf() methods convert various Java primitive types to strings. public final class String extends Object implements Serializable { // Public Constructors public String(); public String(String value); public String(char[] value); public String(char[] value, int offset, int count); # public String(byte[] ascii, int hibyte, int offset, int count); # public String(byte[] ascii, int hibyte); 1.1public String(byte[] bytes, int offset, int length, String enc) throws UnsupportedEncodingException; 1.1public String(byte[] bytes, String enc) throws UnsupportedEncodingException; 1.1public String(byte[] bytes, int offset, int length); 1.1public String(byte[] bytes); public String(StringBuffer buffer); // Class Methods public static String copyValueOf(char[] data, int offset, int count); public static String copyValueOf(char[] data); public static String valueOf(Object obj); public static String valueOf(char[] data); public static String valueOf(char[] data, int offset, int count); public static String valueOf(boolean b); public static String valueOf(char c); public static String valueOf(int i); public static String valueOf(long l);
http://localhost/java/javaref/javanut/ch25_57.htm (1 of 3) [20/12/2001 10:59:58]
[Chapter 25] 25.57 java.lang.String (JDK 1.0)
public static String valueOf(float f); public static String valueOf(double d); // Public Instance Methods public char charAt(int index); public int compareTo(String anotherString); public String concat(String str); public boolean endsWith(String suffix); public boolean equals(Object anObject); // Overrides Object public boolean equalsIgnoreCase(String anotherString); # public void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin); 1.1public byte[] getBytes(String enc) throws UnsupportedEncodingException; 1.1public byte[] getBytes(); public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin); public int hashCode(); // Overrides Object public int indexOf(int ch); public int indexOf(int ch, int fromIndex); public int indexOf(String str); public int indexOf(String str, int fromIndex); public native String intern(); public int lastIndexOf(int ch); public int lastIndexOf(int ch, int fromIndex); public int lastIndexOf(String str); public int lastIndexOf(String str, int fromIndex); public int length(); public boolean regionMatches(int toffset, String other, int ooffset, int len); public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len); public String replace(char oldChar, char newChar); public boolean startsWith(String prefix, int toffset); public boolean startsWith(String prefix); public String substring(int beginIndex); public String substring(int beginIndex, int endIndex); public char[] toCharArray(); 1.1public String toLowerCase(Locale locale); public String toLowerCase(); public String toString(); // Overrides Object 1.1public String toUpperCase(Locale locale); public String toUpperCase(); public String trim(); }
Passed To: Many methods
Returned By: Many methods
Type Of: BorderLayout.CENTER, BorderLayout.EAST, BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.WEST, File.pathSeparator, File.separator, Font.name, HttpURLConnection.method, HttpURLConnection.responseMessage, InvalidClassException.classname, StreamTokenizer.sval, StringBufferInputStream.buffer http://localhost/java/javaref/javanut/ch25_57.htm (2 of 3) [20/12/2001 10:59:58]
[Chapter 25] 25.57 java.lang.String (JDK 1.0)
java.lang.StackOverflowError (JDK 1.0)
java.lang.StringBuffer (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_57.htm (3 of 3) [20/12/2001 10:59:58]
[Chapter 18] 18.10 java.awt.Checkbox (JDK 1.0)
Chapter 18 The java.awt Package
18.10 java.awt.Checkbox (JDK 1.0) This class represents a GUI checkbox with a textual label. The Checkbox maintains a boolean state--whether it is checked or not. The checkbox may optionally be part of a CheckboxGroup which enforces "radio button" behavior. public class Checkbox extends Component implements ItemSelectable { // Public Constructors public Checkbox(); public Checkbox(String label); 1.1 public Checkbox(String label, boolean state); 1.1 public Checkbox(String label, boolean state, CheckboxGroup group); public Checkbox(String label, CheckboxGroup group, boolean state); // Public Instance Methods 1.1 public synchronized void addItemListener(ItemListener l); // From ItemSelectable public void addNotify(); // Overrides Component public CheckboxGroup getCheckboxGroup(); public String getLabel(); 1.1 public Object[] getSelectedObjects(); // From ItemSelectable public boolean getState(); 1.1 public synchronized void removeItemListener(ItemListener l); // From ItemSelectable public void setCheckboxGroup(CheckboxGroup g); public synchronized void setLabel(String label); public void setState(boolean state); // Protected Instance Methods protected String paramString(); // Overrides Component 1.1 protected void processEvent(AWTEvent e); // Overrides Component 1.1 protected void processItemEvent(ItemEvent e); }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Checkbox(ItemSelectable)
Passed To: CheckboxGroup.setCurrent(), CheckboxGroup.setSelectedCheckbox(), Toolkit.createCheckbox()
http://localhost/java/javaref/javanut/ch18_10.htm (1 of 2) [20/12/2001 10:59:58]
[Chapter 18] 18.10 java.awt.Checkbox (JDK 1.0)
Returned By: CheckboxGroup.getCurrent(), CheckboxGroup.getSelectedCheckbox()
java.awt.CardLayout (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_10.htm (2 of 2) [20/12/2001 10:59:58]
java.awt.CheckboxGroup (JDK 1.0)
[Chapter 18] 18.11 java.awt.CheckboxGroup (JDK 1.0)
Chapter 18 The java.awt Package
18.11 java.awt.CheckboxGroup (JDK 1.0) A CheckboxGroup object enforces mutual exclusion (also known as "radio button" behavior) among any number of Checkbox buttons. A Checkbox component can specify a CheckboxGroup object when created or with Checkbox.setCheckboxGroup(). If a Checkbox with a given CheckboxGroup object is selected, then the CheckboxGroup ensures that the previously selected Checkbox becomes unselected. public class CheckboxGroup extends Object implements Serializable { // Public Constructor public CheckboxGroup(); // Public Instance Methods # public Checkbox getCurrent(); 1.1 public Checkbox getSelectedCheckbox(); # public synchronized void setCurrent(Checkbox box); 1.1 public synchronized void setSelectedCheckbox(Checkbox box); public String toString(); // Overrides Object }
Passed To: Checkbox(), Checkbox.setCheckboxGroup(), CheckboxPeer.setCheckboxGroup()
Returned By: Checkbox.getCheckboxGroup()
java.awt.Checkbox (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_11.htm [20/12/2001 10:59:58]
java.awt.CheckboxMenuItem (JDK 1.0)
[Chapter 18] 18.12 java.awt.CheckboxMenuItem (JDK 1.0)
Chapter 18 The java.awt Package
18.12 java.awt.CheckboxMenuItem (JDK 1.0) This class represents a checkbox with a textual label in a GUI menu. It maintains a boolean state--whether it is checked or not. See also MenuItem. public class CheckboxMenuItem extends MenuItem implements ItemSelectable { // Public Constructors 1.1 public CheckboxMenuItem(); public CheckboxMenuItem(String label); 1.1 public CheckboxMenuItem(String label, boolean state); // Public Instance Methods 1.1 public synchronized void addItemListener(ItemListener l); // From ItemSelectable public void addNotify(); // Overrides MenuItem 1.1 public synchronized Object[] getSelectedObjects(); // From ItemSelectable public boolean getState(); public String paramString(); // Overrides MenuItem 1.1 public synchronized void removeItemListener(ItemListener l); // From ItemSelectable public synchronized void setState(boolean b); // Protected Instance Methods 1.1 protected void processEvent(AWTEvent e); // Overrides MenuItem 1.1 protected void processItemEvent(ItemEvent e); }
Hierarchy: Object->MenuComponent(Serializable)->MenuItem->CheckboxMenuItem(ItemSelectable)
Passed To: Toolkit.createCheckboxMenuItem()
java.awt.CheckboxGroup (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_12.htm [20/12/2001 10:59:58]
java.awt.Choice (JDK 1.0)
[Chapter 22] 22.3 java.awt.peer.CheckboxMenuItemPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.3 java.awt.peer.CheckboxMenuItemPeer (JDK 1.0) public abstract interface CheckboxMenuItemPeer extends MenuItemPeer { // Public Instance Methods public abstract void setState(boolean t); }
Hierarchy: (CheckboxMenuItemPeer(MenuItemPeer(MenuComponentPeer)))
Returned By: Toolkit.createCheckboxMenuItem()
java.awt.peer.CanvasPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_03.htm [20/12/2001 10:59:59]
java.awt.peer.CheckboxPeer (JDK 1.0)
[Chapter 22] 22.4 java.awt.peer.CheckboxPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.4 java.awt.peer.CheckboxPeer (JDK 1.0) public abstract interface CheckboxPeer extends ComponentPeer { // Public Instance Methods public abstract void setCheckboxGroup(CheckboxGroup g); public abstract void setLabel(String label); public abstract void setState(boolean state); }
Returned By: Toolkit.createCheckbox()
java.awt.peer.CheckboxMenuItemPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_04.htm [20/12/2001 10:59:59]
java.awt.peer.ChoicePeer (JDK 1.0)
[Chapter 31] 31.2 java.util.zip.CheckedInputStream (JDK 1.1)
Chapter 31 The java.util.zip Package
31.2 java.util.zip.CheckedInputStream (JDK 1.1) This class is a subclass of java.io.FilterInputStream; it allows a stream to be read and a checksum computed on its contents at the same time. This is useful when you want to check the integrity of a stream of data against a published checksum value. To create a CheckedInputStream, you must specify both the stream that it should read and also a Checksum object, such as CRC32, that implements the particular checksum algorithm you desire. The read() and skip() methods are the same as those of other input streams. As bytes are read, they are incorporated into the checksum that is being computed. Note that the getChecksum() method does not return the checksum value itself, but rather the Checksum object. You must call the getValue() method of this object to obtain the checksum value. public class CheckedInputStream extends FilterInputStream { // Public Constructor public CheckedInputStream(InputStream in, Checksum cksum); // Public Instance Methods public Checksum getChecksum(); public int read() throws IOException; // Overrides FilterInputStream public int read(byte[] buf, int off, int len) throws IOException; // Overrides FilterInputStream public long skip(long n) throws IOException; // Overrides FilterInputStream }
Hierarchy: Object->InputStream->FilterInputStream->CheckedInputStream
java.util.zip.Adler32 (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_02.htm [20/12/2001 10:59:59]
java.util.zip.CheckedOutputStream (JDK 1.1)
[Chapter 31] 31.3 java.util.zip.CheckedOutputStream (JDK 1.1)
Chapter 31 The java.util.zip Package
31.3 java.util.zip.CheckedOutputStream (JDK 1.1) This class is a subclass of java.io.FilterOutputStream that allows data to be written to a stream and a checksum computed on that data at the same time. To create a CheckedOutputStream you must specify the output stream that it is to write its data to, and you must also specify a Checksum object, such as an instance of Adler32, that implements the particular checksum algorithm you desire. The write() methods are similar to those of other OutputStream classes. The getChecksum() method returns the Checksum object. Note that you must call getValue() on this object in order to obtain the actual checksum value. public class CheckedOutputStream extends FilterOutputStream { // Public Constructor public CheckedOutputStream(OutputStream out, Checksum cksum); // Public Instance Methods public Checksum getChecksum(); public void write(int b) throws IOException; // Overrides FilterOutputStream public void write(byte[] b, int off, int len) throws IOException; Overrides FilterOutputStream }
Hierarchy: Object->OutputStream->FilterOutputStream->CheckedOutputStream
java.util.zip.CheckedInputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_03.htm [20/12/2001 10:59:59]
java.util.zip.Checksum (JDK 1.1)
//
[Chapter 24] 24.53 java.io.PrintWriter (JDK 1.1)
Chapter 24 The java.io Package
24.53 java.io.PrintWriter (JDK 1.1) This class is a character output stream that implements a number of print() and println() methods that output textual representations of primitive values and objects. When you create a PrintWriter object, you specify a character or byte output stream that it should write its characters to, and also optionally specify whether the PrintWriter stream should be automatically flushed whenever println() is called. If you specify a byte output stream as the destination, the PrintWriter() constructor automatically creates the necessary OutputStreamWriter object to convert characters to bytes using the default encoding. PrintWriter implements the normal write(), flush(), and close() methods that all Writer subclasses do. It is more common to use the higher-level print() and println() methods, each of which converts its argument to a string before outputting it. println() has the additional behavior of terminating the line (and optionally flushing the buffer) after printing its argument. The methods of PrintWriter never throw exceptions. Instead, when errors occur, they set an internal flag that you can check by calling checkError(). checkError() first flushes the internal stream, and then returns true if any exception has occurred while writing values to that stream. Once an error has occurred on a PrintWriter object, all subsequent calls to checkError() return true; there is no way to reset the error flag. PrintWriter is the character stream analog to PrintStream, which it supersedes. You can usually trivially replace any PrintStream objects in a program with PrintWriter objects. This is particularly important for internationalized programs. The only valid remaining use for the PrintStream class is for the System.out and System.err standard output streams. See PrintStream for details. public class PrintWriter extends Writer { // Public Constructors public PrintWriter(Writer out); public PrintWriter(Writer out, boolean autoFlush); public PrintWriter(OutputStream out); public PrintWriter(OutputStream out, boolean autoFlush); // Public Instance Methods public boolean checkError(); public void close(); // Defines Writer public void flush(); // Defines Writer public void print(boolean b); public void print(char c); public void print(int i); public void print(long l); public void print(float f); public void print(double d); public void print(char[] s); http://localhost/java/javaref/javanut/ch24_53.htm (1 of 2) [20/12/2001 11:00:00]
[Chapter 24] 24.53 java.io.PrintWriter (JDK 1.1)
public void print(String s); public void print(Object obj); public void println(); public void println(boolean x); public void println(char x); public void println(int x); public void println(long x); public void println(float x); public void println(double x); public void println(char[] x); public void println(String x); public void println(Object x); public void write(int c); // Overrides Writer public void write(char[] buf, int off, int len); // Defines Writer public void write(char[] buf); // Overrides Writer public void write(String s, int off, int len); // Overrides Writer public void write(String s); // Overrides Writer // Protected Instance Methods protected void setError(); }
Hierarchy: Object->Writer->PrintWriter
Passed To: Component.list(), Container.list(), Properties.list(), Throwable.printStackTrace()
java.io.PrintStream (JDK 1.0)
java.io.PushbackInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_53.htm (2 of 2) [20/12/2001 11:00:00]
[Chapter 31] 31.4 java.util.zip.Checksum (JDK 1.1)
Chapter 31 The java.util.zip Package
31.4 java.util.zip.Checksum (JDK 1.1) This interface defines the methods required to compute a checksum on a stream of data. The checksum is computed based on the bytes of data supplied by the update() methods, and the current value of the checksum can be obtained at any time with the getValue() method. reset() resets the checksum to its default value--use this method before beginning a new stream of data. Note that the checksum value computed by a Checksum object and returned through the getValue() method must fit into a long value. Therefore, this interface is not suitable for the cryptographic checksum algorithms used in cryptography and security. The classes CheckedInputStream and CheckedOutputStream provide a higher-level API for computing a checksum on a stream of data. public abstract interface Checksum { // Public Instance Methods public abstract long getValue(); public abstract void reset(); public abstract void update(int b); public abstract void update(byte[] b, int off, int len); }
Implemented By: Adler32, CRC32
Passed To: CheckedInputStream(), CheckedOutputStream()
Returned By: CheckedInputStream.getChecksum(), CheckedOutputStream.getChecksum()
http://localhost/java/javaref/javanut/ch31_04.htm (1 of 2) [20/12/2001 11:00:00]
[Chapter 31] 31.4 java.util.zip.Checksum (JDK 1.1)
java.util.zip.CheckedOutputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_04.htm (2 of 2) [20/12/2001 11:00:00]
java.util.zip.CRC32 (JDK 1.1)
[Chapter 22] 22.5 java.awt.peer.ChoicePeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.5 java.awt.peer.ChoicePeer (JDK 1.0) public abstract interface ChoicePeer extends ComponentPeer { // Public Instance Methods 1.1 public abstract void add(String item, int index); public abstract void addItem(String item, int index); 1.1 public abstract void remove(int index); public abstract void select(int index); }
Returned By: Toolkit.createChoice()
java.awt.peer.CheckboxPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_05.htm [20/12/2001 11:00:00]
java.awt.peer.ComponentPeer (JDK 1.0)
[Chapter 25] 25.10 java.lang.ClassCircularityError (JDK 1.0)
Chapter 25 The java.lang Package
25.10 java.lang.ClassCircularityError (JDK 1.0) Signals that a circular dependency has been detected while performing initialization for a class. public class ClassCircularityError extends LinkageError { // Public Constructors public ClassCircularityError(); public ClassCircularityError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->ClassCircularityError
java.lang.ClassCastException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_10.htm [20/12/2001 11:00:00]
java.lang.ClassFormatError (JDK 1.0)
[Chapter 16] javac
Chapter 16 JDK Tools
javac Name javac---The Java Compiler
Availability JDK 1.0 and later.
Synopsis javac [ options ] files
Description javac is the Java compiler--it compiles Java source code (in .java files) into Java byte-codes (in .class files). The Java compiler is itself written in Java. javac may be passed any number of Java source files, whose names must all end with the .java extension. javac produces a separate .class class file for each class defined in the source files, regardless of how many source files there are. In other words, there need not be a one-to-one mapping between Java source files and Java class files. Note also that the compiler requires that there be only a single public class defined in any one source file, and that the name of the file (minus the .java extension) be the same as the name of the class (minus its package name, of course). By default, javac places the class files it generates in the same directory as the corresponding source file. You can override this behavior with the -d option. When a source file references a class that is not defined in another source file on the command line, javac searches for the definition of that class using the class path. The default class path contains only the
http://localhost/java/javaref/javanut/ch16_04.htm (1 of 3) [20/12/2001 11:00:01]
[Chapter 16] javac
current directory and the system classes. You may specify additional classes and packages to be searched with the -classpath option or the CLASSPATH environment variable. If javac compiles a source file that relies on a class that is out of date (i.e., if the source file for that class is newer than the class file), it automatically recompiles that file.
Options -classpath path The path that javac uses to look up classes referenced in the specified source code. This option overrides the default path and any path specified by the CLASSPATH environment variable. The path specified is an ordered list of directories and ZIP files, separated by colons on UNIX systems or semicolons on Windows systems. To specify additional directories or ZIP files to be searched, without overriding the default system class path, use the CLASSPATH environment variable. See the java reference page for more information on specifying paths. -d directory The directory in which (or beneath which) class files should be stored. By default, javac stores the .class files it generates in the same directory as the .java file that those classes were defined in. If the -d flag is specified, however, the specified directory is treated as the root of the class hierarchy and .class files are placed in this directory, or in the appropriate subdirectory below it, depending on the package name of the class. Thus, the following command: % javac -d java/classes java/src/Checkers.java places the file Checkers.class in the directory java/classes if the Checkers.java file has no package statement. On the other hand, if the source file specifies that it is in a package: package david.games; then the .class file is stored in java/classes/david/games. When the -d option is specified, javac automatically creates any directories it needs to store its class files in the appropriate place. -depend Tells javac to recompile any out-of-date class files it encounters, not just those that are referenced from one of the specified source files. -deprecation Tells javac to issue a warning for every use of a deprecated API. By default, javac issues only a single warning if a program uses deprecated APIs. Available in JDK 1.1 and later. -g This option tells javac to add line numbers and local variable information to the output class files, for use by debuggers. By default, javac only generates the line numbers. With the -O option, javac http://localhost/java/javaref/javanut/ch16_04.htm (2 of 3) [20/12/2001 11:00:01]
[Chapter 16] javac
does not generate even that information. -Jjavaoption Pass the argument javaoption directly through to the Java interpreter. javaoption should not contain spaces; if multiple arguments must be passed to the interpreter, use multiple -J options. Available in JDK 1.1 and later. -nowarn Tells javac not to print warning messages. Errors are still reported as usual. -nowrite Tells javac not to create any class files. Source files are parsed as usual, but no output is written. This option is useful when you want to check that a file will compile without actually compiling it. -O Enable optimization of class files. This option may cause javac to compile static, final, and private methods inline, so that they execute faster. The trade-off is that the class files will be larger. This option also prevents javac from adding line number debugging information to the class files. -verbose Tells the compiler to display messages about what it is doing.
Environment CLASSPATH Specifies an ordered list (colon-separated on UNIX, semicolon-separated on Windows systems) of directories and ZIP files in which javac should look for class definitions. When a path is specified with this environment variable, javac always implicitly appends the location of the system classes to the end of the path. If this environment variable is not specified, the default path is the current directory and the system classes. This variable is overridden by the -classpath option.
See Also java, jdb
java
http://localhost/java/javaref/javanut/ch16_04.htm (3 of 3) [20/12/2001 11:00:01]
javadoc
[Chapter 16] javap
Chapter 16 JDK Tools
javap Name javap---The Java Class Disassembler
Availability JDK 1.0 and later.
Synopsis javap [ options ] classnames
Description javap disassembles the class files specified by the class names on the command line and prints a human-readable version of those classes. By default, javap prints declarations of the non-private members of each of the classes specified on the command line. The -l, -p, and -c options specify additional information to be printed, including a complete disassembly of the byte-codes in each of the specified classes. javap can also be used to run the class verifier on Java classes.
Options -c Print the Java Virtual Machine instructions for each of the methods in each of the specified classes. This option disassembles all methods, including private methods.
http://localhost/java/javaref/javanut/ch16_08.htm (1 of 3) [20/12/2001 11:00:01]
[Chapter 16] javap
-classpath path The path that javap uses to look up the classes named on the command line. This option overrides the default path and any path specified by the CLASSPATH environment variable. The path specified is an ordered list of directories and ZIP files, separated by colons on UNIX systems or semicolons on Windows systems. To specify additional directories or ZIP files for javap to search without overriding the default system class path, use the CLASSPATH environment variable. See the java reference page for more information on specifying paths. -h Outputs the class in a form suitable for inclusion in a C header file. -l Prints line numbers and local variable tables in addition to the public fields of the class. Note that line numbers and local variable information is included for use with debuggers. Local variable information is available only if a class was compiled with the -g option to javac; line number information is available only if a class was compiled without the -O option. -p Prints private methods and variables of the specified class in addition to the public ones. Note that some compilers (though not javac) may allow this private field information to be "obfuscated" in such a way that private fields and method arguments no longer have meaningful names. This makes Java classes harder to disassemble or reverse engineer. -s Outputs the class member declarations using the internal Virtual Machine format. -v Verbose. Outputs additional information (in the form of Java comments) about each member of each specified class. -verify Causes javap to run the class verifier on the specified classes and display the results of verification. -version Causes javap to display its version number.
Environment CLASSPATH Specifies an ordered list (colon-separated on UNIX, semicolon-separated on Windows systems) of directories and ZIP files in which javap should look for class definitions. When a path is specified with this environment variable, javap always implicitly appends the location of the system classes http://localhost/java/javaref/javanut/ch16_08.htm (2 of 3) [20/12/2001 11:00:01]
[Chapter 16] javap
to the end of the path. If this environment variable is not specified, the default path is the current directory and the system classes. This variable is overridden by the -classpath option.
See Also java, javac
javakey
http://localhost/java/javaref/javanut/ch16_08.htm (3 of 3) [20/12/2001 11:00:01]
jdb
[Chapter 5] 5.2 Nested Top-Level Classes and Interfaces
Chapter 5 Inner Classes and Other New Language Features
5.2 Nested Top-Level Classes and Interfaces As explained above, a nested top-level class or interface is just like a regular package-member class or interface, except that, for convenience, it has been nested within another class or interface. Note that nested top-level classes and interfaces must be declared static. They can only be nested within other top-level classes and interfaces (i.e., they cannot be declared within inner classes), but they can be nested to any depth. Example 5.1 shows how you might define a nested top-level "helper" interface. Note the use of the static keyword in the declaration of the interface. The example also shows how this interface is used both within the class that contains it and by external classes. Note the use of its hierarchical name in the external class. Example 5.1: Defining and Using a Nested Top-Level Interface public class LinkedList { // This nested top-level helper interface is defined as a static member. public interface Linkable { public Linkable getNext(); public void setNext(Linkable node); } // The head of the list is a Linkable object. Linkable head; // Method bodies omitted. public void insert(Linkable node) { ... } public remove(Linkable node) { ... } } // This class defines a type of node that we'd like to use in // a linked list. Note the nested interface name in the implements clause. class LinkableInteger implements LinkedList.Linkable { // Here's the node's data and constructor. int i; public LinkableInteger(int i) { this.i = i; } // Here are the data and methods required to implement the interface. LinkedList.Linkable next; public LinkedList.Linkable getNext() { return next; } public void setNext(LinkedList.Linkable node) { next = node; }
http://localhost/java/javaref/javanut/ch05_02.htm (1 of 2) [20/12/2001 11:00:02]
[Chapter 5] 5.2 Nested Top-Level Classes and Interfaces
} The import statement can be used to import nested top-level classes and interfaces from the class that defines them, just as it can be used to import package member top-level classes and interfaces from the package that defines them. Example 5.2 shows a new definition of the LinkableInteger class from Example 5.1 that uses an import statement to allow it to refer to the Linkable interface by its simple, unqualified name (i.e., the name of the enclosing class is no longer needed). Example 5.2: Importing a Static Member Class import LinkedList.*; // Or use import LinkedList.Linkable; // Since we use an import statement, we can just type // "Linkable" instead of "LinkedList.Linkable". class LinkableInteger2 implements Linkable { int i; public LinkableInteger2(int i) { this.i = i; } Linkable next; public Linkable getNext() { return next; } public void setNext(Linkable node) { next = node; } }
Nested Top-Level Classes and .class Files When you compile the LinkedList.java file shown in Example 5.1, you'll find that two class files are generated. The first is named LinkedList.class, as expected. The second, however, is named LinkedList$Linkable.class. The $ in this name is automatically inserted by the Java 1.1 compiler. The Java Virtual Machine knows nothing about nested top-level classes and interfaces or the various types of inner classes. Therefore, the Java compiler must convert these new types into standard, non-nested class files that the Java interpreter can understand. This is done through source-code transformations that insert $ characters into nested class names. These source-code transformations may also insert hidden fields, methods, and constructor arguments into the affected classes. Unless you are writing a Java 1.1 compiler, however, you do not need to know the details of these source-code transformations, and you will typically not even notice them, except in the names of class files. [2] [2] See the Java Language Specification if you want complete details on the source-code transformations performed by the Java 1.1 compiler to support inner classes.
An Overview of Inner Classes
http://localhost/java/javaref/javanut/ch05_02.htm (2 of 2) [20/12/2001 11:00:02]
Member Classes
[Chapter 3] 3.4 Class Methods
Chapter 3 Classes and Objects in Java
3.4 Class Methods Let's define a new method in our Circle class. This one tests whether a specified point falls within the defined circle: public class Circle { double x, y, r; // is point (a,b) inside this circle? public boolean isInside(double a, double b) { double dx = a - x; double dy = b - y; double distance = Math.sqrt(dx*dx + dy*dy); if (distance < r) return true; else return false; } . . // Constructor and other methods omitted. . } What's this Math.sqrt() thing? It looks like a method call and, given its name and its context, we can guess that it is computing a square root. But the method calls we've discussed are done through an object. Math isn't the name of an object that we've declared, and there aren't any global objects in Java, so this must be a kind of method call that we haven't seen before.
static Methods What's going on here is that Math is the name of a class. sqrt() is the name of a class method (or static method) defined in Math. It differs from the instance methods, such as area() in Circle, that we've seen so far. Class methods are like class variables in a number of ways: ● Class methods are declared with the static keyword. ● Class methods are often referred to as "static methods." ● Class methods are invoked through the class rather than through an instance. (Although within the class they may be invoked by method name alone.) ● Class methods are the closest Java comes to "global" methods. Because they must be referred to by the http://localhost/java/javaref/javanut/ch03_04.htm (1 of 4) [20/12/2001 11:00:02]
[Chapter 3] 3.4 Class Methods
class name, there is no danger of name conflicts.
No this Class methods differ from instance methods in one important way: they are not passed an implicit this reference. Thus, these this-less methods are not associated with any instance of the class and may not refer to any instance variables or invoke instance methods. Since class methods are not passed a this reference, and are not invoked through an object, they are the closest thing that Java offers to the "normal" C procedures that you may be accustomed to, and may therefore seem familiar and comforting. If you're sick and tired of this object-oriented business, it is perfectly possible to write complete Java programs using only class methods, although this does defeat an important purpose of using the language! But don't think that class methods are somehow cheating--there are perfectly good reasons to declare a method static. And indeed, there are classes like Math that declare all their methods (and variables) static. Since Math is a collection of functions that operate on floating-point numbers, which are a primitive type, there are no objects involved, and no need for instance methods. System is another class that defines only class methods--it provides a varied collection of system functions for which there is no appropriate object framework.
A Class Method for Circles Example 3.5 shows two (overloaded) definitions of a method for our Circle class. One is an instance method and one is a class method. Example 3.5: A Class Method and an Instance Method public class Circle { public double x, y, r; // An instance method. Returns the bigger of two circles. public Circle bigger(Circle c) { if (c.r > r) return c; else return this; } // A class method. Returns the bigger of two circles. public static Circle bigger(Circle a, Circle b) { if (a.r > b.r) return a; else return b; } . . // Other methods omitted here. . } You would invoke the instance method like this: Circle a = new Circle(2.0); Circle b = new Circle(3.0); Circle c = a.bigger(b);
// or, b.bigger(a);
And you would invoke the class method like this:
http://localhost/java/javaref/javanut/ch03_04.htm (2 of 4) [20/12/2001 11:00:02]
[Chapter 3] 3.4 Class Methods
Circle a = new Circle(2.0); Circle b = new Circle(3.0); Circle c = Circle.bigger(a,b); Neither of these is the "correct" way to implement this method. One or the other will seem more natural, depending on circumstances.
A Mystery Explained Now that we understand class variables, instance variables, class methods, and instance methods, we are in a position to explore that mysterious method call we saw in our very first Java "Hello World" example: System.out.println("Hello world!"); One hypothesis is that println() is a class method in a class named out, which is in a package named System. Syntactically, this is perfectly reasonable (except perhaps that class names always seem to be capitalized by convention, and out isn't capitalized). But if you look at the API documentation, you'll find that System is not a package name; it is the name of a class (which is in the java.lang package, by the way). Can you figure it out? Here's the story: System is a class. It has a class variable named out. out refers to an object of type PrintStream. The object System.out has an instance method named println(). Mystery solved!
Static Initializers Both class and instance variables can have initializers attached to their declarations. For example: static int num_circles = 0; float r = 1.0; Class variables are initialized when the class is first loaded. Instance variables are initialized when an object is created. Sometimes we need more complex initialization than is possible with these simple variable initializers. For instance variables, there are constructor methods, which are run when a new instance of the class is created. Java also allows you to write an initialization method for class variables. Such a method is called a static initializer. The syntax of static initializers gets kind of bizarre. Consider that a static initializer is invoked automatically by the system when the class is loaded. Thus there are no meaningful arguments that can be passed to it (unlike the arguments we can pass to a constructor method when creating a new instance). There is also no value to return. So a static initializer has no arguments and no return value. Furthermore, it is not really necessary to give it a name, since the system calls the method automatically for us. What part of a method declaration is left? Just the static keyword and the curly brackets! Example 3.6 shows a class declaration with a static initializer. Notice that the class contains a regular static variable initializer of the kind we've seen before, and also a static initializer--an arbitrary block of code between { and }. Example 3.6: A Static Initializer
http://localhost/java/javaref/javanut/ch03_04.htm (3 of 4) [20/12/2001 11:00:02]
[Chapter 3] 3.4 Class Methods
// We can draw the outline of a circle using trigonometric functions. // Trigonometry is slow though, so we pre-compute a bunch of values. public class Circle { // Here are our static lookup tables, and their own simple initializers. static private double sines[] = new double[1000]; static private double cosines[] = new double[1000]; // Here's a static initializer "method" that fills them in. // Notice the lack of any method declaration! static { double x, delta_x; int i; delta_x = (Circle.PI/2)/(1000-1); for(i = 0, x = 0.0; i < 1000; i++, x += delta_x) { sines[i] = Math.sin(x); cosines[i] = Math.cos(x); } } . . // The rest of the class omitted. . } The syntax gets even a little stranger than this. Java allows any number of static initializer blocks of code to appear within a class definition. What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded. One common use of static initializers is for classes that implement native methods--i.e., methods written in C. The static initializer for such a class should call System.load() or System.loadLibrary() to read in the native library that implements these native methods.
Instance Initializers In Java 1.1, a class definition may also include instance initializers. These look like static initializers, but without the static keyword. An instance initializer is like a constructor: it runs when an instance of the class is created. We'll see more about instance initializers in Chapter 5, Inner Classes and Other New Language Features, Inner Classes and Other New Language Features.
Class Variables
http://localhost/java/javaref/javanut/ch03_04.htm (4 of 4) [20/12/2001 11:00:02]
Object Destruction
[Chapter 3] 3.3 Class Variables
Chapter 3 Classes and Objects in Java
3.3 Class Variables In our Circle class definition, we declared three "instance" variables: x, y, and r. Each instance of the class--each circle--has its own copy of these three variables. These variables are like the fields of a struct in C--each instance of the struct has a copy of the fields. Sometimes, though, we want a variable of which there is only one copy--something like a global variable in C. The problem is that Java doesn't allow global variables. (Actually, those in the know consider this is feature!) Every variable in Java must be declared inside a class. So Java uses the static keyword to indicate that a particular variable is a class variable rather than an instance variable. That is, that there is only one copy of the variable, associated with the class, rather than many copies of the variable associated with each instance of the class. The one copy of the variable exists regardless of the number of instances of the class that are created--it exists and can be used even if the class is never actually instantiated. This kind of variable, declared with the static keyword, is often called a static variable. I prefer (and recommend) the name "class variable" because it is easily distinguished from its opposite, "instance variable." We'll use both terms in this book.
An Example As an example (a somewhat contrived one), suppose that while developing the Circle class we wanted to do some testing on it and determine how much it gets used. One way to do this would be to count the number of Circle objects that are instantiated. To do this we obviously need a variable associated with the class, rather than with any particular instance. Example 3.4 shows how we can do it--we declare a static variable and increment it each time we create a Circle. Example 3.4: Static Variable Example public class Circle { static int num_circles = 0; // class variable: how many circles created public double x, y, r; // instance vars: the center and the radius public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; num_circles++; } public Circle(double r) { this(0.0, 0.0, r); } public Circle(Circle c) { this(c.x, c.y, c.r); }
http://localhost/java/javaref/javanut/ch03_03.htm (1 of 3) [20/12/2001 11:00:03]
[Chapter 3] 3.3 Class Variables
public Circle() { this(0.0, 0.0, 1.0); } public double circumference() { return 2 * 3.14159 * r; } public double area() { return 3.14159 * r*r; } }
Accessing Class Variables Now that we are keeping track of the number of Circle objects created, how can we access this information? Because static variables are associated with the class rather than with an instance, we access them through the class rather than through the instance. Thus, we might write: [5] [5] Recall that System.out.println() prints a line of text, and that the string concatenation operator, +, converts non-string types to strings as necessary. System.out.println("Number of circles created: " + Circle.num_circles); Notice that in our definition of the constructor method in Example 3.4, we just used num_circles instead of Circle.num_circles. We're allowed to do this within the class definition of Circle itself. Anywhere else, though, we must use the class name as well.
Global Variables? Earlier we said that Java does not support global variables. In a sense, though, Circle.num_circles behaves just like one. What is different from a global variable in C is that there is no possibility of name conflicts. If we use some other class with a class variable named num_circles, there won't be a "collision" between these two "global" variables, because they must both be referred to by their class names. Since each class variable must be part of a class and must be referred to with its class name, each has a unique name. Furthermore, each class has a unique name because, as we saw in Chapter 2, How Java Differs from C, it is part of a package with a unique name.
Constants: Another Class Variable Example Let's try a less forced example of why you might want to use a class variable with the Circle class. When computing the area and circumference of circles, we use the value pi. Since we use the value frequently, we don't want to keep typing out 3.14159, so we'll define it as a class variable that has a convenient name: public class Circle { public static final double PI = 3.14159265358979323846; public double x, y, r; // ... etc.... } Besides the static keyword that we've already seen, we use the final keyword, which means that this variable can never have its value changed. This prevents you from doing something stupid like: Circle.PI = 4; which would tend to give you some pretty square-looking circles.
http://localhost/java/javaref/javanut/ch03_03.htm (2 of 3) [20/12/2001 11:00:03]
[Chapter 3] 3.3 Class Variables
The Java compiler is smart about variables declared both static and final--it knows that they have constant values. So when you write code like this: double circumference = 2 * Circle.PI * radius; the compiler precomputes the value 2 * Circle.PI , instead of leaving it for the interpreter. Java does not have a preprocessor with a C-style #define directive. static final variables are Java's substitute for C's #define'd constants. Note that the C convention of capitalizing constants has been carried over into Java.
Object Creation
http://localhost/java/javaref/javanut/ch03_03.htm (3 of 3) [20/12/2001 11:00:03]
Class Methods
[Chapter 25] 25.8 java.lang.Class (JDK 1.0)
Chapter 25 The java.lang Package
25.8 java.lang.Class (JDK 1.0) This class represents a Java class or interface, or, in Java 1.1, any Java type. There is one Class object for each class that is loaded into the Java Virtual Machine, and in Java 1.1 there are special Class objects that represent the Java primitive types. The TYPE constants defined by Boolean, Integer, and the other primitive "wrapper classes" hold these special Class objects. Array types are also represented by Class objects in Java 1.1. There is no constructor for this class. You can obtain a Class object by calling the getClass() method of any instance of the desired class. In Java 1.1, a Class object may also be referred to by appending .class to the name of a class. Finally, and most interestingly, a class can be dynamically loaded by passing its fully-qualified name (i.e., package name plus class name) to the static Class.forName() method. This method loads the named class, if it is not already loaded, into the Java interpreter, and returns a Class object for it. The newInstance() method creates an instance of a given class--this allows you to create instances of dynamically loaded classes for which you cannot use the new keyword. Note that this method only works when the target class has a no-argument constructor. See newInstance() in java.lang.reflect.Constructor for a more powerful way to instantiate dynamically loaded classes. getName() returns the name of the class. getSuperclass() returns its superclass. isInterface() tests whether the Class object represents an interface, and getInterfaces() returns an array of the interfaces that this class implements. The various other get and is methods return other information about the represented class, and form part of the Java Reflection API, along with the classes in java.lang.reflect. public final class Class extends Object implements Serializable { // No Constructor // Class Methods public static native Class forName(String className) throws ClassNotFoundException; // Public Instance Methods public native ClassLoader getClassLoader(); 1.1public Class[] getClasses(); 1.1public native Class getComponentType(); 1.1public Constructor getConstructor(Class[] parameterTypes) throws NoSuchMethodException, SecurityException; 1.1public Constructor[] getConstructors() throws SecurityException; 1.1public Class[] getDeclaredClasses() throws SecurityException; 1.1public Constructor getDeclaredConstructor(Class[] parameterTypes) throws NoSuchMethodException, SecurityException; 1.1public Constructor[] getDeclaredConstructors() throws SecurityException; 1.1public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException; 1.1public Field[] getDeclaredFields() throws SecurityException; 1.1public Method getDeclaredMethod(String name, Class[] parameterTypes)
http://localhost/java/javaref/javanut/ch25_08.htm (1 of 3) [20/12/2001 11:00:03]
[Chapter 25] 25.8 java.lang.Class (JDK 1.0)
throws NoSuchMethodException, SecurityException; 1.1public Method[] getDeclaredMethods() throws SecurityException; 1.1public Class getDeclaringClass(); 1.1public Field getField(String name) throws NoSuchFieldException, SecurityException; 1.1public Field[] getFields() throws SecurityException; public native Class[] getInterfaces(); 1.1public Method getMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException; 1.1public Method[] getMethods() throws SecurityException; 1.1public native int getModifiers(); public native String getName(); 1.1public URL getResource(String name); 1.1public InputStream getResourceAsStream(String name); 1.1public native Object[] getSigners(); public native Class getSuperclass(); 1.1public native boolean isArray(); 1.1public native boolean isAssignableFrom(Class cls); 1.1public native boolean isInstance(Object obj); public native boolean isInterface(); 1.1public native boolean isPrimitive(); public native Object newInstance() throws InstantiationException, IllegalAccessException; public String toString(); // Overrides Object }
Passed To: Array.newInstance(), BeanDescriptor(), Beans.getInstanceOf(), Beans.isInstanceOf(), Class.getConstructor(), Class.getDeclaredConstructor(), Class.getDeclaredMethod(), Class.getMethod(), Class.isAssignableFrom(), ClassLoader.resolveClass(), ClassLoader.setSigners(), Compiler.compileClass(), DataFlavor(), EventSetDescriptor(), IndexedPropertyDescriptor(), Introspector.getBeanInfo(), ObjectOutputStream.annotateClass(), ObjectStreamClass.lookup(), PropertyDescriptor(), PropertyDescriptor.setPropertyEditorClass(), PropertyEditorManager.findEditor(), PropertyEditorManager.registerEditor(), SecurityManager.checkMemberAccess()
Returned By: BeanDescriptor.getBeanClass(), BeanDescriptor.getCustomizerClass(), Class.forName(), Class.getClasses(), Class.getComponentType(), Class.getDeclaredClasses(), Class.getDeclaringClass(), Class.getInterfaces(), Class.getSuperclass(), ClassLoader.defineClass(), ClassLoader.findLoadedClass(), ClassLoader.findSystemClass(), ClassLoader.loadClass(), Constructor.getDeclaringClass(), Constructor.getExceptionTypes(), Constructor.getParameterTypes(), DataFlavor.getRepresentationClass(), EventSetDescriptor.getListenerType(), Field.getDeclaringClass(), Field.getType(), IndexedPropertyDescriptor.getIndexedPropertyType(), Member.getDeclaringClass(), Method.getDeclaringClass(), Method.getExceptionTypes(), Method.getParameterTypes(), Method.getReturnType(), Object.getClass(), ObjectInputStream.resolveClass(), ObjectStreamClass.forClass(), PropertyDescriptor.getPropertyEditorClass(), PropertyDescriptor.getPropertyType(), SecurityManager.currentLoadedClass(), SecurityManager.getClassContext()
Type Of: Boolean.TYPE, Byte.TYPE, Character.TYPE, Double.TYPE, Float.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE, Void.TYPE
http://localhost/java/javaref/javanut/ch25_08.htm (2 of 3) [20/12/2001 11:00:03]
[Chapter 25] 25.8 java.lang.Class (JDK 1.0)
java.lang.Character (JDK 1.0)
java.lang.ClassCastException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_08.htm (3 of 3) [20/12/2001 11:00:03]
[Chapter 25] 25.9 java.lang.ClassCastException (JDK 1.0)
Chapter 25 The java.lang Package
25.9 java.lang.ClassCastException (JDK 1.0) Signals an invalid cast of an object to a type of which it is not an instance. public class ClassCastException extends RuntimeException { // Public Constructors public ClassCastException(); public ClassCastException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->ClassCastException
java.lang.Class (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_09.htm [20/12/2001 11:00:03]
java.lang.ClassCircularityError (JDK 1.0)
[Chapter 25] 25.11 java.lang.ClassFormatError (JDK 1.0)
Chapter 25 The java.lang Package
25.11 java.lang.ClassFormatError (JDK 1.0) Signals an error in the binary format of a class file. public class ClassFormatError extends LinkageError { // Public Constructors public ClassFormatError(); public ClassFormatError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->ClassFormatError
java.lang.ClassCircularityError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_11.htm [20/12/2001 11:00:04]
java.lang.ClassLoader (JDK 1.0)
[Chapter 25] 25.12 java.lang.ClassLoader (JDK 1.0)
Chapter 25 The java.lang Package
25.12 java.lang.ClassLoader (JDK 1.0) This abstract class defines the necessary hook for Java to load classes over the network, or from other sources. Normal applications do not need to use or subclass this class. public abstract class ClassLoader extends Object { // Protected Constructor protected ClassLoader(); // Class Methods 1.1public static final URL getSystemResource(String name); 1.1public static final InputStream getSystemResourceAsStream(String name); // Public Instance Methods 1.1public URL getResource(String name); 1.1public InputStream getResourceAsStream(String name); 1.1public Class loadClass(String name) throws ClassNotFoundException; // Protected Instance Methods # protected final Class defineClass(byte[] data, int offset, int length); 1.1protected final Class defineClass(String name, byte[] data, int offset, int length); 1.1protected final Class findLoadedClass(String name); protected final Class findSystemClass(String name) throws ClassNotFoundException; protected abstract Class loadClass(String name, boolean resolve) throws ClassNotFoundException; protected final void resolveClass(Class c); 1.1protected final void setSigners(Class cl, Object[] signers); }
Passed To: Beans.instantiate()
Returned By: Class.getClassLoader(), SecurityManager.currentClassLoader()
java.lang.ClassFormatError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_12.htm [20/12/2001 11:00:04]
java.lang.ClassNotFoundException (JDK 1.0)
[Chapter 25] 25.13 java.lang.ClassNotFoundException (JDK 1.0)
Chapter 25 The java.lang Package
25.13 java.lang.ClassNotFoundException (JDK 1.0) Signals that a class to be loaded could not be found. public class ClassNotFoundException extends Exception { // Public Constructors public ClassNotFoundException(); public ClassNotFoundException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->ClassNotFoundException
Thrown By: Beans.instantiate(), Class.forName(), ClassLoader.findSystemClass(), ClassLoader.loadClass(), Externalizable.readExternal(), ObjectInput.readObject(), ObjectInputStream.defaultReadObject(), ObjectInputStream.readObject(), ObjectInputStream.resolveClass()
java.lang.ClassLoader (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_13.htm [20/12/2001 11:00:04]
java.lang.CloneNotSupportedException (JDK 1.0)
[Chapter 25] 25.22 java.lang.IllegalAccessError (JDK 1.0)
Chapter 25 The java.lang Package
25.22 java.lang.IllegalAccessError (JDK 1.0) Signals an attempted use of a class, method, or variable that is not accessible. public class IllegalAccessError extends IncompatibleClassChangeError { // Public Constructors public IllegalAccessError(); public IllegalAccessError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->IncompatibleClassChangeError->IllegalAccessError
java.lang.Float (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_22.htm [20/12/2001 11:00:04]
java.lang.IllegalAccessException (JDK 1.0)
[Chapter 25] 25.23 java.lang.IllegalAccessException (JDK 1.0)
Chapter 25 The java.lang Package
25.23 java.lang.IllegalAccessException (JDK 1.0) Signals that a class or initializer is not accessible. Thrown by Class.newInstance(). public class IllegalAccessException extends Exception { // Public Constructors public IllegalAccessException(); public IllegalAccessException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->IllegalAccessException
Thrown By: Class.newInstance(), Constructor.newInstance(), Field.get(), Field.getBoolean(), Field.getByte(), Field.getChar(), Field.getDouble(), Field.getFloat(), Field.getInt(), Field.getLong(), Field.getShort(), Field.set(), Field.setBoolean(), Field.setByte(), Field.setChar(), Field.setDouble(), Field.setFloat(), Field.setInt(), Field.setLong(), Field.setShort(), Method.invoke()
java.lang.IllegalAccessError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_23.htm [20/12/2001 11:00:04]
java.lang.IllegalArgumentException (JDK 1.0)
[Chapter 25] 25.28 java.lang.IncompatibleClassChangeError (JDK 1.0)
Chapter 25 The java.lang Package
25.28 java.lang.IncompatibleClassChangeError (JDK 1.0) This is the superclass of a group of related error types. It signals some kind of illegal use of a legal class. public class IncompatibleClassChangeError extends LinkageError { // Public Constructors public IncompatibleClassChangeError(); public IncompatibleClassChangeError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->IncompatibleClassChangeError
Extended By: AbstractMethodError, IllegalAccessError, InstantiationError, NoSuchFieldError, NoSuchMethodError
java.lang.IllegalThreadStateException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_28.htm [20/12/2001 11:00:05]
java.lang.IndexOutOfBoundsException (JDK 1.0)
[Chapter 4] 4.2 Inner Classes
Chapter 4 What's New in Java 1.1
4.2 Inner Classes While the bulk of the changes in Java 1.1 are additions to the core Java API, there has also been a major addition to the language itself. The language has been extended to allow class definitions to be nested within other classes, and even to be defined locally, within blocks of code. Altogether, there are four new types of classes that can be defined in Java 1.1; these four new types are sometimes loosely referred to as "inner classes." Chapter 5, Inner Classes and Other New Language Features explains in detail how to define and use each of the four new types of classes. As we'll see, inner classes are useful primarily for defining simple "helper" or "adaptor" classes that serve a very specific function at a particular place in a program, and are not intended to be general-purpose "top-level" classes. By using inner classes nested within other classes, you can place the definition of these special-purpose helper classes closer to where they are actually used in your programs. This makes your code clearer, and also prevents you from cluttering up the package namespace with small special purpose classes that are not of interest to programmers using your package. We'll also see that inner classes are particularly useful in conjunction with the new AWT event model in Java 1.1. One important feature of inner classes is that no changes to the Java Virtual Machine are required to support them. When a Java 1.1 compiler encounters an inner class, it transforms the Java 1.1 source code in a way that converts the nested class to a regular top-level class. Once that transformation has been performed, the code can be compiled just as it would have been in Java 1.0.
Java 1.1 Package-by-Package
http://localhost/java/javaref/javanut/ch04_02.htm [20/12/2001 11:00:05]
The New AWT Event Model
[Chapter 24] 24.31 java.io.InvalidClassException (JDK 1.1)
Chapter 24 The java.io Package
24.31 java.io.InvalidClassException (JDK 1.1) Signals that the serialization mechanism has encountered one of several possible problems with the class of an object that is being serialized or deserialized. The classname field should contain the name of the class in question, and the getMessage() method is overridden to return this class name with the message. public class InvalidClassException extends ObjectStreamException { // Public Constructors public InvalidClassException(String reason); public InvalidClassException(String cname, String reason); // Public Instance Variables public String classname; // Public Instance Methods public String getMessage(); // Overrides Throwable }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ObjectStreamException->InvalidClassException
java.io.InterruptedIOException (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_31.htm [20/12/2001 11:00:05]
java.io.InvalidObjectException (JDK 1.1)
[Chapter 25] 25.35 java.lang.LinkageError (JDK 1.0)
Chapter 25 The java.lang Package
25.35 java.lang.LinkageError (JDK 1.0) The superclass of a group of errors that signal problems linking a class or resolving dependencies between classes. public class LinkageError extends Error { // Public Constructors public LinkageError(); public LinkageError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError
Extended By: ClassCircularityError, ClassFormatError, ExceptionInInitializerError, IncompatibleClassChangeError, NoClassDefFoundError, UnsatisfiedLinkError, VerifyError
java.lang.InterruptedException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_35.htm [20/12/2001 11:00:05]
java.lang.Long (JDK 1.0)
[Chapter 5] 5.4 Local Classes
Chapter 5 Inner Classes and Other New Language Features
5.4 Local Classes A local class is a class declared locally within a block of Java code. Typically, a local class is defined within a method, but local classes can also be defined within static initializers and instance initializers of a class. (Instance initializers are a new feature of Java 1.1 that we'll see later in this chapter.) Because Java code can only appear within class definitions, all local classes are nested within a containing class. For this reason, local classes share many of the features of member classes. It is usually more appropriate, however, to think of them as an entirely separate kind of inner class. A local class has approximately the same relationship to a member class as a local variable has to an instance variable of a class. Local classes have the following interesting features: ● They are only visible and usable within the block of code in which they are defined. ● They can use any final local variables or method parameters that are visible from the scope in which they are defined. [8] [8] As we'll see shortly, one of the other language changes in Java 1.1 is that local variables and method parameters can be declared final. The first defining characteristic of a local class is obviously that it is local. Like a local variable, the name of a local class is only valid within the block of code in which it was defined (and within any blocks nested with that block, of course). In many cases, this is not a problem. If a helper class is used only within a single method of a containing class, there is no reason that that helper cannot be coded as a local class rather than a member class. Example 5.5 shows how we can modify the enumerate() method of the LinkedList class we saw in previous examples so that it defines the Enumerator class as a local class, rather than as a member class. By doing this, we move the definition of the helper class even closer to the location where it is used and hopefully improve the clarity of the code even further. Example 5.5: Defining and Using a Local Class import java.util.*; public class LinkedList { // Our nested top-level interface. Body omitted here... public interface Linkable { ... } // The head of the list /* private */ Linkable head; // Method bodies omitted here. public void addToHead(Linkable node) { ... } http://localhost/java/javaref/javanut/ch05_04.htm (1 of 5) [20/12/2001 11:00:06]
[Chapter 5] 5.4 Local Classes
public Linkable removeHead() { ... } // This method creates and returns an Enumeration object for this // LinkedList. public Enumeration enumerate() { // Here's the definition of Enumerator as a local class. class Enumerator implements Enumeration { Linkable current; public Enumerator() { this.current = LinkedList.this.head; } public boolean hasMoreElements() { return (current != null); } public Object nextElement() { if (current == null) throw new NoSuchElementException("LinkedList"); Object value = current; current = current.getNext(); return value; } } // Create and return an instance of the Enumerator class defined here. return new Enumerator(); } }
How Local Classes Work A local class is able to refer to fields and methods in its containing class for exactly the same reason that a member class can--it is passed a hidden reference to the containing class in its constructor, and it saves that reference away in a private field added by the compiler. Also like member classes, local classes can use private fields and methods of their containing class, because the compiler inserts any required accessor methods. [9] [9] As previously noted, bugs in the compiler prevent this from working correctly in the current versions of the JDK. What makes local classes different from member classes is that they have the ability to refer to local variables from the scope that defines them. The crucial restriction on this ability, however, is that local classes can only reference local variables and parameters that are declared final. The reason for this is apparent from the implementation. A local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class refers to. The compiler also adds hidden arguments to each of the local class constructors to initialize these automatically created private fields to the appropriate values. So, in fact, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee, the local class can be assured that its internal copies of the variables are "in sync" with the real local variables.
New Syntax for Local Classes In Java 1.0, only fields, methods, and classes may be declared final. The addition of local classes to Java 1.1 has required a liberalization in the use of the final modifier. It can now be applied to local variables, arguments to methods, and even to the exception parameter of a catch statement (Local classes can refer to catch parameters, just as they can refer to method parameters, as long as they are in scope and are declared final.) The meaning of the final modifier remains the same in these new uses: once the local variable or argument has been
http://localhost/java/javaref/javanut/ch05_04.htm (2 of 5) [20/12/2001 11:00:06]
[Chapter 5] 5.4 Local Classes
assigned a value, that value may not be changed. Instances of local classes, like instances of member classes, have an enclosing instance that is implicitly passed to all constructors of the local class. Local classes can use the same new this syntax that member classes do to explicitly refer to members of enclosing classes. Local classes cannot use the new new and super syntax used by member classes, however.
Restrictions on Local Classes Like member classes, and for the same reasons, local classes cannot contain fields, methods, or classes that are declared static. static members must be declared at the top level. Since nested interfaces are implicitly static, local classes may not contain nested interface definitions. Another restriction on local classes is that they cannot be declared public, protected, private, or static. These modifiers are all used for members of classes, and are not allowed with local variable declarations; for the same reason they are not allowed with local class declarations. And finally, a local class, like a member class, cannot have the same name as any of its enclosing classes.
Typical Uses of Local Classes One common application of local classes is to implement "event listeners" for use with the new event model implemented by AWT and JavaBeans in Java 1.1. An event listener is a class that implements a specific "listener" interface. This listener is registered with an AWT component, such as a Button, or with some other "event source." When the Button (or other source) is clicked (or activated in some way), it responds to this event by invoking a method of the event listener. Since Java does not support method pointers, implementing a pre-defined interface is Java's way of defining a "callback" that is notified when some event occurs. The classes used to implement these interfaces are often called adapter classes. Working with adapter classes can become quite cumbersome when they all must be defined as top-level classes. But the introduction of local classes makes them much easier to use. Example 5.6 shows a local class used as an adapter class for handling GUI events. [10] This example also shows how a local class can make use of a method parameter that is declared final. [10] As we'll see in the next section, this adapter class could be written more succinctly as an anonymous class. Example 5.6: Using a Local Class as an Adapter import java.awt.*; import java.awt.event.*; // This class implements the functionality of some application. public class Application { // These are some constants used as the command argument to doCommand(). static final int save = 1; static final int load = 2; static final int quit = 3; // This method dispatches all the commands to the application. // Body omitted. void doCommand(int command) { } // Other methods of the application omitted... }
http://localhost/java/javaref/javanut/ch05_04.htm (3 of 5) [20/12/2001 11:00:06]
[Chapter 5] 5.4 Local Classes
// This class defines a GUI for the application. class GUI extends Frame { Application app; // holds a reference to the Application instance // Constructor and other methods omitted here... // This is a convenience method used to create menu items with // a specified label, keyboard shortcut, and command to be executed. // We declare the "command" argument final so the local // ActionListener class can refer to it. MenuItem createMenuItem(String label, char shortcut, final int command) { // First we create a MenuItem object. MenuItem item = new MenuItem(label, new MenuShortcut(shortcut)); // Then we define a local class to serve as our ActionListener. class MenuItemListener implements ActionListener { // Note that this method uses the app field of the enclosing class // and the (final) command argument from its containing scope. public void actionPerformed(ActionEvent e) { app.doCommand(command); } } // Next, we create an instance of our local class that will be // the particular action listener for this MenuItem. ActionListener listener = new MenuItemListener(); // Then we register the ActionListener for our new MenuItem. item.addActionListener(listener); // And return the item, ready to be inserted into a menu. return item; } } createMenuItem() is the method of interest in Example 5.6. It creates a MenuItem object with the specified label and keyboard shortcut, and then uses a local class to create an ActionListener object for the menu item. The ActionListener is responsible for translating the selection of the MenuItem into an invocation of the application's doCommand() method. Note that the command method parameter is declared final so it can be used by the local class. Also note that the local class uses the app field of the class that contains it. Because this is an instance variable instead of a local variable, it does not need to be declared final. A local class can use fields defined within the local class itself or inherited by the local class, final local variables and final parameters in the scope of the local class definition, and fields defined by or inherited by the containing class. Example 5.7 is a program that demonstrates these various fields and variables that are accessible to a local class. If you can make sense of the code, you have a good understanding of local classes. Example 5.7: Fields and Variables Accessible to a Local Class class A { protected char a = 'a'; } class B { protected char b = 'b'; } public class C extends A {
http://localhost/java/javaref/javanut/ch05_04.htm (4 of 5) [20/12/2001 11:00:06]
[Chapter 5] 5.4 Local Classes
private char c = 'c'; // Private fields visible to local class. public static char d = 'd'; public void createLocalObject(final char e) { final char f = 'f'; int i = 0; // i not final; not usable by local class. class Local extends B { char g = 'g'; public void printVars() { // All of these fields and variables are accessible to this class. System.out.println(g); // (this.g) g is a field of this class. System.out.println(f); // f is a final local variable. System.out.println(e); // e is a final local argument. System.out.println(d); // (C.this.d) d -- field of containing class. System.out.println(c); // (C.this.c) c -- field of containing class. System.out.println(b); // b is inherited by this class. System.out.println(a); // a is inherited by the containing class. } } Local l = this.new Local(); // Create an instance of the local class l.printVars(); // and call its printVars() method. } public static void main(String[] args) { // Create an instance of the containing class, and invoke the // method that defines and creates the local class. C c = new C(); c.createLocalObject('e'); // pass a value for final parameter e. } }
Member Classes
http://localhost/java/javaref/javanut/ch05_04.htm (5 of 5) [20/12/2001 11:00:06]
Anonymous Classes
[Chapter 5] 5.3 Member Classes
Chapter 5 Inner Classes and Other New Language Features
5.3 Member Classes While nested top-level classes are nested within a containing class, we've seen that they are still top-level classes, and that the nesting is purely a matter of organizational convenience. The same is not true of member classes, however. These classes are also nested, but they are not declared static, and in this case, the nesting is significant. The main features of member classes are: ● Every instance of a member class is internally associated with an instance of the class that defines or contains the member class. ● The methods of a member class can implicitly refer to the fields defined within the member class, as well as those defined by any enclosing class, including private fields of the enclosing class. Like nested top-level classes, member classes are commonly used for helper classes required by the enclosing class. You use a member class instead of a nested top-level class when the member class requires access to the instance fields of the enclosing class, or when every instance of the helper class must refer to an instance of the enclosing class. When you use a member class, this reference from member class to enclosing class is implemented automatically for you. Let's return to the LinkedList example that we saw above. Suppose we want to add the ability to loop through the elements in the linked list using the java.util.Enumeration interface. To do this, we define a separate class that implements this interface, and then add a method to the LinkedList class that returns an instance of the separate Enumeration class. Example 5.3 shows a typical Java 1.0-style implementation. [3] [3] For simplicity, this example implements a very simple Enumeration class that is not thread-safe and that may return incorrect results if items are added to or removed from the list while an Enumeration object is in use. Example 5.3: A LinkedList Enumerator, as a Separate Top-Level Class import java.util.*; public class LinkedList { // Our nested top-level interface. Body omitted here... public interface Linkable { ... } // The head of the list. Linkable head; // Method bodies omitted here. public void addToHead(Linkable node) { ... } public Linkable removeHead() { ... } // This method returns an Enumeration object for this LinkedList.
http://localhost/java/javaref/javanut/ch05_03.htm (1 of 7) [20/12/2001 11:00:06]
[Chapter 5] 5.3 Member Classes
public Enumeration enumerate() { return new LinkedListEnumerator(this); } } // This class defines the Enumeration type we use to list the elements in // a LinkedList. Note that each LinkedListEnumerator object is associated // with a particular LinkedList object which is passed to the constructor. class LinkedListEnumerator implements Enumeration { private LinkedList container; private LinkedList.Linkable current; public LinkedListEnumerator(LinkedList l) { container = l; current = container.head; } public boolean hasMoreElements() { return (current != null); } public Object nextElement() { if (current == null) throw new NoSuchElementException("LinkedList"); Object value = current; current = current.getNext(); return value; } } The point to notice about the LinkedListEnumerator class in Example 5.3 is that we must explicitly pass a LinkedList object to its constructor. The problem with Example 5.3 is that LinkedListEnumerator is defined as a separate top-level class, when it really would be more elegant to define it as part of the LinkedList class itself. In Java 1.1, this is easily done using a member class, as shown in Example 5.4. Example 5.4: A LinkedList Enumerator, as a Member Class import java.util.*; public class LinkedList { // Our nested top-level interface. Body omitted here... public interface Linkable { ... } // The head of the list. // This field could be private except for inner class-related compiler bugs. /* private */ Linkable head; // Method bodies omitted here. public void addToHead(Linkable node) { ... } public Linkable removeHead() { ... } // This method returns an Enumeration object for this LinkedList. // Note: no LinkedList object is explicitly passed to the constructor. public Enumeration enumerate() { return new Enumerator(); } // And here is the implementation of the Enumeration interface, // defined as a private member class. private class Enumerator implements Enumeration { Linkable current;
http://localhost/java/javaref/javanut/ch05_03.htm (2 of 7) [20/12/2001 11:00:06]
[Chapter 5] 5.3 Member Classes
// Note: the constructor implicitly refers to 'head' in containing class. public Enumerator() { current = head; } public boolean hasMoreElements() { return (current != null); } public Object nextElement() { if (current == null) throw new NoSuchElementException("LinkedList"); Object value = current; current = current.getNext(); return value; } } } In this version of the example, notice how the Enumerator class is nested within the LinkedList class. There is a real elegance to defining the helper class so close to where it is used by the containing class. [4] Of course, if you compiled this example you'd find that the Enumerator member class is compiled to a file named LinkedList$Enumerator.class--while one class is nested within the other in source code form, the same is not true of their compiled byte-code forms. [4] John Rose, the author of Sun's inner class specification, points out that the advantages of inner classes are not only their elegance, but also their "conciseness, expressiveness, and modularity." He says, "Even prosy-minded programmers who don't care a fig for prissy elegance...will appreciate the fact that they can define their adapter classes right next to the code that needs them, and that they won't have to manually wire the adapter to the main object...and that they won't have to pollute the name space of the package..." Notice that no instance of the containing LinkedList class is passed to the Enumerator() constructor of the member class. A member class can refer to the members of its enclosing class implicitly; no explicit reference is necessary. Also note that the Enumerator class makes use of the head field of the enclosing class, even though head is declared private. Because the member class is defined within the enclosing class, it is "inside" the class as far as the definition of private fields and methods is concerned. In general, member classes, as well as local and anonymous classes can use the private fields and methods (and classes!) of their containing class. Similarly, a containing class can use the private fields, methods, and classes of the classes it contains. And any two classes that are enclosed by the same third class can access each other's private members. [5] [5] As noted earlier, however, bugs in javac in current versions of JDK 1.1 prevent this kind of access to private members. Until these bugs are fixed, you should use use package visibility instead of private visibility.
How Member Classes Work The Enumerator member class of LinkedList can refer to the head field of LinkedList because every instance of a member class implicitly refers to an instance of the class that contains it--this is one of the fundamental features of member classes. It works because the compiler automatically inserts a private field in the member class to hold the required reference to the containing object. The compiler also automatically inserts a hidden argument to all constructors of a member class and passes the containing object as the value of this argument. [6] Once the compiler automatically adds this private field and constructor argument to the code in Example 5.4, you can see that we end up with code very much like what we saw in Example 5.3! [6] If you're curious about this, use javap -p to disassemble the class file of a member class. It shows you both the inserted private field and the extra constructor argument. Because the Java Virtual Machine has no notion of inner classes, the Java 1.1 compiler also must take special action
http://localhost/java/javaref/javanut/ch05_03.htm (3 of 7) [20/12/2001 11:00:06]
[Chapter 5] 5.3 Member Classes
to allow member classes (and local and anonymous classes) to use the private fields and methods in their enclosing classes (and vice versa). When a private field or method is used in a way that is allowed in Java 1.1, but is not allowed by the Java interpreter, the compiler automatically inserts a special accessor method to allow the access.
New Syntax for Member Classes The most important feature of a member class is that it can implicitly refer to fields in its containing object. We saw this in the following constructor from Example 5.4: public Enumerator() { current = head; } In this example, head is a field of the LinkedList class, and we assign it to the current field of the Enumerator class. What if we want to make these references explicit? We could try code like this: public Enumerator() { this.current = this.head; } This code does not compile, however. this.current is fine; it is an explicit reference to the current field in the newly created Enumerator object. It is the this.head expression that causes the problem--it refers to a field named head in the Enumerator object. There is no such field, so the compiler generates an error. To prevent this problem, Java 1.1 defines new syntax for explicitly referring to the containing instance of the current instance of a member class. If we wanted to be explicit in our constructor, we'd use the new syntax like this: public Enumerator() { this.current = LinkedList.this.head; } Similarly, we can use LinkedList.this to refer to the containing LinkedList object itself. In general, the syntax is classname.this, where classname is the name of a containing class. Note that member classes can themselves contain member classes, nested to any depth, and no member class can have the same name as any containing class. Thus, the use of the class name prepended to this is a perfectly general way to refer to any containing instance, as the following nested class example demonstrates: public class A { public String name = "a"; public class B { public String name = "b"; public class C { public String name = "c"; public void print_names() { System.out.println(name); System.out.println(this.name); System.out.println(C.this.name); System.out.println(B.this.name); System.out.println(A.this.name); } } } }
// // // // //
"c": "c": "c": "b": "a":
name name name name name
field field field field field
of of of of of
class class class class class
C C C B A
Another new piece of Java 1.1 syntax has to do with the way member classes are created. As we've seen, member classes work the way they do because the compiler automatically adds an argument to each member class constructor. This argument passes a reference to the containing instance to the newly created member instance. Now http://localhost/java/javaref/javanut/ch05_03.htm (4 of 7) [20/12/2001 11:00:06]
[Chapter 5] 5.3 Member Classes
look again at our definition of the enumerate() method in Example 5.4: public Enumeration enumerate() { return new Enumerator(); } Nowhere in this new expression do we specify what the containing instance of the new Enumerator instance should be. In this case, the this object is used as the containing instance, which is what you would expect to happen. It is also what you want to occur in most cases. Nevertheless, Java 1.1 supports a new syntax that lets you explicitly specify the containing instance when creating an instance of a member class. We can make our method more explicit by using the following code: public Enumeration enumerate() { return this.new Enumerator(); } The syntax is containing_instance .new, where containing_instance is an expression that evaluates to an instance of the class that defines the desired member class. Let's look at another example of this syntax. Recall that we declared the Enumerator member class to be private in Example 5.4. We did this for reasons of modularity and encapsulation. Suppose, however, that we had given Enumerator package visibility. In that case, it would be accessible outside of the LinkedList class, and we could instantiate our own copy of it. In order to create an instance of the member class LinkedList.Enumerator, however, we must specify the instance of LinkedList that contains it (and is implicitly passed to its constructor). Our code might look like the following: // First create a linked list, and add elements to it (omitted). LinkedList list = new LinkedList(); // Create an enumerator for the linked list. Note the syntax of the // 'new' expression. Enumerator e = list.new Enumerator(); As a more complex example, consider the following lines of code used to create an instance of class C nested within an instance of class B nested within an instance of class A: A a = new A(); A.B b = a.new B(); A.B.C c = b.new C(); c.print_names();
// // // //
Create Create Create Invoke
an instance an instance an instance a method of
of A. of B within the instance of A. of C within the instance of B. the instance of c.
Note that in the new expressions we name the class to be created relative to the instance that will contain it. That is, we say b.new C(), not b.new A.B.C() . There is one final piece of new Java 1.1 syntax related to member class instantiation and initialization. Before we consider it, however, let me point out that you should rarely, if ever, need to use this syntax. It represents one of the pathological cases that snuck into the language along with all the elegant features of inner classes. The new syntax for the new operator described above allows us to specify the containing instance that is passed to the constructor of a member class. There is one circumstance in which a constructor is invoked without the use of the new operator--when it is invoked with the super keyword from a subclass constructor. As strange as it may seem, it is possible for a top-level class to extend a member class. This means that the subclass does not have a containing instance, but that its superclass does. When the subclass constructor invokes the superclass constructor, it must specify the containing instance. It does this by prepending the containing instance and a period to the super keyword. If we had not declared our Enumerator class to be a private member of LinkedList, then we could subclass it. Although it is not clear why we would want to do so, we could write code like the following:
http://localhost/java/javaref/javanut/ch05_03.htm (5 of 7) [20/12/2001 11:00:06]
[Chapter 5] 5.3 Member Classes
// A top-level class that extends a member class class SpecialEnumerator extends LinkedList.Enumerator { // The constructor must take the LinkedList argument explicitly, // and then must pass it implicitly to the superclass constructor // using the new 'super' syntax. public SpecialEnumerator(LinkedList l) { l.super(); } // Here we override one or the other of the LinkedList.Enumerator // methods to have some kind of special behavior. . . . }
Scope Versus Inheritance Having noted that a top-level class can extend a member class, it is important to point out that with the introduction of member classes there are two entirely separate hierarchies that must be considered for any class. The first is the class hierarchy, from superclass to subclass, that defines the fields that a member class inherits. The second is the containment hierarchy, from containing class to contained class, that defines the fields that are in the scope of (and are therefore accessible to) the member class. The two hierarchies are entirely distinct from each other, and it is important that you do not confuse them. This should not be a problem if you refrain from creating name conflicts where a field or method in a superclass has the same name as a field or method in a containing class. If such a name conflict does arise, however, the inherited field or method hides (i.e., takes precedence over) the field or method of the same name in the containing class or classes. This behavior is logical because when a class inherits a field or method, that field or method effectively becomes part of that class. Therefore, inherited fields and methods are in the scope of the class that inherits them, and take precedence over fields and methods by the same name in enclosing scopes. Because this can be quite confusing, Java does not leave it to chance that you get it right! Whenever there is a name conflict between an inherited field or method and a field or method in a containing class, Java 1.1 requires that you explicitly specify which one you mean. For example, if a member class B inherits a field named x and is contained within a class A that also defines a field named x, you must use this.x to specify the inherited field, or A.this.x to specify the field in the containing class. An attempt to use the field x without an explicit specification of the desired instance causes a compilation error. A good way to prevent confusion between the class hierarchy and the containment hierarchy is to avoid deep containment hierarchies. If a class is nested more than two levels deep, it is probably going to cause more confusion than it is worth. Furthermore, if a class has a deep class hierarchy (i.e., if it has many superclass ancestors), consider defining it as a top-level class rather than as a member class.
Restrictions on Member Classes There are two important restrictions on member classes. First, they cannot have the same name as any containing class or package. This is an important rule, and one that is not shared by fields and methods. Second, member classes, like all inner classes, cannot contain any static members (fields, methods, or classes). The justification for this restriction is that static fields, methods, and classes are "top level" constructs, and it is therefore reasonable that they only be defined at the "top level"--i.e., within top-level classes. Defining a static, top-level member within a non-top-level member class would simply promote confusion and bad programming style. It is clearer (and therefore required) to define all static members within a top-level class. (Which may be a nested top-level class, of course.)
http://localhost/java/javaref/javanut/ch05_03.htm (6 of 7) [20/12/2001 11:00:06]
[Chapter 5] 5.3 Member Classes
Member Classes and Visibility Modifiers A member class, like any member of a class, may be assigned one of three visibility levels: public, [7] protected, or private. If none of these visibility modifiers is specified, the default "package" visibility is used. However, as mentioned earlier, there have been no changes to the Java Virtual Machine to support member classes, and member classes are compiled to class files just like top-level classes are. As far as the Java interpreter is concerned, therefore, member classes, like top-level classes, can only have public or package visibility. Thus, a member class declared protected is actually treated as a public class, and a member class declared private actually has package visibility. While this is unfortunate, and is something you should be aware of, it does not constitute a major security flaw. [7] Because member classes are nested, and because of their nature as "helper" classes, it is unusual to ever declare a member class public. Note that this does not mean that you should never declare a member class as protected or private. Although the interpreter cannot enforce these visibility attributes, the desired attributes are noted in the class file. This means that any conforming Java 1.1 compiler can enforce the visibility attributes and prevent the member classes from being accessed in unintended ways.
Nested Top-Level Classes and Interfaces
http://localhost/java/javaref/javanut/ch05_03.htm (7 of 7) [20/12/2001 11:00:06]
Local Classes
[Chapter 25] 25.39 java.lang.NoClassDefFoundError (JDK 1.0)
Chapter 25 The java.lang Package
25.39 java.lang.NoClassDefFoundError (JDK 1.0) Signals that the definition of a specified class could not be found. public class NoClassDefFoundError extends LinkageError { // Public Constructors public NoClassDefFoundError(); public NoClassDefFoundError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->NoClassDefFoundError
java.lang.NegativeArraySizeException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_39.htm [20/12/2001 11:00:07]
java.lang.NoSuchFieldError (JDK 1.0)
[Chapter 24] 24.43 java.io.ObjectStreamClass (JDK 1.1)
Chapter 24 The java.io Package
24.43 java.io.ObjectStreamClass (JDK 1.1) This class is used to represent a class that is being serialized. An ObjectStreamClass object contains the name of a class and its unique version identifier. This class does not have a constructor; you should use the static lookup() method to obtain an ObjectStreamClass object for a given Class object. The forClass() instance method performs the opposite operation--it returns the Class object that corresponds to a given ObjectStreamClass. Most applications never need to use this class. public class ObjectStreamClass extends Object implements Serializable { // No Constructor // Class Methods public static ObjectStreamClass lookup(Class cl); // Public Instance Methods public Class forClass(); public String getName(); public long getSerialVersionUID(); public String toString(); // Overrides Object }
Passed To: ObjectInputStream.resolveClass()
Returned By: ObjectStreamClass.lookup()
java.io.ObjectOutputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_43.htm [20/12/2001 11:00:07]
java.io.ObjectStreamException (JDK 1.1)
[Chapter 12] Reflection
Chapter 12
12. Reflection Contents: Obtaining Class and Member Information Invoking a Named Method As noted in Chapter 4, What's New in Java 1.1, the Reflection API allows a Java program to inspect and manipulate itself. The Reflection API comprises the much-expanded Class class in java.lang and the java.lang.reflect package, which represents the members of a class with Method, Constructor, and Field objects. Reflection can be used to obtain information about a class and its members. This is the technique that the JavaBeans "introspection" mechanism uses to determine the properties, events, and methods that are supported by a bean, for example. Reflection can also be used to manipulate objects in Java. You can use the Field class to query and set the values of fields, the Method class to invoke methods, and the Constructor class to create new objects. The examples in this chapter demonstrate both techniques for using the Reflection API.
12.1 Obtaining Class and Member Information Example 12.1 shows a program that uses the Class, Constructor, Field, and Method classes to display information about a specified class. The program's output is similar to the class synopses that appear in the reference section of this book. (You might notice that the names of method arguments are not shown; argument names are not stored in class files, so they are not available through the Reflection API.) Here is the output from using ShowClass on itself: % java ShowClass ShowClass public class ShowClass extends java.lang.Object { // Constructors public ShowClass(); // Fields // Methods public static void main(java.lang.String[]); public static void print_class(java.lang.Class); public static java.lang.String typename(java.lang.Class); public static java.lang.String modifiers(int); public static void print_field(java.lang.reflect.Field); public static void print_method_or_constructor(java.lang.reflect.Member); }
http://localhost/java/javaref/javanut/ch12_01.htm (1 of 4) [20/12/2001 11:00:07]
[Chapter 12] Reflection
The code for this example is quite straightforward. It uses the Class.forName() method to dynamically load the named class, and calls various methods of Class object to look up the superclass, interfaces, and members of the class. The example uses Constructor, Field, and Method objects to obtain information about each member of the class. Example 12.1: Obtaining Class and Member Information with the Reflection API import java.lang.reflect.*; /** A program that displays a class synopsis for the named class. */ public class ShowClass { /** The main method. Print info about the named class. */ public static void main(String[] args) throws ClassNotFoundException { Class c = Class.forName(args[0]); print_class(c); } /** Display the modifiers, name, superclass, and interfaces of a class * or interface. Then go and list all constructors, fields, and methods. */ public static void print_class(Class c) { // Print modifiers, type (class or interface), name, and superclass. if (c.isInterface()) { // The modifiers will include the "interface" keyword here... System.out.print(Modifier.toString(c.getModifiers()) + c.getName()); } else System.out.print(Modifier.toString(c.getModifiers()) + " class " + c.getName() + " extends " + c.getSuperclass().getName()); // Print interfaces or super-interfaces of the class or interface. Class[] interfaces = c.getInterfaces(); if ((interfaces != null) && (interfaces.length > 0)) { if (c.isInterface()) System.out.println(" extends "); else System.out.print(" implements "); for(int i = 0; i < interfaces.length; i++) { if (i > 0) System.out.print(", "); System.out.print(interfaces[i].getName()); } } System.out.println(" {"); // Begin class member listing. // Now look up and display the members of the class. System.out.println(" // Constructors"); Constructor[] constructors = c.getDeclaredConstructors(); for(int i = 0; i < constructors.length; i++) // Display constructors. print_method_or_constructor(constructors[i]); System.out.println(" // Fields"); Field[] fields = c.getDeclaredFields(); // Look up fields. for(int i = 0; i < fields.length; i++) // Display them. print_field(fields[i]); System.out.println(" // Methods"); Method[] methods = c.getDeclaredMethods(); // Look up methods.
http://localhost/java/javaref/javanut/ch12_01.htm (2 of 4) [20/12/2001 11:00:07]
[Chapter 12] Reflection
for(int i = 0; i < methods.length; i++) // Display them. print_method_or_constructor(methods[i]); System.out.println("}"); // End class member listing. } /** Return the name of an interface or primitive type, handling arrays. */ public static String typename(Class t) { String brackets = ""; while(t.isArray()) { brackets += "[]"; t = t.getComponentType(); } return t.getName() + brackets; } /** Return a string version of modifiers, handling spaces nicely. */ public static String modifiers(int m) { if (m == 0) return ""; else return Modifier.toString(m) + " "; } /** Print the modifiers, type, and name of a field. */ public static void print_field(Field f) { System.out.println(" " + modifiers(f.getModifiers()) + typename(f.getType()) + " " + f.getName() + ";"); } /** Print the modifiers, return type, name, parameter types, and exception * type of a method or constructor. Note the use of the Member interface * to allow this method to work with both Method and Constructor objects. */ public static void print_method_or_constructor(Member member) { Class returntype=null, parameters[], exceptions[]; if (member instanceof Method) { Method m = (Method) member; returntype = m.getReturnType(); parameters = m.getParameterTypes(); exceptions = m.getExceptionTypes(); } else { Constructor c = (Constructor) member; parameters = c.getParameterTypes(); exceptions = c.getExceptionTypes(); } System.out.print(" " + modifiers(member.getModifiers()) + ((returntype!=null)? typename(returntype)+" " : "") + member.getName() + "("); for(int i = 0; i < parameters.length; i++) { if (i > 0) System.out.print(", "); System.out.print(typename(parameters[i])); } System.out.print(")"); if (exceptions.length > 0) System.out.print(" throws "); for(int i = 0; i < exceptions.length; i++) { if (i > 0) System.out.print(", "); System.out.print(typename(exceptions[i]));
http://localhost/java/javaref/javanut/ch12_01.htm (3 of 4) [20/12/2001 11:00:07]
[Chapter 12] Reflection
} System.out.println(";"); } }
Formatted Messages
http://localhost/java/javaref/javanut/ch12_01.htm (4 of 4) [20/12/2001 11:00:07]
Invoking a Named Method
[Chapter 3] 3.8 Data Hiding and Encapsulation
Chapter 3 Classes and Objects in Java
3.8 Data Hiding and Encapsulation We started this chapter by describing a class as "a collection of data and methods." One of the important object-oriented techniques that we haven't discussed so far is hiding the data within the class, and making it available only through the methods. This technique is often known as encapsulation, because it seals the class's data (and internal methods) safely inside the "capsule" of the class, where it can be accessed only by trusted users--i.e., by the methods of the class. Why would you want to do this? The most important reason is to hide the internal implementation details of your class. If you prevent programmers from relying on those details, then you can safely modify the implementation without worrying that you will break existing code that uses the class. Another reason for encapsulation is to protect your class against accidental or willful stupidity. A class often contains a number of variables that are interdependent and must be in a consistent state. If you allow a programmer (this may be you yourself) to manipulate those variables directly, she may change one variable without changing important related variables, thus leaving the class in an inconsistent state. If, instead, she had to call a method to change the variable, that method can be sure to do everything necessary to keep the state consistent. Here's another way to think about encapsulation: When all of a class's variables are hidden, the class's methods define the only possible operations that can be performed on objects of that class. Once you have carefully tested and debugged your methods, you can be confident that the class will work as expected. On the other hand, if all the variables can be directly manipulated, the number of possibilities you have to test becomes unmanageable. There are other reasons to hide data, too: ● Internal variables that are visible externally to the class just clutter up your class's API. Keeping visible variables to a minimum keeps your class tidy and elegant. ● If a variable is visible in your class, you have to document it. Save time by hiding it instead!
Visibility Modifiers In most of our examples so far, you've probably noticed the public keyword being used. When applied to a class, it means that the class is visible everywhere. When applied to a method or variable, it means that the method or variable is visible everywhere. To hide variables (or methods, for that matter) you just have to declare them private: public class Laundromat { private Laundry[] dirty; public void wash() { ... } public void dry() { ... }
// // // //
People can use this class. They can't see this internal variable, but they can use these public methods to manipulate the internal variable.
http://localhost/java/javaref/javanut/ch03_08.htm (1 of 4) [20/12/2001 11:00:08]
[Chapter 3] 3.8 Data Hiding and Encapsulation
} A private field of a class is visible only in methods defined within that class. (Or, in Java 1.1, in classes defined within the class.) Similarly, a private method may only be invoked by methods within the class (or methods of classes within the class). Private members are not visible within subclasses, and are not inherited by subclasses as other members are. [11] Of course, non-private methods that invoke private methods internally are inherited and may be invoked by subclasses. [11] Every object does, of course, have its own copy of all fields of all superclasses, including the private fields. The methods defined by the object can never refer to or use the private fields of superclasses, however, and so we say that those fields are not inherited. Besides public and private, Java has two other visibility levels: protected and the default visibility level, "package visibility," which applies if none of the public, private, and protected keywords are used. A protected member of a class is visible within the class where it is defined, of course, and within all subclasses of the class, and also within all classes that are in the same package as that class. You should use protected visibility when you want to hide fields and methods from code that uses your class, but want those fields and methods to be fully accessible to code that extends your class. The default package visibility is more restrictive than protected, but less restrictive than private. If a class member is not declared with any of the public, private, or protected keywords, then it is visible only within the class that defines it and within classes that are part of the same package. It is not visible to subclasses unless those subclasses are part of the same package. A note about packages: A package is a group of related and possibly cooperating classes. All non-private members of all classes in the package are visible to all other classes in the package. This is okay because the classes are assumed to know about, and trust, each other. [12] The only time difficulty arises is when you write programs without a package statement. These classes are thrown into a default package with other package-less classes, and all their non-private members are visible throughout the package. (The default package usually consists of all classes in the current working directory.) [12] If you're a C++ programmer, you can say that classes within the same package are friend-ly to each other. There is an important point to make about subclass access to protected members. A subclass inherits the protected members of its superclass, but it can only access those members through instances of itself, not directly in instances of the superclass. Suppose, for example, that A, B, and C are public classes, each defined in a different package, and that a, b, and c are instances of those classes. Let B be a subclass of A, and C be a subclass of B. Now, if A has a protected field x, then the class B inherits that field, and its methods can use this.x, b.x and c.x. But it cannot access a.x. Similarly, if A has a protected method f(), then the methods of class B can invoke this.f(), b.f(), and c.f(), but they cannot invoke a.f(). Table 3.1 shows the circumstances under which class members of the various visibility types are accessible to other classes. Table 3.1: Class Member Accessibility Accessible to:
public protected package private
Same class Class in same package
yes yes
yes yes
yes yes
yes no
Subclass in different package yes Non-subclass, different package yes
yes no
no no
no no
http://localhost/java/javaref/javanut/ch03_08.htm (2 of 4) [20/12/2001 11:00:08]
[Chapter 3] 3.8 Data Hiding and Encapsulation
The details of member visibility in Java can become quite confusing. Here are some simple rules of thumb for using visibility modifiers: ● Use public only for methods and constants that form part of the public API of the class. Certain very important or very frequently used fields may also be public, but it is common practice to make fields non-public and encapsulate them with public accessor methods. ● Use protected for fields and methods that aren't necessary to use the class, but that may be of interest to anyone creating a subclass as part of a different package. ● Use the default package visibility for fields and methods that you want to be hidden outside of the package, but which you want cooperating classes within the same package to have access to. ● Use private for fields and methods that are only used inside the class and should be hidden everywhere else. Note that you can't take advantage of package visibility unless you use the package statement to group your related classes into packages. See Chapter 13, Java Syntax, Java Syntax, for a table that summarizes the Java visibility modifiers and other modifiers.
Data Access Methods In the Circle example we've been using, we've declared the circle position and radius to be public fields. In fact, the Circle class is one where it may well make sense to keep those visible--it is a simple enough class, with no dependencies between the variables. On the other hand, suppose we wanted to impose a maximum radius on objects of the Circle class. Then it would be better to hide the r variable so that it could not be set directly. Instead of a visible r variable, we'd implement a setRadius() method that verifies that the specified radius isn't too large and then sets the r variable internally. Example 3.14 shows how we might implement Circle with encapsulated data and a restriction on radius size. For convenience, we use protected fields for the radius and position variables. This means that subclasses of Circle, or cooperating classes within the shapes package are able to access these variables directly. To any other classes, however, the variables are hidden. Also, note the private constant and method used to check whether a specified radius is legal. And finally, notice the public methods that allow you to set and query the values of the instance variables. Example 3.14: Hiding Variables in the Circle Class package shapes; // Specify a package for the class. public class Circle { // Note that the class is still public! protected double x, y; // Position is hidden, but visible to subclasses. protected double r; // Radius is hidden, but visible to subclasses. private static final double MAXR = 100.0; // Maximum radius (constant). private boolean check_radius(double r) { return (r Throwable(Serializable)->Exception->CloneNotSupportedException
Thrown By: Object.clone()
java.lang.ClassNotFoundException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_14.htm [20/12/2001 11:00:11]
java.lang.Cloneable (JDK 1.0)
[Chapter 24] 24.69 java.io.Writer (JDK 1.1)
Chapter 24 The java.io Package
24.69 java.io.Writer (JDK 1.1) This abstract class is the superclass of all character output streams. It is an analog to OutputStream, which is the superclass of all byte output streams. Writer defines the basic write(), flush(), and close() methods that all character output streams provide. The five versions of the write() method write a single character, a character array or subarray, or a string or substring to the destination of the stream. The most general version of this method--the one that writes a specified portion of a character array--is abstract and must be implemented by all subclasses. By default, the other write() methods are implemented in terms of this abstract one. The flush() method is another abstract method that all subclasses must implement. It should force any output buffered by the stream to be written to its destination. If that destination is itself a character or byte output stream, it should invoke the flush() method of the destination stream as well. The close() method is also abstract. Subclasses must implement this method so that it flushes and then closes the current stream, and also closes whatever destination stream it is connected to. Once the stream has been closed, any future calls to write() or flush() should throw an IOException. public abstract class Writer extends Object { // Protected Constructors protected Writer(); protected Writer(Object lock); // Protected Instance Variables protected Object lock; // Public Instance Methods public abstract void close() throws IOException; public abstract void flush() throws IOException; public void write(int c) throws IOException; public void write(char[] cbuf) throws IOException; public abstract void write(char[] cbuf, int off, int len) throws IOException; public void write(String str) throws IOException; public void write(String str, int off, int len) throws IOException; }
Extended By: BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
http://localhost/java/javaref/javanut/ch24_69.htm (1 of 2) [20/12/2001 11:00:11]
[Chapter 24] 24.69 java.io.Writer (JDK 1.1)
Passed To: BufferedWriter(), CharArrayWriter.writeTo(), FilterWriter(), PrintWriter()
Type Of: FilterWriter.out
java.io.WriteAbortedException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_69.htm (2 of 2) [20/12/2001 11:00:11]
The java.lang Package
[Chapter 28] 28.6 java.net.DatagramSocket (JDK 1.0)
Chapter 28 The java.net Package
28.6 java.net.DatagramSocket (JDK 1.0) This class defines a socket that can receive and send unreliable datagram packets over the network using the UDP protocol. A datagram is a very low-level networking interface: it is simply an array of bytes sent over the network. A datagram does not implement any kind of stream-based communication protocol, and there is no connection established between the sender and the receiver. Datagram packets are called "unreliable" because the protocol does not make any attempt to ensure that they arrived or to resend them if they did not. Thus, packets sent through a DatagramSocket are not guaranteed to arrive in the order sent, or to arrive at all. On the other hand, this low-overhead protocol makes datagram transmission very fast. If a port is specified when the DatagramSocket is created, that port is used; otherwise, the system assigns a port. getLocalPort() returns the port number in use. send() sends a DatagramPacket through the socket. The packet must contain the destination address to which it should be sent. receive() waits for data to arrive at the socket and stores it, along with the address of the sender, into the specified DatagramPacket. close() closes the socket and frees the port it used for reuse. Once close() has been called, the DatagramSocket should not be used again. See Socket and URL for higher-level interfaces to networking. public class DatagramSocket extends Object { // Public Constructors public DatagramSocket() throws SocketException; public DatagramSocket(int port) throws SocketException; 1.1public DatagramSocket(int port, InetAddress laddr) throws SocketException; // Public Instance Methods public void close(); 1.1public InetAddress getLocalAddress(); public int getLocalPort(); 1.1public synchronized int getSoTimeout() throws SocketException; public synchronized void receive(DatagramPacket p) throws IOException; public void send(DatagramPacket p) throws IOException; 1.1public synchronized void setSoTimeout(int timeout) throws SocketException; }
Extended By: MulticastSocket
java.net.DatagramPacket (JDK 1.0)
java.net.DatagramSocketImpl (JDK 1.1)
http://localhost/java/javaref/javanut/ch28_06.htm [20/12/2001 11:00:11]
[Chapter 31] 31.8 java.util.zip.DeflaterOutputStream (JDK 1.1)
Chapter 31 The java.util.zip Package
31.8 java.util.zip.DeflaterOutputStream (JDK 1.1) This class is a subclass of java.io.FilterOutputStream; it "filters" a stream of data by compressing ("deflating") it and then writes the compressed data to another output stream. To create a DeflaterOutputStream, you must specify the stream that it is to write to, and also a Deflater object that is to perform the compression. You can set various options on the Deflater object to specify just what type of compression is to be performed. Once a DeflaterOutputStream is created, its write() and close() methods are the same as those of other output streams. The InflaterInputStream class can be used to read data written with the DeflaterOutputStream. Note that a DeflaterOutputStream writes raw compressed data; applications often prefer one of its subclasses, GZIPOutputStream or ZipOutputStream, which wraps the raw compressed data within a standard file format. public class DeflaterOutputStream extends FilterOutputStream { // Public Constructors public DeflaterOutputStream(OutputStream out, Deflater def, int size); public DeflaterOutputStream(OutputStream out, Deflater def); public DeflaterOutputStream(OutputStream out); // Protected Instance Variables protected byte[] buf; protected Deflater def; // Public Instance Methods public void close() throws IOException; // Overrides FilterOutputStream public void finish() throws IOException; public void write(int b) throws IOException; // Overrides FilterOutputStream public void write(byte[] b, int off, int len) throws IOException; // Overrides FilterOutputStream // Protected Instance Methods protected void deflate() throws IOException; }
Hierarchy: Object->OutputStream->FilterOutputStream->DeflaterOutputStream
Extended By: GZIPOutputStream, ZipOutputStream
java.util.zip.Deflater (JDK 1.1)
java.util.zip.GZIPInputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_08.htm (1 of 2) [20/12/2001 11:00:11]
[Chapter 31] 31.8 java.util.zip.DeflaterOutputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_08.htm (2 of 2) [20/12/2001 11:00:11]
[Chapter 24] 24.18 java.io.FileInputStream (JDK 1.0)
Chapter 24 The java.io Package
24.18 java.io.FileInputStream (JDK 1.0) This class is a subclass of InputStream that reads bytes from a file specified by name or by a File or FileDescriptor object. read() reads a byte or array of bytes from the file. It returns -1 when the end of file has been reached. To read binary data, you typically use this class in conjunction with a BufferedInputStream and DataInputStream. To read text, you typically use it with an InputStreamReader and BufferedReader. Call close() to close the file when input is no longer needed. public class FileInputStream extends InputStream { // Public Constructors public FileInputStream(String name) throws FileNotFoundException; public FileInputStream(File file) throws FileNotFoundException; public FileInputStream(FileDescriptor fdObj); // Public Instance Methods public native int available() throws IOException; // Overrides InputStream public native void close() throws IOException; // Overrides InputStream public final FileDescriptor getFD() throws IOException; public native int read() throws IOException; // Defines InputStream public int read(byte[] b) throws IOException; // Overrides InputStream public int read(byte[] b, int off, int len) throws IOException; // Overrides InputStream public native long skip(long n) throws IOException; // Overrides InputStream // Protected Instance Methods protected void finalize() throws IOException; // Overrides Object }
Hierarchy: Object->InputStream->FileInputStream
java.io.FileDescriptor (JDK 1.0)
java.io.FileNotFoundException (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_18.htm [20/12/2001 11:00:12]
[Chapter 24] 24.20 java.io.FileOutputStream (JDK 1.0)
Chapter 24 The java.io Package
24.20 java.io.FileOutputStream (JDK 1.0) This class is a subclass of OutputStream that writes data to a file specified by name, or by a File or FileDescriptor object. write() writes a byte or array of bytes to the file. To write binary data, you typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream. To write text, you typically use it with a PrintWriter, BufferedWriter, and an OutputStreamWriter. Use close() to close a FileOutputStream when no further output will be written to it. public class FileOutputStream extends OutputStream { // Public Constructors public FileOutputStream(String name) throws IOException; 1.1 public FileOutputStream(String name, boolean append) throws IOException; public FileOutputStream(File file) throws IOException; public FileOutputStream(FileDescriptor fdObj); // Public Instance Methods public native void close() throws IOException; // Overrides OutputStream public final FileDescriptor getFD() throws IOException; public native void write(int b) throws IOException; // Defines OutputStream public void write(byte[] b) throws IOException; // Overrides OutputStream public void write(byte[] b, int off, int len) throws IOException; // Overrides OutputStream // Protected Instance Methods protected void finalize() throws IOException; // Overrides Object }
Hierarchy: Object->OutputStream->FileOutputStream
java.io.FileNotFoundException (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_20.htm [20/12/2001 11:00:12]
java.io.FileReader (JDK 1.1)
[Chapter 31] 31.9 java.util.zip.GZIPInputStream (JDK 1.1)
Chapter 31 The java.util.zip Package
31.9 java.util.zip.GZIPInputStream (JDK 1.1) This class is a subclass of InflaterInputStream that reads and uncompresses data compressed in gzip format. To create a GZIPInputStream, you must simply specify the InputStream it is to read compressed data from, and optionally specify a buffer size for the internal decompression buffer. Once a GZIPInputStream is created, you can use the read() and close() methods as you would with any input stream. public class GZIPInputStream extends InflaterInputStream { // Public Constructors public GZIPInputStream(InputStream in, int size) throws IOException; public GZIPInputStream(InputStream in) throws IOException; // Constants public static final int GZIP_MAGIC; // Protected Instance Variables protected CRC32 crc; protected boolean eos; // Public Instance Methods public void close() throws IOException; // Overrides FilterInputStream public int read(byte[] buf, int off, int len) throws IOException; // Overrides InflaterInputStream }
Hierarchy: Object->InputStream->FilterInputStream->InflaterInputStream->GZIPInputStream
java.util.zip.DeflaterOutputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_09.htm [20/12/2001 11:00:12]
java.util.zip.GZIPOutputStream (JDK 1.1)
[Chapter 31] 31.10 java.util.zip.GZIPOutputStream (JDK 1.1)
Chapter 31 The java.util.zip Package
31.10 java.util.zip.GZIPOutputStream (JDK 1.1) This class is a subclass of DeflaterOutputStream that compresses and writes data using the gzip file format. To create a GZIPOutputStream, you must specify the OutputStream that it is to write to, and may optionally specify a size for the internal compression buffer. Once the GZIPOutputStream is created, you can use the write() and close() methods as you would any other output stream. public class GZIPOutputStream extends DeflaterOutputStream { // Public Constructors public GZIPOutputStream(OutputStream out, int size) throws IOException; public GZIPOutputStream(OutputStream out) throws IOException; // Protected Instance Variables protected CRC32 crc; // Public Instance Methods public void close() throws IOException; // Overrides DeflaterOutputStream public void finish() throws IOException; // Overrides DeflaterOutputStream public synchronized void write(byte[] buf, int off, int len) throws IOException; // Overrides DeflaterOutputStream }
Hierarchy: Object->OutputStream->FilterOutputStream->DeflaterOutputStream->GZIPOutputStream
java.util.zip.GZIPInputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_10.htm [20/12/2001 11:00:12]
java.util.zip.Inflater (JDK 1.1)
[Chapter 24] 24.46 java.io.OutputStream (JDK 1.0)
Chapter 24 The java.io Package
24.46 java.io.OutputStream (JDK 1.0) This abstract class is the superclass of all output streams. It defines the basic output methods that all output stream classes provide. write() writes a single byte or an array or subarray of bytes. flush() forces any buffered output to be written. close() closes the stream and frees up any system resources associated with it. The stream may not be used once close() has been called. See also Writer. public abstract class OutputStream extends Object { // Default Constructor: public OutputStream() // Public Instance Methods public void close() throws IOException; public void flush() throws IOException; public abstract void write(int b) throws IOException; public void write(byte[] b) throws IOException; public void write(byte[] b, int off, int len) throws IOException; }
Extended By: ByteArrayOutputStream, FileOutputStream, FilterOutputStream, ObjectOutputStream, PipedOutputStream
Passed To: BufferedOutputStream(), ByteArrayOutputStream.writeTo(), CheckedOutputStream(), DataOutputStream(), DeflaterOutputStream(), FilterOutputStream(), GZIPOutputStream(), ObjectOutputStream(), OutputStreamWriter(), PrintStream(), PrintWriter(), Properties.save(), Runtime.getLocalizedOutputStream(), ZipOutputStream()
Returned By: Process.getOutputStream(), Runtime.getLocalizedOutputStream(), Socket.getOutputStream(), SocketImpl.getOutputStream(), URLConnection.getOutputStream()
http://localhost/java/javaref/javanut/ch24_46.htm (1 of 2) [20/12/2001 11:00:13]
[Chapter 24] 24.46 java.io.OutputStream (JDK 1.0)
Type Of: FilterOutputStream.out
java.io.OptionalDataException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_46.htm (2 of 2) [20/12/2001 11:00:13]
java.io.OutputStreamWriter (JDK 1.1)
[Chapter 24] 24.57 java.io.Reader (JDK 1.1)
Chapter 24 The java.io Package
24.57 java.io.Reader (JDK 1.1) This abstract class is the superclass of all character input streams. It is an analog to InputStream, which is the superclass of all byte input streams. Reader defines the basic methods that all character output streams provide. read() returns a single character or an array (or subarray) of characters, blocking if necessary. It returns -1 if the end of the stream has been reached. ready() returns true if there are characters available for reading. If ready() returns true, the next call to read() is guaranteed not to block. close() closes the character input stream. skip() skips a specified number of characters in the input stream. If markSupported() returns true, then mark() "marks" a position in the stream and, if necessary, creates a look-ahead buffer of the specified size. Future calls to reset() restore the stream to the marked position, if they occur within the specified look-ahead limit. Note that not all stream types support this mark-and-reset functionality. To create a subclass of Reader, you need only implement the three-argument version of read() and close(). Most subclasses implement additional methods as well, however. public abstract class Reader extends Object { // Protected Constructors protected Reader(); protected Reader(Object lock); // Protected Instance Variables protected Object lock; // Public Instance Methods public abstract void close() throws IOException; public void mark(int readAheadLimit) throws IOException; public boolean markSupported(); public int read() throws IOException; public int read(char[] cbuf) throws IOException; public abstract int read(char[] cbuf, int off, int len) throws IOException; public boolean ready() throws IOException; public void reset() throws IOException; public long skip(long n) throws IOException; }
http://localhost/java/javaref/javanut/ch24_57.htm (1 of 2) [20/12/2001 11:00:13]
[Chapter 24] 24.57 java.io.Reader (JDK 1.1)
Extended By: BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader
Passed To: BufferedReader(), FilterReader(), LineNumberReader(), PushbackReader(), StreamTokenizer()
Type Of: FilterReader.in
java.io.RandomAccessFile (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_57.htm (2 of 2) [20/12/2001 11:00:13]
java.io.SequenceInputStream (JDK 1.0)
[Chapter 24] 24.64 java.io.StringWriter (JDK 1.1)
Chapter 24 The java.io Package
24.64 java.io.StringWriter (JDK 1.1) This class is a character output stream that uses an internal StringBuffer object as the destination of the characters written to the stream. When you create a StringWriter, you may optionally specify an initial size for the StringBuffer, but you do not specify the StringBuffer itself--it is managed internally by the StringWriter, and grows as necessary to accommodate the characters written to it. StringWriter defines the standard write(), flush(), and close() methods that all Writer subclasses do, and also defines two methods to obtain the characters that have been written into the stream's internal buffer. toString() returns the contents of the internal buffer as a String, and getBuffer() returns the buffer itself. Note that getBuffer() returns a reference to the actual internal buffer, not a copy of it, so any changes you make to the buffer are reflected in subsequent calls to toString(). StringWriter is quite similar to CharArrayWriter, but does not have a byte stream analog. public class StringWriter extends Writer { // Public Constructor public StringWriter(); // Protected Constructor protected StringWriter(int initialSize); // Public Instance Methods public void close(); // Defines Writer public void flush(); // Defines Writer public StringBuffer getBuffer(); public String toString(); // Overrides Object public void write(int c); // Overrides Writer public void write(char[] cbuf, int off, int len); // Defines Writer public void write(String str); // Overrides Writer public void write(String str, int off, int len); // Overrides Writer }
Hierarchy: Object->Writer->StringWriter
java.io.StringReader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_64.htm [20/12/2001 11:00:13]
java.io.SyncFailedException (JDK 1.1)
[Chapter 31] 31.17 java.util.zip.ZipOutputStream (JDK 1.1)
Chapter 31 The java.util.zip Package
31.17 java.util.zip.ZipOutputStream (JDK 1.1) This class is a subclass of DeflaterOutputStream that writes data in ZIP file format to an output stream. Before writing any data to the ZipOutputStream, you must begin an entry within the ZIP file with putNextEntry(). The ZipEntry object passed to this method should specify at least a name for the entry. Once you have begun an entry with putNextEntry(), you can write the contents of that entry with the write() methods. When you reach the end of an entry, you can begin a new one by calling putNextEntry() again, or you can close the current entry with closeEntry(), or you can close the stream itself with close(). Before beginning an entry with putNextEntry(), you can set the compression method and level with setMethod() and setLevel(). The constants DEFLATED and STORED are the two legal values for setMethod(). If you use STORED, the entry is stored in the ZIP file without any compression. If you use DEFLATED, you can also specify the compression speed/strength trade-off by passing a number from 1 to 9 to setLevel(), where 9 gives the strongest and slowest level of compression. You can also use the constants Deflater.BEST_SPEED, Deflater.BEST_COMPRESSION, and Deflater.DEFAULT_COMPRESSION with the setLevel() method. Note that if you are simply storing an entry without compression, the ZIP file format requires that you specify, in advance, the entry size and CRC-32 checksum in the ZipEntry object for the entry. An exception is thrown if these values are not specified or are incorrectly specified. public class ZipOutputStream extends DeflaterOutputStream { // Public Constructor public ZipOutputStream(OutputStream out); // Constants public static final int DEFLATED; public static final int STORED; // Public Instance Methods public void close() throws IOException; // Overrides DeflaterOutputStream public void closeEntry() throws IOException; public void finish() throws IOException; // Overrides DeflaterOutputStream public void putNextEntry(ZipEntry e) throws IOException; public void setComment(String comment); public void setLevel(int level); public void setMethod(int method); public synchronized void write(byte[] b, int off, int len) throws IOException; // Overrides DeflaterOutputStream
http://localhost/java/javaref/javanut/ch31_17.htm (1 of 2) [20/12/2001 11:00:14]
[Chapter 31] 31.17 java.util.zip.ZipOutputStream (JDK 1.1)
}
Hierarchy: Object->OutputStream->FilterOutputStream->DeflaterOutputStream->ZipOutputStream
java.util.zip.ZipInputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_17.htm (2 of 2) [20/12/2001 11:00:14]
Class, Method, and Field Index
[Chapter 31] 31.16 java.util.zip.ZipInputStream (JDK 1.1)
Chapter 31 The java.util.zip Package
31.16 java.util.zip.ZipInputStream (JDK 1.1) This class is a subclass of InflaterInputStream that reads the entries of a ZIP file in sequential order. A ZipInputStream is created by specifying the InputStream from which it is to read the contents of the ZIP file. Once the ZipInputStream is created, the getNextEntry() method is used to begin reading of data from the next entry in the ZIP file. This method must be called before read() is called to begin reading of the first entry. Note that getNextEntry() returns a ZipEntry object that describes the entry being read. Also note that getNextEntry() returns null when there are no more entries to be read from the ZIP file. The read() methods of ZipInputStream read until the end of the current entry and then return -1 indicating that there are no more data to read. To continue with the next entry in the ZIP file, you must call getNextEntry() again. Similarly, the skip() method only skips bytes within the current entry. closeEntry() can be called to skip the remaining data in the current entry, but it is usually easier simply to call getNextEntry() to begin the next entry. public class ZipInputStream extends InflaterInputStream { // Public Constructor public ZipInputStream(InputStream in); // Public Instance Methods public void close() throws IOException; // Overrides FilterInputStream public void closeEntry() throws IOException; public ZipEntry getNextEntry() throws IOException; public int read(byte[] b, int off, int len) throws IOException; // Overrides InflaterInputStream public long skip(long n) throws IOException; // Overrides InflaterInputStream }
Hierarchy: Object->InputStream->FilterInputStream->InflaterInputStream->ZipInputStream
java.util.zip.ZipFile (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_16.htm [20/12/2001 11:00:14]
java.util.zip.ZipOutputStream (JDK 1.1)
[Chapter 29] 29.4 java.text.CollationElementIterator (JDK 1.1)
Chapter 29 The java.text Package
29.4 java.text.CollationElementIterator (JDK 1.1) A CollationElementIterator object is returned by the getCollationElementIterator() method of the RuleBasedCollator object. The purpose of this class is to allow a program to iterate (with the next() method) through the characters of a string, returning ordering values for each of the "collation keys" in the string. Note that collation keys are not exactly the same thing as characters. In the traditional Spanish collation order, for example, the two-character sequence "ch" is treated as a single collation key that comes alphabetically between the letters "c" and "d." The value returned by the next() method is the collation order of the next collation key in the string. This numeric value can be directly compared to the value returned by next() for other CollationElementIterator objects. The value returned by next() can also be decomposed into primary, secondary, and tertiary ordering values with the static methods of this class. This class is used by RuleBasedCollator to implement its compare() method, and to create CollationKey objects. Few applications ever need to use it directly. public final class CollationElementIterator extends Object { // No Constructor // Constants public static final int NULLORDER; // Class Methods public static final int primaryOrder(int order); public static final short secondaryOrder(int order); public static final short tertiaryOrder(int order); // Public Instance Methods public int next(); public void reset(); }
http://localhost/java/javaref/javanut/ch29_04.htm (1 of 2) [20/12/2001 11:00:14]
[Chapter 29] 29.4 java.text.CollationElementIterator (JDK 1.1)
Returned By: RuleBasedCollator.getCollationElementIterator()
java.text.ChoiceFormat (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_04.htm (2 of 2) [20/12/2001 11:00:14]
java.text.CollationKey (JDK 1.1)
[Chapter 29] 29.5 java.text.CollationKey (JDK 1.1)
Chapter 29 The java.text Package
29.5 java.text.CollationKey (JDK 1.1) CollationKey objects are used to compare strings more quickly than is possible with Collation.compare(). Objects of this class are returned by Collation.getCollationKey(). To compare two CollationKey objects, invoke the compareTo() method of key A, passing the key B as an argument (both CollationKey objects must be created through the same Collation object). The return value of this method is less than zero if the key A is collated before the key B. It is equal to zero if they are equivalent for the purposes of collation, and it is greater than zero if the key A is collated after the key B. Use getSourceString() to obtain the string represented by a CollationKey. public final class CollationKey extends Object { // No Constructor // Public Instance Methods public int compareTo(CollationKey target); public boolean equals(Object target); // Overrides Object public String getSourceString(); public int hashCode(); // Overrides Object public byte[] toByteArray(); }
Passed To: CollationKey.compareTo()
Returned By: Collator.getCollationKey(), RuleBasedCollator.getCollationKey()
java.text.CollationElementIterator (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_05.htm (1 of 2) [20/12/2001 11:00:14]
java.text.Collator (JDK 1.1)
[Chapter 29] 29.5 java.text.CollationKey (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_05.htm (2 of 2) [20/12/2001 11:00:14]
[Chapter 29] 29.6 java.text.Collator (JDK 1.1)
Chapter 29 The java.text Package
29.6 java.text.Collator (JDK 1.1) This class is used to compare, order, and sort strings in a way that is appropriate for the default locale or some other specified locale. Because it is an abstract class, it cannot be instantiated directly. Instead, you must use the static getInstance() method to obtain an instance of a Collator subclass that is appropriate for the default or specified locale. You can use getAvailableLocales() to determine whether a Collator object is available for a desired locale. Once an appropriate Collator object has been obtained, you can use the compare() method to compare strings. The possible return values of this method are -1, 0, and 1, which indicate, respectively, that the first string is collated before the second, that the two are equivalent for collation purposes, and that the first string is collated after the second. The equals() method is a convenient shortcut for testing two strings for collation equivalence. When sorting an array of strings, each string in the array is typically compared more than once. Using the compare() method in this case is inefficient. A more efficient method for comparing strings multiple times is to use getCollationKey() for each string to create CollationKey objects. These objects can then be compared to each other more quickly than the strings themselves could be compared. You can customize the way the Collator object performs comparisons by calling setStrength(). If you pass the constant PRIMARY to this method, the comparison only looks at primary differences in the strings--it compares letters but ignores accents and case differences. If you pass the constant SECONDARY, it ignores case differences but does not ignore accents. And if you pass TERTIARY (the default), the Collator object takes both accents and case differences into account in its comparison. public abstract class Collator extends Object implements Cloneable, Serializable { // Protected Constructor protected Collator(); // Constants public static final int CANONICAL_DECOMPOSITION; public static final int FULL_DECOMPOSITION; public static final int IDENTICAL; public static final int NO_DECOMPOSITION; public static final int PRIMARY; public static final int SECONDARY; public static final int TERTIARY; // Class Methods public static synchronized Locale[] getAvailableLocales(); public static synchronized Collator getInstance(); public static synchronized Collator getInstance(Locale desiredLocale); // Public Instance Methods public Object clone(); // Overrides Object public abstract int compare(String source, String target); public boolean equals(String source, String target); http://localhost/java/javaref/javanut/ch29_06.htm (1 of 2) [20/12/2001 11:00:15]
[Chapter 29] 29.6 java.text.Collator (JDK 1.1)
public public public public public public public
boolean equals(Object that); // Overrides Object abstract CollationKey getCollationKey(String source); synchronized int getDecomposition(); synchronized int getStrength(); abstract synchronized int hashCode(); // Overrides Object synchronized void setDecomposition(int decompositionMode); synchronized void setStrength(int newStrength);
}
Extended By: RuleBasedCollator
Returned By: Collator.getInstance()
java.text.CollationKey (JDK 1.1)
java.text.DateFormat (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_06.htm (2 of 2) [20/12/2001 11:00:15]
[Chapter 29] 29.17 java.text.RuleBasedCollator (JDK 1.1)
Chapter 29 The java.text Package
29.17 java.text.RuleBasedCollator (JDK 1.1) This class is a concrete subclass of the abstract Collator class. It performs collations using a table of rules that are specified in textual form. Most applications do not use this class directly; instead they call Collator.getInstance() to obtain a Collator object (typically a RuleBasedCollator object) that implements the default collation order for a specified or default locale. You should only need to use this class if you are collating strings for a locale that is not supported by default, or if you need to implement a highly customized collation order. public class RuleBasedCollator extends Collator { // Public Constructor public RuleBasedCollator(String rules) throws ParseException; // Public Instance Methods public Object clone(); // Overrides Collator public int compare(String source, String target); // Defines Collator public boolean equals(Object obj); // Overrides Collator public CollationElementIterator getCollationElementIterator(String source); public CollationKey getCollationKey(String source); // Defines Collator public String getRules(); public int hashCode(); // Defines Collator }
Hierarchy: Object->Collator(Cloneable, Serializable)->RuleBasedCollator
java.text.ParsePosition (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_17.htm [20/12/2001 11:00:15]
java.text.SimpleDateFormat (JDK 1.1)
[Chapter 6] 6.3 Drawing Graphics
Chapter 6 Applets
6.3 Drawing Graphics Example 6.2 shows a fancier version of our simple applet. As you can see from Figure 6.2 , we've made the graphical display more interesting. This applet also does all of its drawing in the paint() method. It demonstrates the use of Font and Color objects. This example also introduces the init() method, which is used, typically in place of a constructor, to perform any one-time initialization that is necessary when the applet is first created. The paint() method may be invoked many times in the life of an applet, so this example uses init() to create the Font object that paint() uses. Figure 6.2: A fancier applet
Example 6.2: An Applet with Fancier Graphics import java.applet.*; import java.awt.*; public class SecondApplet extends Applet { static final String message = "Hello World"; private Font font; // One-time initialization for the applet // Note: no constructor defined. public void init() { http://localhost/java/javaref/javanut/ch06_03.htm (1 of 2) [20/12/2001 11:00:15]
[Chapter 6] 6.3 Drawing Graphics
font = new Font("Helvetica", Font.BOLD, 48); } // Draw the applet whenever necessary. Do some fancy graphics. public void paint(Graphics g) { // The pink oval g.setColor(Color.pink); g.fillOval(10, 10, 330, 100); // The red outline. Java doesn't support wide lines, so we // try to simulate a 4-pixel wide line by drawing four ovals. g.setColor(Color.red); g.drawOval(10, 10, 330, 100); g.drawOval(9, 9, 332, 102); g.drawOval(8, 8, 334, 104); g.drawOval(7, 7, 336, 106); // The text g.setColor(Color.black); g.setFont(font); g.drawString(message, 40, 75); } }
A First Applet
http://localhost/java/javaref/javanut/ch06_03.htm (2 of 2) [20/12/2001 11:00:15]
Handling Events
[Chapter 21] 21.2 java.awt.image.ColorModel (JDK 1.0)
Chapter 21 The java.awt.image Package
21.2 java.awt.image.ColorModel (JDK 1.0) This abstract class defines a color model--i.e., a scheme for representing a color. Subclasses implement the methods of this interface to convert their particular representation of a pixel value into the default RGB color model. The static method getRGBDefault() returns a ColorModel object that implements the default color model--RGB plus alpha transparency. You generally never need to call the instance methods of a ColorModel--they are called internally by other image manipulation classes. See also DirectColorModel and IndexColorModel. public abstract class ColorModel extends Object { // Public Constructor public ColorModel(int bits); // Protected Instance Variables protected int pixel_bits; // Class Methods public static ColorModel getRGBdefault(); // Public Instance Methods public void finalize(); // Overrides Object public abstract int getAlpha(int pixel); public abstract int getBlue(int pixel); public abstract int getGreen(int pixel); public int getPixelSize(); public int getRGB(int pixel); public abstract int getRed(int pixel); }
Extended By: DirectColorModel, IndexColorModel
http://localhost/java/javaref/javanut/ch21_02.htm (1 of 2) [20/12/2001 11:00:15]
[Chapter 21] 21.2 java.awt.image.ColorModel (JDK 1.0)
Passed To: AreaAveragingScaleFilter.setPixels(), CropImageFilter.setPixels(), ImageConsumer.setColorModel(), ImageConsumer.setPixels(), ImageFilter.setColorModel(), ImageFilter.setPixels(), MemoryImageSource(), MemoryImageSource.newPixels(), PixelGrabber.setColorModel(), PixelGrabber.setPixels(), ReplicateScaleFilter.setPixels(), RGBImageFilter.setColorModel(), RGBImageFilter.setPixels(), RGBImageFilter.substituteColorModel()
Returned By: ColorModel.getRGBdefault(), Component.getColorModel(), ComponentPeer.getColorModel(), PixelGrabber.getColorModel(), Toolkit.getColorModel()
Type Of: RGBImageFilter.newmodel, RGBImageFilter.origmodel
java.awt.image.AreaAveragingScaleFilter (JDK 1.1)
http://localhost/java/javaref/javanut/ch21_02.htm (2 of 2) [20/12/2001 11:00:15]
java.awt.image.CropImageFilter (JDK 1.0)
[Chapter 21] 21.4 java.awt.image.DirectColorModel (JDK 1.0)
Chapter 21 The java.awt.image Package
21.4 java.awt.image.DirectColorModel (JDK 1.0) This class is a ColorModel that extracts the red, green, blue, and alpha values directly from the bits of the pixel. The arguments to the constructor methods specify the number of significant bits in the pixel and the mask used to extract each of the color components from the pixel. The default RGB color model is a DirectColorModel. You should not need to instantiate any kind of ColorModel object unless you are processing image data that does not use the standard RGB color format. public class DirectColorModel extends ColorModel { // Public Constructors public DirectColorModel(int bits, int rmask, int gmask, int bmask); public DirectColorModel(int bits, int rmask, int gmask, int bmask, int amask); // Public Instance Methods public final int getAlpha(int pixel); // Defines ColorModel public final int getAlphaMask(); public final int getBlue(int pixel); // Defines ColorModel public final int getBlueMask(); public final int getGreen(int pixel); // Defines ColorModel public final int getGreenMask(); public final int getRGB(int pixel); // Overrides ColorModel public final int getRed(int pixel); // Defines ColorModel public final int getRedMask(); }
Hierarchy: Object->ColorModel->DirectColorModel
java.awt.image.CropImageFilter (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_04.htm [20/12/2001 11:00:16]
java.awt.image.FilteredImageSource (JDK 1.0)
[Chapter 21] 21.10 java.awt.image.IndexColorModel (JDK 1.0)
Chapter 21 The java.awt.image Package
21.10 java.awt.image.IndexColorModel (JDK 1.0) This class is a ColorModel that determines the red, green, blue, and alpha values for a pixel by using the pixel value as an index into colormap arrays. If no array of alpha values is specified, all pixels are considered fully opaque, except for one optionally specified reserved value that is fully transparent. This color model is useful when working with image data that is defined in terms of a color map. You should not need to instantiate any kind of ColorModel object unless you are processing image data that does not use the standard RGB color format. public class IndexColorModel extends ColorModel { // Public Constructors public IndexColorModel(int bits, int size, byte[] r, byte[] g, byte[] b); public IndexColorModel(int bits, int size, byte[] r, byte[] g, byte[] b, int trans); public IndexColorModel(int bits, int size, byte[] r, byte[] g, byte[] b, byte[] a); public IndexColorModel(int bits, int size, byte[] cmap, int start, boolean hasalpha); public IndexColorModel(int bits, int size, byte[] cmap, int start, boolean hasalpha, int trans); // Public Instance Methods public final int getAlpha(int pixel); // Defines ColorModel public final void getAlphas(byte[] a); public final int getBlue(int pixel); // Defines ColorModel public final void getBlues(byte[] b); public final int getGreen(int pixel); // Defines ColorModel public final void getGreens(byte[] g); public final int getMapSize(); public final int getRGB(int pixel); // Overrides ColorModel public final int getRed(int pixel); // Defines ColorModel public final void getReds(byte[] r); public final int getTransparentPixel(); }
Hierarchy: Object->ColorModel->IndexColorModel
Passed To: RGBImageFilter.filterIndexColorModel()
http://localhost/java/javaref/javanut/ch21_10.htm (1 of 2) [20/12/2001 11:00:16]
[Chapter 21] 21.10 java.awt.image.IndexColorModel (JDK 1.0)
Returned By: RGBImageFilter.filterIndexColorModel()
java.awt.image.ImageProducer (JDK 1.0)
java.awt.image.MemoryImageSource (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_10.htm (2 of 2) [20/12/2001 11:00:16]
[Chapter 14] 14.2 Working with System Properties
Chapter 14 System Properties
14.2 Working with System Properties The system property list is not a static. Other properties can be added to it (and read from it) to allow easy customization of application behavior.
Specifying Individual Properties You can specify individual properties to be inserted into the system properties list with the -D option to the Java interpreter. For example, you might invoke a program like this: % java -Dgames.tetris.level=9 -Dgames.tetris.sound=off games.tetris Note the format of each property specification: the property name, which is often a hierarchical one, followed by an equals sign, followed by the property value. A property value may include spaces, but any -D option specifying a property value containing spaces would have to be quoted when passed to java, of course. If you write a platform-specific script file to invoke your Java application, you can use this -D option to translate native environment variable settings into Java system properties. On a Unix system, for example, such a script might look like this: #!/bin/sh exec java -Dgames.tetris.level=$TETRIS_LEVEL \ -Dgames.tetris.sound=$TETRIS_SOUND \ games.tetris
Using Property Files Properties in Java are represented by the java.util.Properties object, which is essentially a hash table that can be read from and written to a file. A program need not limit itself to the use of system properties. It can also read in its own files of properties to support user preferences and user customization. For example, when the appletviewer program starts up, it reads the properties from the lib/appletviewer.properties file in the JDK distribution. This file contains the various messages that appletviewer displays to the user and provides the flexibility to translate those messages into other languages. The following lines are an excerpt from appletviewer.properties:
http://localhost/java/javaref/javanut/ch14_02.htm (1 of 3) [20/12/2001 11:00:16]
[Chapter 14] 14.2 Working with System Properties
# # Applet status messages # appletloader.nocode=APPLET tag missing CODE parameter. appletloader.notfound=load: class %0 not found. appletloader.nocreate=load: %0 can't be instantiated. Note that comments in a properties file start with #, and that the property specification format is the same as with the -D option. Also note that these property values do contain spaces. Some of them also contain the % substitution character and are intended for use with the java.text.MessageFormat class. When reading in a file of properties, it can be convenient to merge those properties with the standard system properties, so that the program need only look in one place to find both loaded properties and standard properties (and properties specifed wiht the -D option). Every Properties object can have a "parent" properties object; if a property is not found in the Properties object, it is searched for in the parent. Thus, it is possible to merge in properties with code like this: // Create a new Properties object with system props as its parent. Properties props = new Properties(System.getProperties()); // Load a file of properties into it. We may get an exception here... props.load(new BufferedInputStream(new FileInputStream(propsfilename))); // Set these new combined properties as the system properties. System.setProperties(props);
Specifying Font Properties As noted above, a program can read the string value of a system property with the System.getProperty() method. There are also some convenience methods that read a property value and convert that value into some other type of object. One of these convenience methods is Font.getFont(). This method reads the value of a named property and attempts to parse it into a font specification. The font specification syntax it uses is: name[-style][-size] Thestyle should be italic, bold or bolditalic. If omitted, a plain font is used. The size should be an integer that specifies the font size in points. If omitted, 12-point is used. If the style is specified, the size must also be specified. For example, you might specify font properties like the following: games.tetris.titlefont=sanserif-bolditalic-48 games.tetris.mainfont=serif-14 games.tetris.scorefont=monospaced
http://localhost/java/javaref/javanut/ch14_02.htm (2 of 3) [20/12/2001 11:00:16]
[Chapter 14] 14.2 Working with System Properties
Specifying Color Properties Color.getColor() is another convenience routine that reads a system property and converts it into a Color object. To specify a color property, you specify the color as an integer value, typically as a hexadecimal value in the format 0xRRGGBB. For example: # A green foreground games.tetris.foreground=0x00FF00 # A light gray background games.tetris.background=0xD0D0D0
Standard System Properties
http://localhost/java/javaref/javanut/ch14_02.htm (3 of 3) [20/12/2001 11:00:16]
Java-Related HTML Tags
[Chapter 18] 18.56 java.awt.SystemColor (JDK 1.1)
Chapter 18 The java.awt Package
18.56 java.awt.SystemColor (JDK 1.1) Instances of the SystemColor class represent colors used in the system desktop. You can use these colors to produce applications and custom components that fit well in the desktop color scheme. On platforms that allow the desktop colors to be modified dynamically, the actual color represented by these symbolic system colors may be dynamically updated. The SystemColor class does not have a constructor, but it defines constant SystemColor objects that represent each of the symbolic colors used by the system desktop. If you need to compare a SystemColor object to a regular Color object, use the getRGB() method of both objects and compare the resulting values. public final class SystemColor extends Color implements Serializable { // No Constructor // Color Constants public static final SystemColor activeCaption, activeCaptionBorder, activeCaptionText; public static final SystemColor control, controlDkShadow, controlHighlight; public static final SystemColor controlLtHighlight, controlShadow, controlText; public static final SystemColor desktop; public static final SystemColor inactiveCaption, inactiveCaptionBorder, inactiveCaptionText; public static final SystemColor info, infoText; public static final SystemColor menu, menuText; public static final SystemColor scrollbar; public static final SystemColor text, textHighlight, textHighlightText; public static final SystemColor textInactiveText, textText; public static final SystemColor window, windowBorder, windowText; // Color Index Constants public static final int ACTIVE_CAPTION, ACTIVE_CAPTION_BORDER, ACTIVE_CAPTION_TEXT; public static final int CONTROL, CONTROL_DK_SHADOW, CONTROL_HIGHLIGHT; public static final int CONTROL_LT_HIGHLIGHT, CONTROL_SHADOW, CONTROL_TEXT; public static final int DESKTOP; public static final int INACTIVE_CAPTION, INACTIVE_CAPTION_BORDER, INACTIVE_CAPTION_TEXT; public static final int INFO, INFO_TEXT; public static final int MENU, MENU_TEXT; public static final int NUM_COLORS; public static final int SCROLLBAR;
http://localhost/java/javaref/javanut/ch18_56.htm (1 of 2) [20/12/2001 11:00:16]
[Chapter 18] 18.56 java.awt.SystemColor (JDK 1.1)
public static final int TEXT, TEXT_HIGHLIGHT, TEXT_HIGHLIGHT_TEXT; public static final int TEXT_INACTIVE_TEXT, TEXT_TEXT; public static final int WINDOW, WINDOW_BORDER, WINDOW_TEXT; // Public Instance Methods public int getRGB(); // Overrides Color public String toString(); // Overrides Color }
Hierarchy: Object->Color(Serializable)->SystemColor(Serializable)
java.awt.Shape (JDK 1.1)
java.awt.TextArea (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_56.htm (2 of 2) [20/12/2001 11:00:16]
[Chapter 24] 24.61 java.io.StreamTokenizer (JDK 1.0)
Chapter 24 The java.io Package
24.61 java.io.StreamTokenizer (JDK 1.0) This class performs lexical analysis of a specified input stream and breaks the input up into tokens. It can be extremely useful when writing simple parsers. nextToken() returns the next token in the stream--this is either one of the constants defined by the class (which represent end-of-file, end-of-line, a parsed floating-point number, and a parsed word) or a character value. pushBack() "pushes" the token back onto the stream, so that it is returned by the next call to nextToken(). The public variables sval and nval contain the string and numeric values (if applicable) of the most recently read token. They are applicable when the returned token is TT_WORD and TT_NUMBER. lineno() returns the current line number. The remaining methods allow you to specify how tokens are recognized. wordChars() specifies a range of characters that should be treated as parts of words. whitespaceChars() specifies a range of characters that serve to delimit tokens. ordinaryChars() and ordinaryChar() specify characters that are never part of tokens and should be returned as-is. resetSyntax() makes all characters "ordinary." eolIsSignificant() specifies whether end-of-line is significant. If so, the TT_EOL constant is returned for end-of-lines. Otherwise they are treated as whitespace. commentChar() specifies a character that begins a comment that lasts until the end of the line. No characters in the comment are returned. slashStarComments() and slashSlashComments() specify whether the StreamTokenizer should recognize C and C++-style comments. If so, no parts of the comments are returned as tokens. quoteChar() specifies a character used to delimit strings. When a string token is parsed, the quote character is returned as the token value, and the body of the string is stored in the sval variable. lowerCaseMode() specifies whether TT_WORD tokens should be converted to all lowercase characters before being stored in sval. parseNumbers() specifies that the StreamTokenizer should recognize and return double-precision floating-point number tokens. public class StreamTokenizer extends Object { // Public Constructors # public StreamTokenizer(InputStream is); 1.1 public StreamTokenizer(Reader r); // Constants public static final int TT_EOF; public static final int TT_EOL;
http://localhost/java/javaref/javanut/ch24_61.htm (1 of 2) [20/12/2001 11:00:17]
[Chapter 24] 24.61 java.io.StreamTokenizer (JDK 1.0)
public static final int TT_NUMBER; public static final int TT_WORD; // Public Instance Variables public double nval; public String sval; public int ttype; // Public Instance Methods public void commentChar(int ch); public void eolIsSignificant(boolean flag); public int lineno(); public void lowerCaseMode(boolean fl); public int nextToken() throws IOException; public void ordinaryChar(int ch); public void ordinaryChars(int low, int hi); public void parseNumbers(); public void pushBack(); public void quoteChar(int ch); public void resetSyntax(); public void slashSlashComments(boolean flag); public void slashStarComments(boolean flag); public String toString(); // Overrides Object public void whitespaceChars(int low, int hi); public void wordChars(int low, int hi); }
java.io.StreamCorruptedException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_61.htm (2 of 2) [20/12/2001 11:00:17]
java.io.StringBufferInputStream (JDK 1.0; Deprecated.)
[Chapter 18] 18.15 java.awt.Component (JDK 1.0)
Chapter 18 The java.awt Package
18.15 java.awt.Component (JDK 1.0) Component is the superclass of all GUI components (except menu components) in the java.awt package. You may not instantiate a Component directly; you must use a subclass. Component defines many methods. Some of these are intended to be implemented by subclasses. Some are used internally by the AWT. Some are to be implemented to handle events. And many are useful utility methods for working with GUI components. getParent() returns the Container that a Component is contained in. setBackground(), setForeground(), and setFont() set the specified display attributes of a component. hide(), show(), enable(), and disable() perform the specified actions for a component. createImage() creates an Image object from a specified ImageProducer, or creates an offscreen image that can be draw into and used for double-buffering during animation. Component also has quite a few deprecated methods as a result of the Java 1.1 event model and the introduction of the JavaBeans method naming conventions. The class defines quite a few methods for handling many types of events using the 1.0 model and the 1.1 model in both its high-level and low-level forms. public abstract class Component extends Object implements ImageObserver, MenuContainer, Serializable { // Protected Constructor 1.1 protected Component(); // Constants 1.1 public static final float BOTTOM_ALIGNMENT; 1.1 public static final float CENTER_ALIGNMENT; 1.1 public static final float LEFT_ALIGNMENT; 1.1 public static final float RIGHT_ALIGNMENT; 1.1 public static final float TOP_ALIGNMENT; // Public Instance Methods # public boolean action(Event evt, Object what); 1.1 public synchronized void add(PopupMenu popup); 1.1 public synchronized void addComponentListener(ComponentListener l); 1.1 public synchronized void addFocusListener(FocusListener l); 1.1 public synchronized void addKeyListener(KeyListener l); 1.1 public synchronized void addMouseListener(MouseListener l); 1.1 public synchronized void addMouseMotionListener(MouseMotionListener l); public void addNotify(); # public Rectangle bounds(); public int checkImage(Image image, ImageObserver observer); public int checkImage(Image image, int width, int height, ImageObserver observer); 1.1 public boolean contains(int x, int y); 1.1 public boolean contains(Point p); public Image createImage(ImageProducer producer); public Image createImage(int width, int height); # public void deliverEvent(Event e); # public void disable();
http://localhost/java/javaref/javanut/ch18_15.htm (1 of 4) [20/12/2001 11:00:17]
[Chapter 18] 18.15 java.awt.Component (JDK 1.0)
h);
1.1 public final void dispatchEvent(AWTEvent e); 1.1 public void doLayout(); # public void enable(); # public void enable(boolean b); 1.1 public float getAlignmentX(); 1.1 public float getAlignmentY(); public Color getBackground(); 1.1 public Rectangle getBounds(); public ColorModel getColorModel(); 1.1 public Component getComponentAt(int x, int y); 1.1 public Component getComponentAt(Point p); 1.1 public Cursor getCursor(); public Font getFont(); // From MenuContainer public FontMetrics getFontMetrics(Font font); public Color getForeground(); public Graphics getGraphics(); 1.1 public Locale getLocale(); 1.1 public Point getLocation(); 1.1 public Point getLocationOnScreen(); 1.1 public Dimension getMaximumSize(); 1.1 public Dimension getMinimumSize(); 1.1 public String getName(); public Container getParent(); # public ComponentPeer getPeer(); 1.1 public Dimension getPreferredSize(); 1.1 public Dimension getSize(); public Toolkit getToolkit(); 1.1 public final Object getTreeLock(); # public boolean gotFocus(Event evt, Object what); # public boolean handleEvent(Event evt); # public void hide(); public boolean imageUpdate(Image img, int flags, int x, int y, int w, int // From ImageObserver # public boolean inside(int x, int y); public void invalidate(); public boolean isEnabled(); 1.1 public boolean isFocusTraversable(); public boolean isShowing(); public boolean isValid(); public boolean isVisible(); # public boolean keyDown(Event evt, int key); # public boolean keyUp(Event evt, int key); # public void layout(); public void list(); public void list(PrintStream out); public void list(PrintStream out, int indent); 1.1 public void list(PrintWriter out); 1.1 public void list(PrintWriter out, int indent); # public Component locate(int x, int y); # public Point location(); # public boolean lostFocus(Event evt, Object what); # public Dimension minimumSize(); # public boolean mouseDown(Event evt, int x, int y); # public boolean mouseDrag(Event evt, int x, int y); # public boolean mouseEnter(Event evt, int x, int y);
http://localhost/java/javaref/javanut/ch18_15.htm (2 of 4) [20/12/2001 11:00:17]
[Chapter 18] 18.15 java.awt.Component (JDK 1.0)
# # # # #
public boolean mouseExit(Event evt, int x, int y); public boolean mouseMove(Event evt, int x, int y); public boolean mouseUp(Event evt, int x, int y); public void move(int x, int y); public void nextFocus(); public void paint(Graphics g); public void paintAll(Graphics g); # public boolean postEvent(Event e); // From MenuContainer # public Dimension preferredSize(); public boolean prepareImage(Image image, ImageObserver observer); public boolean prepareImage(Image image, int width, int height, ImageObserver observer); public void print(Graphics g); public void printAll(Graphics g); 1.1 public synchronized void remove(MenuComponent popup); // From MenuContainer 1.1 public synchronized void removeComponentListener(ComponentListener l); 1.1 public synchronized void removeFocusListener(FocusListener l); 1.1 public synchronized void removeKeyListener(KeyListener l); 1.1 public synchronized void removeMouseListener(MouseListener l); 1.1 public synchronized void removeMouseMotionListener(MouseMotionListener l); public void removeNotify(); public void repaint(); public void repaint(long tm); public void repaint(int x, int y, int width, int height); public void repaint(long tm, int x, int y, int width, int height); public void requestFocus(); # public void reshape(int x, int y, int width, int height); # public void resize(int width, int height); # public void resize(Dimension d); public void setBackground(Color c); 1.1 public void setBounds(int x, int y, int width, int height); 1.1 public void setBounds(Rectangle r); 1.1 public synchronized void setCursor(Cursor cursor); 1.1 public void setEnabled(boolean b); public synchronized void setFont(Font f); public void setForeground(Color c); 1.1 public void setLocale(Locale l); 1.1 public void setLocation(int x, int y); 1.1 public void setLocation(Point p); 1.1 public void setName(String name); 1.1 public void setSize(int width, int height); 1.1 public void setSize(Dimension d); 1.1 public void setVisible(boolean b); # public void show(); # public void show(boolean b); # public Dimension size(); public String toString(); // Overrides Object 1.1 public void transferFocus(); public void update(Graphics g); public void validate(); // Protected Instance Methods 1.1 protected final void disableEvents(long eventsToDisable); 1.1 protected final void enableEvents(long eventsToEnable); http://localhost/java/javaref/javanut/ch18_15.htm (3 of 4) [20/12/2001 11:00:17]
[Chapter 18] 18.15 java.awt.Component (JDK 1.0)
1.1 1.1 1.1 1.1 1.1 1.1
protected String paramString(); protected void processComponentEvent(ComponentEvent e); protected void processEvent(AWTEvent e); protected void processFocusEvent(FocusEvent e); protected void processKeyEvent(KeyEvent e); protected void processMouseEvent(MouseEvent e); protected void processMouseMotionEvent(MouseEvent e);
}
Extended By: Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, TextComponent
Passed To: BorderLayout.addLayoutComponent(), BorderLayout.removeLayoutComponent(), CardLayout.addLayoutComponent(), CardLayout.removeLayoutComponent(), ComponentEvent(), Container.add(), Container.addImpl(), Container.isAncestorOf(), Container.remove(), ContainerEvent(), FlowLayout.addLayoutComponent(), FlowLayout.removeLayoutComponent(), FocusEvent(), GridBagLayout.addLayoutComponent(), GridBagLayout.getConstraints(), GridBagLayout.lookupConstraints(), GridBagLayout.removeLayoutComponent(), GridBagLayout.setConstraints(), GridLayout.addLayoutComponent(), GridLayout.removeLayoutComponent(), KeyEvent(), LayoutManager.addLayoutComponent(), LayoutManager.removeLayoutComponent(), LayoutManager2.addLayoutComponent(), MediaTracker(), MouseEvent(), PaintEvent(), PopupMenu.show(), ScrollPane.addImpl(), Toolkit.createComponent(), Toolkit.getNativeContainer()
Returned By: Component.getComponentAt(), Component.locate(), ComponentEvent.getComponent(), Container.add(), Container.getComponent(), Container.getComponentAt(), Container.getComponents(), Container.locate(), ContainerEvent.getChild(), PropertyEditor.getCustomEditor(), PropertyEditorSupport.getCustomEditor(), Window.getFocusOwner()
java.awt.Color (JDK 1.0)
java.awt.Container (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_15.htm (4 of 4) [20/12/2001 11:00:17]
[Chapter 20] 20.6 java.awt.event.ComponentEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.6 java.awt.event.ComponentEvent (JDK 1.1) An event of this type serves as notification that the source Component has been moved, resized, shown, or hidden. Note that this event is a notification only: the AWT handles these Component operations internally, and the recipient of the event need take no action itself. getComponent() returns the component that was moved, resized, shown or hidden. It is simply a convenient alternative to getSource(). getID() returns one of four COMPONENT_ constants to indicate what operation was performed on the Component. public class ComponentEvent extends AWTEvent { // Public Constructor public ComponentEvent(Component source, int id); // Constants public static final int COMPONENT_FIRST; public static final int COMPONENT_HIDDEN; public static final int COMPONENT_LAST; public static final int COMPONENT_MOVED; public static final int COMPONENT_RESIZED; public static final int COMPONENT_SHOWN; // Public Instance Methods public Component getComponent(); public String paramString(); // Overrides AWTEvent }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ComponentEvent
http://localhost/java/javaref/javanut/ch20_06.htm (1 of 2) [20/12/2001 11:00:17]
[Chapter 20] 20.6 java.awt.event.ComponentEvent (JDK 1.1)
Extended By: ContainerEvent, FocusEvent, InputEvent, PaintEvent, WindowEvent
Passed To: AWTEventMulticaster.componentHidden(), AWTEventMulticaster.componentMoved(), AWTEventMulticaster.componentResized(), AWTEventMulticaster.componentShown(), Component.processComponentEvent(), ComponentAdapter.componentHidden(), ComponentAdapter.componentMoved(), ComponentAdapter.componentResized(), ComponentAdapter.componentShown(), ComponentListener.componentHidden(), ComponentListener.componentMoved(), ComponentListener.componentResized(), ComponentListener.componentShown()
java.awt.event.ComponentAdapter (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_06.htm (2 of 2) [20/12/2001 11:00:17]
java.awt.event.ComponentListener (JDK 1.1)
[Chapter 20] 20.7 java.awt.event.ComponentListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.7 java.awt.event.ComponentListener (JDK 1.1) This interface defines the methods that an object must implement to "listen" for component events on AWT components. When a ComponentEvent occurs, an AWT component notifies its registered ComponentListener objects by invoking one of their methods. An easy way to implement this interface is by subclassing the ComponentAdapter class. public abstract interface ComponentListener extends EventListener { // Public Instance Methods public abstract void componentHidden(ComponentEvent e); public abstract void componentMoved(ComponentEvent e); public abstract void componentResized(ComponentEvent e); public abstract void componentShown(ComponentEvent e); }
Implemented By: AWTEventMulticaster, ComponentAdapter
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), Component.addComponentListener(), Component.removeComponentListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
java.awt.event.ComponentEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_07.htm [20/12/2001 11:00:17]
java.awt.event.ContainerAdapter (JDK 1.1)
[Chapter 22] 22.6 java.awt.peer.ComponentPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.6 java.awt.peer.ComponentPeer (JDK 1.0) public abstract interface ComponentPeer { // Public Instance Methods public abstract int checkImage(Image img, int w, int h, ImageObserver o); public abstract Image createImage(ImageProducer producer); public abstract Image createImage(int width, int height); public abstract void disable(); public abstract void dispose(); public abstract void enable(); public abstract ColorModel getColorModel(); public abstract FontMetrics getFontMetrics(Font font); public abstract Graphics getGraphics(); 1.1 public abstract Point getLocationOnScreen(); 1.1 public abstract Dimension getMinimumSize(); 1.1 public abstract Dimension getPreferredSize(); public abstract Toolkit getToolkit(); 1.1 public abstract void handleEvent(AWTEvent e); public abstract void hide(); 1.1 public abstract boolean isFocusTraversable(); public abstract Dimension minimumSize(); public abstract void paint(Graphics g); public abstract Dimension preferredSize(); public abstract boolean prepareImage(Image img, int w, int h, ImageObserver o); public abstract void print(Graphics g); public abstract void repaint(long tm, int x, int y, int width, int height); public abstract void requestFocus(); public abstract void reshape(int x, int y, int width, int height); public abstract void setBackground(Color c); 1.1 public abstract void setBounds(int x, int y, int width, int height); 1.1 public abstract void setCursor(Cursor cursor); 1.1 public abstract void setEnabled(boolean b); public abstract void setFont(Font f); public abstract void setForeground(Color c); 1.1 public abstract void setVisible(boolean b); public abstract void show(); }
http://localhost/java/javaref/javanut/ch22_06.htm (1 of 2) [20/12/2001 11:00:18]
[Chapter 22] 22.6 java.awt.peer.ComponentPeer (JDK 1.0)
Extended By: ButtonPeer, CanvasPeer, CheckboxPeer, ChoicePeer, ContainerPeer, LabelPeer, LightweightPeer, ListPeer, ScrollbarPeer, TextComponentPeer
Returned By: Component.getPeer()
java.awt.peer.ChoicePeer (JDK 1.0)
java.awt.peer.ContainerPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_06.htm (2 of 2) [20/12/2001 11:00:18]
[Chapter 7] Events
Chapter 7
7. Events Contents: The Java 1.0 Event Model Scribbling in Java 1.0 The Java 1.1 Event Model Scribbling in Java 1.1 Scribbling with Inner Classes Inside the Java 1.1 Event Model The heart of any applet or graphical user interface is the event processing code. Graphical applications are event-driven: they do nothing until the user moves the mouse or clicks a button or types a key. An event-driven program is structured around its event-processing model, so a solid understanding of event handling mechanisms is crucial for good programming. Unfortunately, the Java event handling model has changed between Java 1.0 and Java 1.1. The Java 1.0 model is a simple one, well suited to writing basic applets. It has a number of shortcomings, however, and does not scale well to complicated interfaces. Although the 1.0 event model is deprecated in Java 1.1, you'll still need to use it for any applets that you want to run on Web browsers based on Java 1.0. The Java 1.1 event model solves many of the shortcomings of the 1.0 model it replaces, but would be quite cumbersome to use if it were not for the new inner class features also introduced in Java 1.1. This chapter covers both event models and provides examples of each.
7.1 The Java 1.0 Event Model In Java 1.0, all events are represented by the Event class. This class has a number of instance variables that describe the event. One of these variables, id, specifies the type of the event. Event defines a number of constants that are the possible values for the id field. The target field specifies the object (typically a Component) that generated the event, or on which the event occurred (i.e., the source of the event). The other fields may or may not be used, depending on the type of the event. For example, the x and y fields are defined when id is BUTTON_EVENT, but not when it is ACTION_EVENT. The arg field can provide additional type-dependent data. Java 1.0 events are dispatched first to the handleEvent() method of the Component on which they
http://localhost/java/javaref/javanut/ch07_01.htm (1 of 6) [20/12/2001 11:00:19]
[Chapter 7] Events
occurred. The default implementation of this method checks the id field of the Event object and dispatches the most commonly used types of events to various type-specific methods, listed in Table 7.1. Table 7.1: Java 1.0 Event Processing Methods of Component action() gotFocus() keyDown() keyUp()
lostFocus() mouseExit() mouseDown() mouseMove() mouseDrag() mouseUp() mouseEnter()
The methods listed in Table 7.1 are defined by the Component class. One of the primary characteristics of the Java 1.0 event model is that you must override these methods in order to process events. This means that you must create a subclass to define custom event-handling behavior, which is exactly what we do when we write an applet, for example. Notice, however, that not all of the event types are dispatched by handleEvent() to more specific methods. So, if you are interested in LIST_SELECT or WINDOW_ICONIFY events, for example, you have to override handleEvent() itself, rather than one of the more specific methods. If you do this, you should usually invoke super.handleEvent() to continue dispatching events of other types in the default way. The handleEvent() method, and all of the type-specific methods, return boolean values. If an event-handling method returns false, as they all do by default, it means that the event was not handled, so it should be passed to the container of the current component to see if that container is interested in processing it. If a method returns true, on the other hand, it is a signal that the event has been handled and no further processing is needed. The fact that unhandled events are passed up the containment hierarchy is important. It means that we can override the action() method (for example) in an applet in order to handle the ACTION_EVENT events that are generated by the buttons within the applet. If they were not propagated up as they are, we would have to create a custom subclass of Button for every button we wanted to add to an interface! In programs that use the Java 1.0 event model, it is typical to handle events at the top-level component. In an applet, for example, you override the handleEvent() method, or some of the other type-specific methods, of the Applet subclass you create. Or, in a stand-alone program that creates its own window, you subclass Frame to provide definitions of the event-handling methods. When a program displays a dialog box, it subclasses Dialog to define the methods. With complex interfaces, the event-handling methods of the containers at the top of the hierarchy can become long and somewhat convoluted, so you need to be careful when writing them.
Components and Their Events In the Java 1.0 model, there is no defacto way to know what types of events are generated by what GUI components. You simply have to look this information up in the documentation. Additionally, different components use different fields of the Event object, and pass different values in the arg field of that object. Table 7.2 lists each of the AWT components, and for each one, lists the type of events it generates. The first column of the table specifies both the type of the component and the type of the
http://localhost/java/javaref/javanut/ch07_01.htm (2 of 6) [20/12/2001 11:00:19]
[Chapter 7] Events
event. The event type is the constant stored in the id field of the Event. The second through sixth columns indicate whether the when (timestamp), x (mouse x coordinate), y (mouse y coordinate), key (the key that was pressed), and modifiers (modifier keys that were down) fields are set for a given event. If a dot appears in this column, the event sets a value for the corresponding field. The seventh column explains what occurred to trigger the event, and what the value of the arg field of the Event object is. Events listed for the Component component type apply to all java.awt Component subclasses. The events listed for the Window component type also apply to the Window subclasses, Dialog and Frame. Table 7.2: AWT Components and the Java 1.0 Events They Generate Component Event Meaning when x y key mods Event Type (id) arg (Type: value) User clicked on the button Button String: the button label User clicked on checkbox
ACTION_EVENT Checkbox
Boolean: new checkbox state User selected an item
ACTION_EVENT Choice
*
String: label of selected item Got input focus unused User pressed a function key
*
unused--key contains key constant User released a function key
*
unused--key contains key constant User pressed a key
*
unused--key contains ASCII key value User released a key
ACTION_EVENT Component GOT_FOCUS Component
*
***
KEY_ACTION Component
*
***
KEY_ACTION_RELEASE Component
*
***
KEY_PRESS Component
*
***
KEY_RELEASE Component LOST_FOCUS Component
*
**
unused--key contains ASCII key value Lost input focus unused Mouse entered the Component
http://localhost/java/javaref/javanut/ch07_01.htm (3 of 6) [20/12/2001 11:00:19]
[Chapter 7] Events
MOUSE_ENTER Component MOUSE_EXIT Component MOUSE_DOWN Component MOUSE_UP Component MOUSE_MOVE Component MOUSE_DRAG List ACTION_EVENT List LIST_SELECT List LIST_DESELECT MenuItem ACTION_EVENT Scrollbar SCROLL_LINE_UP Scrollbar SCROLL_LINE_DOWN Scrollbar SCROLL_PAGE_UP Scrollbar SCROLL_PAGE_DOWN Scrollbar SCROLL_ABSOLUTE TextField ACTION_EVENT Window WINDOW_DESTROY Window WINDOW_ICONIFY
*
**
*
**
*
*
**
*
*
**
*
*
**
*
unused Mouse left the Component unused User pressed mouse button unused User released mouse button unused User moved mouse unused User dragged mouse unused User double-clicked on an item String: label of activated item User selected an item Integer: index of selected item User deselected an item Integer: index of deselected item User selected an item String: label of selected item User requested scroll Integer: position to scroll to User requested scroll Integer: position to scroll to User requested scroll Integer: position to scroll to User requested scroll Integer: position to scroll to User requested scroll Integer: position to scroll to User struck String: user's input text Window was destroyed unused Window was iconified unused
http://localhost/java/javaref/javanut/ch07_01.htm (4 of 6) [20/12/2001 11:00:19]
[Chapter 7] Events
Window WINDOW_DEICONIFY Window WINDOW_MOVED
**
Window was deiconified unused Window was moved unused
Key and Modifier Constants The java.awt.Event class contains the field key, which is filled in when a keyboard event has occurred, and the field modifiers, which list the keyboard modifier keys currently in effect for key and mouse events. Four modifier constants are defined by the java.awt.Event class; they are listed in Table 7.3. They are mask values that are ORed into the modifiers field. You can test for them using AND. You can also check a given event for the first three of the modifiers with the Event methods shiftDown(), controlDown(), and metaDown(). Table 7.3: Java Keyboard Modifiers Modifier Constant Meaning Event.SHIFT_MASK SHIFT key is held down (or CAPS LOCK on) Event.CTRL_MASK CONTROL key is held down Event.META_MASK META key is held down ALT key is held down Event.ALT_MASK When a KEY_PRESS or KEY_RELEASE event occurs, it means that the user pressed a key that is a normal printing character, a control character, or a non-printing character with a standard ASCII value--one of RETURN (ASCII 10 or '\n'), TAB (ASCII 9 or '\t'), ESCAPE (ASCII 27), BACKSPACE (ASCII 8), or DELETE (ASCII 127). In this case, the value of the key field in the event is simply the ASCII value of the key that was pressed or released. When a KEY_ACTION or KEY_ACTION_RELEASE event occurs, it means that the user pressed some sort of function key, one which does not have an ASCII representation. java.awt.Event defines constants for each of these function keys, which are listed in Table 7.4. Table 7.4: Java Function Key Constants Key Constant Event.HOME Event.END Event.PGUP Event.PGDN Event.UP Event.DOWN
Meaning HOME key END key PAGE UP key PAGE DOWN key UP arrow key DOWN arrow key
http://localhost/java/javaref/javanut/ch07_01.htm (5 of 6) [20/12/2001 11:00:19]
[Chapter 7] Events
LEFT arrow key Event.LEFT RIGHT arrow key Event.RIGHT Event.F1 to Event.F12 Function keys 1 through 12
Mouse Buttons In order to maintain platform independence, Java only recognizes a single mouse button--the Event class does not have any kind of mouseButton field to indicate which button has been pressed on a multi-button mouse. On platforms that support two- or three-button mouses, the right and center buttons generate mouse down, mouse drag, and mouse up events as if the user were holding down modifier keys, as shown in Table 7.5. Table 7.5: Mouse Button Modifiers Mouse Button Flag Set in Event.modifiers Field Left button none Right button Event.META_MASK Middle button Event.ALT_MASK Using keyboard modifiers to indicate the mouse button that has been pressed maintains compatibility with platforms that only have one-button mouses, but still allows programs to use the right and middle buttons on platforms that support them. Suppose, for example, you want to write a program that allows the user to draw lines with the mouse using two different colors. You might draw in the primary color if there are no modifier flags set, and draw in the secondary color when the META_MASK modifier is set. In this way, users with a two- or three-button mouse can simply use the left and right mouse buttons to draw in the two colors; and users with a one-button mouse can use the META key, in conjunction with the mouse, to draw in the secondary color.
Signed Applets
http://localhost/java/javaref/javanut/ch07_01.htm (6 of 6) [20/12/2001 11:00:19]
Scribbling in Java 1.0
[Chapter 24] 24.48 java.io.PipedInputStream (JDK 1.0)
Chapter 24 The java.io Package
24.48 java.io.PipedInputStream (JDK 1.0) This class is an InputStream that implements one-half of a pipe, and is useful for communication between threads. A PipedInputStream must be connected to a PipedOutputStream object, which may be specified when the PipedInputStream is created or with the connect() method. Data read from a PipedInputStream object are received from the PipedOutputStream to which it is connected. See InputStream for information on the low-level methods for reading data from a PipedInputStream. A FilterInputStream may be used to provide a higher-level interface for reading data from a PipedInputStream. public class PipedInputStream extends InputStream { // Public Constructors public PipedInputStream(PipedOutputStream src) throws IOException; public PipedInputStream(); // Constants 1.1 protected static final int PIPE_SIZE; // Protected Instance Variables 1.1 protected byte[] buffer; 1.1 protected int in; 1.1 protected int out; // Public Instance Methods public synchronized int available() throws IOException; // Overrides InputStream public void close() throws IOException; // Overrides InputStream public void connect(PipedOutputStream src) throws IOException; public synchronized int read() throws IOException; // Defines InputStream public synchronized int read(byte[] b, int off, int len) throws IOException; // Overrides InputStream // Protected Instance Methods 1.1 protected synchronized void receive(int b) throws IOException; }
Hierarchy: Object->InputStream->PipedInputStream
http://localhost/java/javaref/javanut/ch24_48.htm (1 of 2) [20/12/2001 11:00:19]
[Chapter 24] 24.48 java.io.PipedInputStream (JDK 1.0)
Passed To: PipedOutputStream(), PipedOutputStream.connect()
java.io.OutputStreamWriter (JDK 1.1)
java.io.PipedOutputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_48.htm (2 of 2) [20/12/2001 11:00:19]
[Chapter 24] 24.49 java.io.PipedOutputStream (JDK 1.0)
Chapter 24 The java.io Package
24.49 java.io.PipedOutputStream (JDK 1.0) This class is an OutputStream that implements one half of a pipe, and is useful for communication between threads. A PipedOutputStream must be connected to a PipedInputStream, which may be specified when the PipedOutputStream is created or with the connect() method. Data written to the PipedOutputStream are available for reading on the PipedInputStream. See OutputStream for information on the low-level methods for writing data to a PipedOutputStream. A FilterOutputStream may be used to provide a higher-level interface for writing data to a PipedOutputStream. public class PipedOutputStream extends OutputStream { // Public Constructors public PipedOutputStream(PipedInputStream snk) throws IOException; public PipedOutputStream(); // Public Instance Methods public void close() throws IOException; // Overrides OutputStream public void connect(PipedInputStream snk) throws IOException; public synchronized void flush() throws IOException; // Overrides OutputStream public void write(int b) throws IOException; // Defines OutputStream public void write(byte[] b, int off, int len) throws IOException; // Overrides OutputStream }
Hierarchy: Object->OutputStream->PipedOutputStream
Passed To: PipedInputStream(), PipedInputStream.connect()
java.io.PipedInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_49.htm [20/12/2001 11:00:19]
java.io.PipedReader (JDK 1.1)
[Chapter 28] 28.23 java.net.URLConnection (JDK 1.0)
Chapter 28 The java.net Package
28.23 java.net.URLConnection (JDK 1.0) This abstract class defines a network connection to an object specified by a URL. URL.openConnection() returns a URLConnection instance. You would use a URLConnection object when you want more control over the downloading of data than is available through the simpler URL methods. connect() actually performs the network connection. Other methods that depend on being connected will call this method. getContent() returns the data referred to by the URL, parsed into an appropriate type of Object. If the URL protocol supports read and write operations, then getInputStream() and getOutputStream() respectively return input and output streams to the object referred to by the URL. getContentLength(), getContentType(), getContentEncoding(), getExpiration(), getDate(), and getLastModified() return the appropriate information about the object referred to by the URL, if that information can be determined (e.g., from HTTP header fields). getHeaderField() returns an HTTP header field specified by name or by number. getHeaderFieldInt() and getHeaderFieldDate() return the value of a named header field parsed as an integer or a date. There are a number of options that you may specify to control how the URLConnection behaves. These options are set with the various set() methods, and may be queried with corresponding get() methods. The options must be set before the connect() method is called. setDoInput() and setDoOutput() allow you to specify whether you use the URLConnection for input and/or output. The default is input-only. setAllowUserInteraction() specifies whether user interaction (such as typing a password) is allowed during the data transfer. The initial default is false. setDefaultAllowUserInteraction() is a class method that allows you to change the default value for user interaction. setUseCaches() allows you to specify whether a cached version of the URL may be used. You can set this to false to force a URL to be reloaded. setDefaultUseCaches() sets the default value for setUseCaches(). setIfModifiedSince() allows you to specify that a URL should not be fetched (if it is possible to determine its modification date) unless it has been modified since a specified time. public abstract class URLConnection extends Object { // Protected Constructor protected URLConnection(URL url); // Class Variables 1.1public static FileNameMap fileNameMap; // Protected Instance Variables protected boolean allowUserInteraction; protected boolean connected; protected boolean doInput; protected boolean doOutput; protected long ifModifiedSince; protected URL url; protected boolean useCaches; // Class Methods public static boolean getDefaultAllowUserInteraction();
http://localhost/java/javaref/javanut/ch28_23.htm (1 of 3) [20/12/2001 11:00:20]
[Chapter 28] 28.23 java.net.URLConnection (JDK 1.0)
public static String getDefaultRequestProperty(String key); protected static String guessContentTypeFromName(String fname); public static String guessContentTypeFromStream(InputStream is) throws IOException; public static synchronized void setContentHandlerFactory(ContentHandlerFactory fac); public static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction); public static void setDefaultRequestProperty(String key, String value); // Public Instance Methods public abstract void connect() throws IOException; public boolean getAllowUserInteraction(); public Object getContent() throws IOException; public String getContentEncoding(); public int getContentLength(); public String getContentType(); public long getDate(); public boolean getDefaultUseCaches(); public boolean getDoInput(); public boolean getDoOutput(); public long getExpiration(); public String getHeaderField(String name); public String getHeaderField(int n); public long getHeaderFieldDate(String name, long Default); public int getHeaderFieldInt(String name, int Default); public String getHeaderFieldKey(int n); public long getIfModifiedSince(); public InputStream getInputStream() throws IOException; public long getLastModified(); public OutputStream getOutputStream() throws IOException; public String getRequestProperty(String key); public URL getURL(); public boolean getUseCaches(); public void setAllowUserInteraction(boolean allowuserinteraction); public void setDefaultUseCaches(boolean defaultusecaches); public void setDoInput(boolean doinput); public void setDoOutput(boolean dooutput); public void setIfModifiedSince(long ifmodifiedsince); public void setRequestProperty(String key, String value); public void setUseCaches(boolean usecaches); public String toString(); // Overrides Object }
Extended By: HttpURLConnection
Passed To: ContentHandler.getContent()
http://localhost/java/javaref/javanut/ch28_23.htm (2 of 3) [20/12/2001 11:00:20]
[Chapter 28] 28.23 java.net.URLConnection (JDK 1.0)
Returned By: URL.openConnection(), URLStreamHandler.openConnection()
java.net.URL (JDK 1.0)
java.net.URLEncoder (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_23.htm (3 of 3) [20/12/2001 11:00:20]
[Chapter 28] 28.2 java.net.ConnectException (JDK 1.1)
Chapter 28 The java.net Package
28.2 java.net.ConnectException (JDK 1.1) This exception signals that a socket could not be connected to a remote address and port. This means that the remote host could be reached, but is not responding, perhaps because there is no process on that host that is listening on the specified port. public class ConnectException extends SocketException { // Public Constructors public ConnectException(String msg); public ConnectException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->SocketException->ConnectException
java.net.BindException (JDK 1.1)
http://localhost/java/javaref/javanut/ch28_02.htm [20/12/2001 11:00:20]
java.net.ContentHandler (JDK 1.0)
[Chapter 26] 26.2 java.lang.reflect.Constructor (JDK 1.1)
Chapter 26 The java.lang.reflect Package
26.2 java.lang.reflect.Constructor (JDK 1.1) This class represents a constructor method of a class. Instances of Constructor are obtained by calling getConstructor() and related methods of java.lang.Class. Constructor implements the Member interface, so you can use the methods of that interface to obtain the constructor name, modifiers, and declaring class. In addition, getParameterTypes() and getExceptionTypes() also return important information about the represented constructor. In addition to these methods that return information about the constructor, the newInstance() method allows the constructor to be invoked with an array of arguments in order to create a new instance of the class that declares the constructor. If any of the arguments to the constructor are of primitive types, they must be converted to their corresponding wrapper object types in order to be passed to newInstance(). If the constructor causes an exception, the Throwable object it throws is wrapped within the InvocationTargetException that is thrown by newInstance(). Note that newInstance() is much more useful than the newInstance() method of java.lang.Class because it can pass arguments to the constructor. public final class Constructor extends Object implements Member { // No Constructor // Public Instance Methods public boolean equals(Object obj); // Overrides Object public Class getDeclaringClass(); // From Member public Class[] getExceptionTypes(); public native int getModifiers(); // From Member public String getName(); // From Member public Class[] getParameterTypes(); public int hashCode(); // Overrides Object public native Object newInstance(Object[] initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException; public String toString(); // Overrides Object }
http://localhost/java/javaref/javanut/ch26_02.htm (1 of 2) [20/12/2001 11:00:20]
[Chapter 26] 26.2 java.lang.reflect.Constructor (JDK 1.1)
Returned By: Class.getConstructor(), Class.getConstructors(), Class.getDeclaredConstructor(), Class.getDeclaredConstructors()
java.lang.reflect.Array (JDK 1.1)
http://localhost/java/javaref/javanut/ch26_02.htm (2 of 2) [20/12/2001 11:00:20]
java.lang.reflect.Field (JDK 1.1)
[Chapter 20] 20.14 java.awt.event.InputEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.14 java.awt.event.InputEvent (JDK 1.1) This abstract class serves as the superclass for the raw user input event types MouseEvent and KeyEvent. Use the inherited getComponent() to determine in which component the event occurred. Use getWhen() to obtain a timestamp for the event. Use getModifiers() to determine which keyboard modifier keys or mouse buttons were down when the event occurred. You can decode the getModifiers() return value using the various _MASK constants defined by this class. The class also defines four convenience methods for determining the state of keyboard modifiers. In Java 1.1, input events are delivered to the appropriate listener objects before they are delivered to the AWT components themselves. If a listener calls the consume() method of the event, the event is not passed on to the component. For example, if a listener registered on a Button "consumes" a mouse click, it prevents the button itself from responding to that event. You can use isConsumed() to test whether some other listener object has already consumed the event. public abstract class InputEvent extends ComponentEvent { // No Constructor // Constants public static final int ALT_MASK; public static final int BUTTON1_MASK; public static final int BUTTON2_MASK; public static final int BUTTON3_MASK; public static final int CTRL_MASK; public static final int META_MASK; public static final int SHIFT_MASK; // Public Instance Methods public void consume(); // Overrides AWTEvent public int getModifiers(); public long getWhen(); public boolean isAltDown(); public boolean isConsumed(); // Overrides AWTEvent public boolean isControlDown(); public boolean isMetaDown();
http://localhost/java/javaref/javanut/ch20_14.htm (1 of 2) [20/12/2001 11:00:20]
[Chapter 20] 20.14 java.awt.event.InputEvent (JDK 1.1)
public boolean isShiftDown(); }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ComponentEvent->InputEvent
Extended By: KeyEvent, MouseEvent
java.awt.event.FocusListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_14.htm (2 of 2) [20/12/2001 11:00:20]
java.awt.event.ItemEvent (JDK 1.1)
[Chapter 20] 20.18 java.awt.event.KeyEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.18 java.awt.event.KeyEvent (JDK 1.1) An event of this type indicates that the user has pressed or released a key or typed a character. Call getID() to determine the particular type of key event that has occurred. The constant KEY_PRESSED indicates that a key has been pressed, while the constant KEY_RELEASED indicates that a key has been released. Not all keystrokes actually correspond to or generate Unicode characters. Modifier keys and function keys, for example, do not correspond to characters. Furthermore, for internationalized input, multiple keystrokes are sometimes required to generate a single character of input. Therefore, getID() returns a third constant, KEY_TYPED, to indicate a KeyEvent that actually contains a character value. For KEY_PRESSED and KEY_RELEASED key events, use getKeyCode() to obtain the "virtual key code" of the key that was pressed or released. KeyEvent defines a number of VK_ constants that represent these "virtual keys." Note that not all keys on all keyboards have corresponding constants in the KeyEvent class, and not all keyboards can generate all of the virtual key codes defined by the class. In JDK 1.1, the VK_ constants for letter keys, number keys, and some other keys have the same values as the ASCII encodings of the letters and numbers. You should not rely on this to always be the case, however. If the key that was pressed or released corresponds directly to a Unicode character, you can obtain that character by calling getKeyChar(). If there is not a corresponding Unicode character, this method returns the constant CHAR_UNDEFINED. The isActionKey() method returns true if the key that was pressed or released does not have a corresponding character. For KEY_TYPED key events, use getKeyChar() to return the Unicode character that was typed. If you call getKeyCode() for this type of key event, it returns VK_UNDEFINED. See InputEvent for information on inherited methods you can use to obtain the keyboard modifiers that were down during the event and other important methods. Use getComponent(), inherited from ComponentEvent, to determine what component the event occurred over. The static method getKeyText() returns a (possibly localized) textual name for a given key code. The static method getKeyModifiersText() returns a (possibly localized) textual description for a set of modifiers. The KeyEvent has methods that allow you to change the key code, key character, or modifiers of an event. These methods, along with the consume() method, allow a KeyListener to perform filtering of key events before they are passed to the underlying AWT component. public class KeyEvent extends InputEvent { // Public Constructors public KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar); public KeyEvent(Component source, int id, long when, int modifiers, int keyCode); // Constants // Event Type Constants public static final int KEY_FIRST; http://localhost/java/javaref/javanut/ch20_18.htm (1 of 3) [20/12/2001 11:00:21]
[Chapter 20] 20.18 java.awt.event.KeyEvent (JDK 1.1)
public static final int KEY_LAST; public static final int KEY_PRESSED; public static final int KEY_RELEASED; public static final int KEY_TYPED; // Undefined Key and Character public static final int VK_UNDEFINED; public static final char CHAR_UNDEFINED; // Alphanumeric Keys public static final int VK_A, VK_B, VK_C, VK_D, VK_E, VK_F, VK_G, VK_H, VK_I; public static final int VK_J, VK_K, VK_L, VK_M, VK_N, VK_O, VK_P, VK_Q, VK_R; public static final int VK_S, VK_T, VK_U, VK_V, VK_W, VK_X, VK_Y, VK_Z; public static final int VK_SPACE; public static final int VK_0, VK_1, VK_2, VK_3, VK_4, VK_5, VK_6, VK_7, VK_8, VK_9; public static final int VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4; public static final int VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9; // Control Keys public static final int VK_BACK_SPACE, VK_ENTER, VK_ESCAPE, VK_TAB; // Modifier Keys public static final int VK_ALT, VK_CAPS_LOCK, VK_CONTROL, VK_META, VK_SHIFT; // Function Keys public static final int VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6; public static final int VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12; public static final int VK_PRINTSCREEN, VK_SCROLL_LOCK, VK_PAUSE; public static final int VK_DELETE, VK_INSERT; public static final int VK_PAGE_DOWN, VK_PAGE_UP; public static final int VK_DOWN, VK_LEFT, VK_RIGHT, VK_UP; public static final int VK_END, VK_HOME; public static final int VK_ACCEPT, VK_NUM_LOCK, VK_CANCEL; public static final int VK_CLEAR, VK_CONVERT, VK_FINAL; public static final int VK_HELP, VK_KANA, VK_KANJI; public static final int VK_MODECHANGE, VK_NONCONVERT; // Punctuation Keys public static final int VK_ADD, VK_BACK_QUOTE, VK_BACK_SLASH; public static final int VK_CLOSE_BRACKET, VK_COMMA, VK_DECIMAL; public static final int VK_DIVIDE, VK_EQUALS, VK_MULTIPLY; public static final int VK_OPEN_BRACKET, VK_PERIOD, VK_QUOTE; public static final int VK_SEMICOLON, VK_SEPARATER, VK_SLASH; public static final int VK_SUBTRACT; // Class Methods public static String getKeyModifiersText(int modifiers); public static String getKeyText(int keyCode); // Public Instance Methods public char getKeyChar(); public int getKeyCode(); public boolean isActionKey(); public String paramString(); // Overrides ComponentEvent public void setKeyChar(char keyChar); public void setKeyCode(int keyCode); http://localhost/java/javaref/javanut/ch20_18.htm (2 of 3) [20/12/2001 11:00:21]
[Chapter 20] 20.18 java.awt.event.KeyEvent (JDK 1.1)
public void setModifiers(int modifiers); }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ComponentEvent->InputEvent->KeyEvent
Passed To: AWTEventMulticaster.keyPressed(), AWTEventMulticaster.keyReleased(), AWTEventMulticaster.keyTyped(), Component.processKeyEvent(), KeyAdapter.keyPressed(), KeyAdapter.keyReleased(), KeyAdapter.keyTyped(), KeyListener.keyPressed(), KeyListener.keyReleased(), KeyListener.keyTyped()
java.awt.event.KeyAdapter (JDK 1.1)
java.awt.event.KeyListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_18.htm (3 of 3) [20/12/2001 11:00:21]
[Chapter 20] 20.9 java.awt.event.ContainerEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.9 java.awt.event.ContainerEvent (JDK 1.1) An event of this type serves as notification that the source Container has had a child added to it or removed from it. Note that this event is a notification only; the AWT adds or removes the child internally, and the recipient of this event need take no action itself. getChild() returns the child Component that was added or removed, and getContainer() returns the Container that it was added to or removed from. getContainer() is simply a convenient alternative to getSource(). getID() returns the constant COMPONENT_ADDED or COMPONENT_REMOVED to indicate whether the specified child was added or removed. public class ContainerEvent extends ComponentEvent { // Public Constructor public ContainerEvent(Component source, int id, Component child); // Constants public static final int COMPONENT_ADDED; public static final int COMPONENT_REMOVED; public static final int CONTAINER_FIRST; public static final int CONTAINER_LAST; // Public Instance Methods public Component getChild(); public Container getContainer(); public String paramString(); // Overrides ComponentEvent }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ComponentEvent->ContainerEvent
Passed To: AWTEventMulticaster.componentAdded(), AWTEventMulticaster.componentRemoved(), Container.processContainerEvent(), ContainerAdapter.componentAdded(), ContainerAdapter.componentRemoved(), ContainerListener.componentAdded(), ContainerListener.componentRemoved()
http://localhost/java/javaref/javanut/ch20_09.htm (1 of 2) [20/12/2001 11:00:21]
[Chapter 20] 20.9 java.awt.event.ContainerEvent (JDK 1.1)
java.awt.event.ContainerAdapter (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_09.htm (2 of 2) [20/12/2001 11:00:21]
java.awt.event.ContainerListener (JDK 1.1)
[Chapter 20] 20.10 java.awt.event.ContainerListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.10 java.awt.event.ContainerListener (JDK 1.1) This interface defines the methods that an object must implement to "listen" for container events on AWT components. When a ContainerEvent occurs, an AWT component notifies its registered ContainerListener objects by invoking one of their methods. An easy way to implement this interface is by subclassing the ContainerAdapter class. public abstract interface ContainerListener extends EventListener { // Public Instance Methods public abstract void componentAdded(ContainerEvent e); public abstract void componentRemoved(ContainerEvent e); }
Implemented By: AWTEventMulticaster, ContainerAdapter
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), Container.addContainerListener(), Container.removeContainerListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
java.awt.event.ContainerEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_10.htm [20/12/2001 11:00:21]
java.awt.event.FocusAdapter (JDK 1.1)
[Chapter 22] 22.7 java.awt.peer.ContainerPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.7 java.awt.peer.ContainerPeer (JDK 1.0) public abstract interface ContainerPeer extends ComponentPeer { // Public Instance Methods 1.1 public abstract void beginValidate(); 1.1 public abstract void endValidate(); 1.1 public abstract Insets getInsets(); public abstract Insets insets(); }
Extended By: PanelPeer, ScrollPanePeer, WindowPeer
java.awt.peer.ComponentPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_07.htm [20/12/2001 11:00:21]
java.awt.peer.DialogPeer (JDK 1.0)
[Chapter 28] 28.3 java.net.ContentHandler (JDK 1.0)
Chapter 28 The java.net Package
28.3 java.net.ContentHandler (JDK 1.0) This abstract class defines a method that reads data from a URLConnection and returns an object representing that data. Each subclass that implements this method is responsible for handling a different type of content (i.e., a different MIME type). Applications never create ContentHandler objects directly--they are created, when necessary, by the registered ContentHandlerFactory object. Applications should also never call ContentHandler methods directly--they should call URL.getContent() or URLConnection.getContent() instead. You only need to subclass ContentHandler if you are writing a Web browser or similar application that needs to parse and understand some new content type. public abstract class ContentHandler extends Object { // Default Constructor: public ContentHandler() // Public Instance Methods public abstract Object getContent(URLConnection urlc) throws IOException; }
Returned By: ContentHandlerFactory.createContentHandler()
java.net.ConnectException (JDK 1.1)
java.net.ContentHandlerFactory (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_03.htm [20/12/2001 11:00:21]
[Chapter 28] 28.4 java.net.ContentHandlerFactory (JDK 1.0)
Chapter 28 The java.net Package
28.4 java.net.ContentHandlerFactory (JDK 1.0) This interface defines a method that creates and returns an appropriate ContentHandler object for a specified MIME type. A system-wide ContentHandlerFactory interface may be specified by using the URLConnection.setContentHandlerFactory() method. Normal applications never need to use or implement this interface. public abstract interface ContentHandlerFactory { // Public Instance Methods public abstract ContentHandler createContentHandler(String mimetype); }
Passed To: URLConnection.setContentHandlerFactory()
java.net.ContentHandler (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_04.htm [20/12/2001 11:00:22]
java.net.DatagramPacket (JDK 1.0)
[Chapter 30] 30.23 java.util.StringTokenizer (JDK 1.0)
Chapter 30 The java.util Package
30.23 java.util.StringTokenizer (JDK 1.0) This class, when instantiated with a String, breaks the string up into tokens separated by any of the characters in the specified string of delimiters. (For example, words separated by space and tab characters are tokens.) The hasMoreTokens() and nextToken() methods can be used to obtain the tokens in order. countTokens() returns the number of tokens in the string. Note that StringTokenizer implements the Enumeration interface, so you may also access the tokens with the familiar hasMoreElements() and nextElement() methods. When you create a StringTokenizer you may specify a string of delimiter characters to use for the entire string, or you may rely on the default whitespace delimiters. You may also specify whether the delimiters themselves should be returned as tokens. You may optionally specify a new string of delimiter characters when you call nextToken(). public class StringTokenizer extends Object implements Enumeration { // Public Constructors public StringTokenizer(String str, String delim, boolean returnTokens); public StringTokenizer(String str, String delim); public StringTokenizer(String str); // Public Instance Methods public int countTokens(); public boolean hasMoreElements(); // From Enumeration public boolean hasMoreTokens(); public Object nextElement(); // From Enumeration public String nextToken(); public String nextToken(String delim); }
java.util.Stack (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_23.htm [20/12/2001 11:00:22]
java.util.TimeZone (JDK 1.1)
[Chapter 31] 31.5 java.util.zip.CRC32 (JDK 1.1)
Chapter 31 The java.util.zip Package
31.5 java.util.zip.CRC32 (JDK 1.1) This class implements the Checksum interface and computes a checksum on a stream of data using the CRC-32 algorithm. The CheckedInputStream and CheckedOutputStream classes provide a higher-level interface to computing checksums on streams of data. public class CRC32 extends Object implements Checksum { // Default Constructor: public CRC32() // Public Instance Methods public long getValue(); // From Checksum public void reset(); // From Checksum public void update(int b); // From Checksum public native void update(byte[] b, int off, int len); public void update(byte[] b); }
Type Of: GZIPInputStream.crc, GZIPOutputStream.crc
java.util.zip.Checksum (JDK 1.1)
java.util.zip.DataFormatException (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_05.htm [20/12/2001 11:00:22]
// From Checksum
[Chapter 18] 18.27 java.awt.Graphics (JDK 1.0)
Chapter 18 The java.awt Package
18.27 java.awt.Graphics (JDK 1.0) This abstract class defines a device-independent interface to graphics. It specifies methods for doing line drawing, area filling, image painting, area copying, and graphics output clipping. Specific subclasses of Graphics are implemented for different platforms and different graphics output devices. A Graphics object cannot be created directly through a constructor--it must be obtained with the getGraphics() method of a Component or an Image, or copied from an existing Graphics object with create(). When a Graphics object is no longer needed, you should call dispose() to free up the window system resources it uses. public abstract class Graphics extends Object { // Protected Constructor protected Graphics(); // Public Instance Methods public abstract void clearRect(int x, int y, int width, int height); public abstract void clipRect(int x, int y, int width, int height); public abstract void copyArea(int x, int y, int width, int height, int dx, int dy); public abstract Graphics create(); public Graphics create(int x, int y, int width, int height); public abstract void dispose(); public void draw3DRect(int x, int y, int width, int height, boolean raised); public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle); public void drawBytes(byte[] data, int offset, int length, int x, int y); public void drawChars(char[] data, int offset, int length, int x, int y); public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, public abstract boolean drawImage'u'ImageObserver observer); 1.1 public abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, 1.1 public abstract boolean drawImage'u'int sx2, int sy2, ImageObserver observer); 1.1 public abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, 1.1 public abstract boolean drawImage'u'int sx2, int sy2, Color bgcolor, ImageObserver observer); public abstract void drawLine(int x1, int y1, int x2, int y2); http://localhost/java/javaref/javanut/ch18_27.htm (1 of 3) [20/12/2001 11:00:22]
[Chapter 18] 18.27 java.awt.Graphics (JDK 1.0)
public abstract void drawOval(int x, int y, int width, int height); public abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints); 1.1 nPoints);
public void drawPolygon(Polygon p); public abstract void drawPolyline(int[] xPoints, int[] yPoints, int
public void drawRect(int x, int y, int width, int height); public abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); public abstract void drawString(String str, int x, int y); public void fill3DRect(int x, int y, int width, int height, boolean raised); public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle); public abstract void fillOval(int x, int y, int width, int height); public abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); public void fillPolygon(Polygon p); public abstract void fillRect(int x, int y, int width, int height); public abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); public void finalize(); // Overrides Object 1.1 public abstract Shape getClip(); 1.1 public abstract Rectangle getClipBounds(); # public Rectangle getClipRect(); public abstract Color getColor(); public abstract Font getFont(); public FontMetrics getFontMetrics(); public abstract FontMetrics getFontMetrics(Font f); 1.1 public abstract void setClip(int x, int y, int width, int height); 1.1 public abstract void setClip(Shape clip); public abstract void setColor(Color c); public abstract void setFont(Font font); public abstract void setPaintMode(); public abstract void setXORMode(Color c1); public String toString(); // Overrides Object public abstract void translate(int x, int y); }
Passed To: Canvas.paint(), Component.paint(), Component.paintAll(), Component.print(), Component.printAll(), Component.update(), ComponentPeer.paint(), ComponentPeer.print(), Container.paint(), Container.paintComponents(), Container.print(), Container.printComponents(), PropertyEditor.paintValue(), PropertyEditorSupport.paintValue(), ScrollPane.printComponents()
Returned By: Component.getGraphics(), ComponentPeer.getGraphics(), Graphics.create(), Image.getGraphics(), PrintJob.getGraphics()
http://localhost/java/javaref/javanut/ch18_27.htm (2 of 3) [20/12/2001 11:00:22]
[Chapter 18] 18.27 java.awt.Graphics (JDK 1.0)
java.awt.Frame (JDK 1.0)
java.awt.GridBagConstraints (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_27.htm (3 of 3) [20/12/2001 11:00:22]
[Chapter 21] 21.3 java.awt.image.CropImageFilter (JDK 1.0)
Chapter 21 The java.awt.image Package
21.3 java.awt.image.CropImageFilter (JDK 1.0) This class implements an ImageFilter that crops an image to a specified rectangle. The methods defined by this class are used for communication between the filter and its FilteredImageSource and should never be called directly. public class CropImageFilter extends ImageFilter { // Public Constructor public CropImageFilter(int x, int y, int w, int h); // Public Instance Methods public void setDimensions(int w, int h); // Overrides ImageFilter public void setPixels(int x, int y, int w, int h, ColorModel model, public void setPixels'u'byte[] pixels, int off, int scansize); // Overrides ImageFilter public void setPixels(int x, int y, int w, int h, ColorModel model, public void setPixels'u'int[] pixels, int off, int scansize); // Overrides ImageFilter public void setProperties(Hashtable props); // Overrides ImageFilter }
Hierarchy: Object->ImageFilter(ImageConsumer, Cloneable)->CropImageFilter
java.awt.image.ColorModel (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_03.htm [20/12/2001 11:00:23]
java.awt.image.DirectColorModel (JDK 1.0)
[Chapter 18] 18.17 java.awt.Cursor (JDK 1.1)
Chapter 18 The java.awt Package
18.17 java.awt.Cursor (JDK 1.1) This class represents a mouse cursor. It defines a number of constants, each of which specify one of the supported cursor images. Pass one of these constants to the constructor to create a cursor of the specified type, and call getType() to determine the type of an existing Cursor object. Since there are only a fixed number of available cursors, the static method getPredefinedCursor() is more efficient than the Cursor() constructor--it maintains a cache of Cursor objects that can be reused. The static getDefaultCursor() method returns the system default cursor. public class Cursor extends Object implements Serializable { // Public Constructor public Cursor(int type); // Cursor Constants public static final int DEFAULT_CURSOR; public static final int CROSSHAIR_CURSOR, HAND_CURSOR, MOVE_CURSOR; public static final int TEXT_CURSOR, WAIT_CURSOR; public static final int N_RESIZE_CURSOR, S_RESIZE_CURSOR; public static final int E_RESIZE_CURSOR, W_RESIZE_CURSOR; public static final int NE_RESIZE_CURSOR, NW_RESIZE_CURSOR; public static final int SE_RESIZE_CURSOR, SW_RESIZE_CURSOR; // Class Variables protected static Cursor[] predefined; // Class Methods public static Cursor getDefaultCursor(); public static Cursor getPredefinedCursor(int type); // Public Instance Methods public int getType(); }
Passed To: Component.setCursor(), ComponentPeer.setCursor()
Returned By: Component.getCursor(), Cursor.getDefaultCursor(), Cursor.getPredefinedCursor()
http://localhost/java/javaref/javanut/ch18_17.htm (1 of 2) [20/12/2001 11:00:23]
[Chapter 18] 18.17 java.awt.Cursor (JDK 1.1)
Type Of: Cursor.predefined
java.awt.Container (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_17.htm (2 of 2) [20/12/2001 11:00:23]
java.awt.Dialog (JDK 1.0)
[Chapter 10] 10.8 Defining a Bean Customizer
Chapter 10 Java Beans
10.8 Defining a Bean Customizer A bean may want to provide some way for the user of a beanbox program to customize its properties other than by setting them one at a time. A bean can do this by creating a Customizer class for itself, and registering the customizer class with the BeanDescriptor object returned by its BeanInfo class, as we saw in Example 10.5. A customizer must be some kind of AWT component that is suitable for display in a dialog box created by the beanbox. Therefore, a customizer class is typically a subclass of Panel. In addition, a customizer must implement the Customizer interface. This interface consists of methods for adding and removing property change event listeners and a setObject() method that the beanbox calls to tell the customizer what bean object it is customizing. Whenever the user makes a change to the bean through the customizer, the customizer should send a PropertyChangeEvent to any interested listeners. Finally, like a property editor, a customizer must have a no-argument constructor, so it can easily be instantiated by a beanbox. Example 10.8 shows a customizer for our YesNoDialog bean. This customizer displays a panel that has the same layout as a YesNoDialog, but it substitutes a TextArea object for the message display and three TextField objects for the three buttons that the dialog can display. These text entry areas allow the user to enter values for the message, yesLabel, noLabel, and cancelLabel properties. Figure 10.3 shows this customizer panel displayed within a dialog box created by the beanbox program. Again, note that the Done button is part of the beanbox dialog, not part of the customizer itself. Figure 10.3: The customizer dialog for the YesNoDialog bean
Example 10.8: The YesNoDialogCustomizer Class http://localhost/java/javaref/javanut/ch10_08.htm (1 of 3) [20/12/2001 11:00:24]
[Chapter 10] 10.8 Defining a Bean Customizer
package oreilly.beans.yesno; import java.awt.*; import java.awt.event.*; import java.beans.*; /** * This class is a customizer for the YesNoDialog bean. It displays a * TextArea and three TextFields where the user can enter the dialog message * and the labels for each of the three buttons. It does not allow the * dialog title or other resources to be set. */ public class YesNoDialogCustomizer extends Panel implements Customizer, TextListener { protected YesNoDialog bean; // The bean being customized. protected TextComponent message, fields[]; // Components used by customizer // Default constructor: YesNoDialogCustomizer() { super(); } // The bean box calls this method to tell us what object to customize. // This method will always be called before the customizer is displayed, // so it is safe to create the customizer GUI here. public void setObject(Object o) { bean = (YesNoDialog)o; // Save the object we're customizing. // Put a label at the top of the panel. this.setLayout(new BorderLayout()); this.add(new Label("Enter the message to appear in the dialog:"), "North"); // And a big text area below it for entering the dialog message. message = new TextArea(bean.getMessage()); message.addTextListener(this); // TextAreas don't know how big they want to be. You must tell them. message.setSize(400, 200); this.add(message, "Center"); // Then add a row of textfields for entering the button labels. Panel buttonbox = new Panel(); // The row container. buttonbox.setLayout(new GridLayout(1, 0, 25, 10)); // Equally spaced items. this.add(buttonbox, "South"); // Put row on bottom. // Now go create three TextFields to put in this row. But actually // position a Label above each, so create a container for each // TextField+Label combination. fields = new TextComponent[3]; // Array of TextFields. String[] labels = new String[] { // Labels for each. "Yes Button Label", "No Button Label", "Cancel Button Label"}; String[] values = new String[] { // Initial values of each. bean.getYesLabel(), bean.getNoLabel(), bean.getCancelLabel()}; for(int i = 0; i < 3; i++) { Panel p = new Panel(); // Create a container. p.setLayout(new BorderLayout()); // Give it a BorderLayout. p.add(new Label(labels[i]), "North"); // Put a label on the top. fields[i] = new TextField(values[i]); // Create the text field. p.add(fields[i], "Center"); // Put it below the label. fields[i].addTextListener(this); // Set the event listener.
http://localhost/java/javaref/javanut/ch10_08.htm (2 of 3) [20/12/2001 11:00:24]
[Chapter 10] 10.8 Defining a Bean Customizer
buttonbox.add(p);
// Add container to row.
} } // Add some space around the outside of the panel. public Insets getInsets() { return new Insets(10, 10, 10, 10); } // This is the method defined by the TextListener interface. Whenever the // user types a character in the TextArea or TextFields, this will get // called. It updates the appropriate property of the bean and fires a // property changed event, as all customizers are required to do. // Note that we are not required to fire an event for every keystroke. // Instead we could include an "Apply" button that would make all the // changes at once, with a single property changed event. public void textValueChanged(TextEvent e) { TextComponent t = (TextComponent)e.getSource(); String s = t.getText(); if (t == message) bean.setMessage(s); else if (t == fields[0]) bean.setYesLabel(s); else if (t == fields[1]) bean.setNoLabel(s); else if (t == fields[2]) bean.setCancelLabel(s); listeners.firePropertyChange(null, null, null); } // This code uses the PropertyChangeSupport class to maintain a list of // listeners interested in the edits we make to the bean. protected PropertyChangeSupport listeners = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener l) { listeners.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { listeners.removePropertyChangeListener(l); } }
Defining a Complex Property Editor
http://localhost/java/javaref/javanut/ch10_08.htm (3 of 3) [20/12/2001 11:00:24]
Naming Patterns and Conventions
[Chapter 31] 31.6 java.util.zip.DataFormatException (JDK 1.1)
Chapter 31 The java.util.zip Package
31.6 java.util.zip.DataFormatException (JDK 1.1) Signals that invalid or corrupt data has been encountered while uncompressing data. public class DataFormatException extends Exception { // Public Constructors public DataFormatException(); public DataFormatException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->DataFormatException
Thrown By: Inflater.inflate()
java.util.zip.CRC32 (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_06.htm [20/12/2001 11:00:24]
java.util.zip.Deflater (JDK 1.1)
[Chapter 24] 24.10 java.io.DataInput (JDK 1.0)
Chapter 24 The java.io Package
24.10 java.io.DataInput (JDK 1.0) This interface defines the methods required for streams that can read Java primitive data types in a machine-independent binary format. It is implemented by DataInputStream and RandomAccessFile. See DataInputStream for more information on the methods. public abstract interface DataInput { // Public Instance Methods public abstract boolean readBoolean() throws IOException; public abstract byte readByte() throws IOException; public abstract char readChar() throws IOException; public abstract double readDouble() throws IOException; public abstract float readFloat() throws IOException; public abstract void readFully(byte[] b) throws IOException; public abstract void readFully(byte[] b, int off, int len) throws IOException; public abstract int readInt() throws IOException; public abstract String readLine() throws IOException; public abstract long readLong() throws IOException; public abstract short readShort() throws IOException; public abstract String readUTF() throws IOException; public abstract int readUnsignedByte() throws IOException; public abstract int readUnsignedShort() throws IOException; public abstract int skipBytes(int n) throws IOException; }
Extended By: ObjectInput
Implemented By: DataInputStream, RandomAccessFile
Passed To: DataInputStream.readUTF()
http://localhost/java/javaref/javanut/ch24_10.htm (1 of 2) [20/12/2001 11:00:24]
[Chapter 24] 24.10 java.io.DataInput (JDK 1.0)
java.io.CharConversionException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_10.htm (2 of 2) [20/12/2001 11:00:24]
java.io.DataInputStream (JDK 1.0)
[Chapter 24] 24.11 java.io.DataInputStream (JDK 1.0)
Chapter 24 The java.io Package
24.11 java.io.DataInputStream (JDK 1.0) This class is a type of FilterInputStream that allows you to read binary representations of Java primitive data types in a portable way. Create a DataInputStream by specifying the InputStream that is to be filtered in the call to the constructor. Many of this class's methods read and return a single Java primitive type, in binary format, from the stream. readUnsignedByte() and readUnsignedShort() read unsigned values and return them as int values, since unsigned byte and short types are not supported in Java. read() reads data into an array of bytes, blocking until at least some data are available. By contrast, readFully() reads data into an array of bytes, but blocks until all of the requested data become available. skipBytes() blocks until the specified number of bytes have been read and discarded. readLine() reads characters from the stream until it encounters a newline, a carriage return, or a newline carriage return pair. The returned string is not terminated with a newline or carriage return. This method is deprecated in Java 1.1; see BufferedReader for an alternative. readUTF() reads a string of Unicode text encoded in a slightly modified version of the UTF-8 "transformation format." UTF-8 is an ASCII-compatible encoding of Unicode characters that is often used for the transmission and storage of Unicode text. This class uses a modified UTF-8 encoding that never contains embedded null characters. DataInputStream only reads primitive Java types. Use ObjectInputStream to read object values. public class DataInputStream extends FilterInputStream implements DataInput { // Public Constructor public DataInputStream(InputStream in); // Class Methods public static final String readUTF(DataInput in) throws IOException; // Public Instance Methods public final int read(byte[] b) throws IOException; // Overrides FilterInputStream public final int read(byte[] b, int off, int len) throws IOException; // Overrides FilterInputStream public final boolean readBoolean() throws IOException; // From DataInput public final byte readByte() throws IOException; // From DataInput public final char readChar() throws IOException; // From DataInput public final double readDouble() throws IOException; // From DataInput public final float readFloat() throws IOException; // From DataInput public final void readFully(byte[] b) throws IOException; // From DataInput public final void readFully(byte[] b, int off, int len) throws IOException; // From DataInput public final int readInt() throws IOException; // From DataInput # public final String readLine() throws IOException; // From DataInput public final long readLong() throws IOException; // From DataInput public final short readShort() throws IOException; // From DataInput public final String readUTF() throws IOException; // From DataInput http://localhost/java/javaref/javanut/ch24_11.htm (1 of 2) [20/12/2001 11:00:24]
[Chapter 24] 24.11 java.io.DataInputStream (JDK 1.0)
public final int readUnsignedByte() throws IOException;
// From
DataInput public final int readUnsignedShort() throws IOException;
// From
DataInput public final int skipBytes(int n) throws IOException; }
Hierarchy: Object->InputStream->FilterInputStream->DataInputStream(DataInput)
java.io.DataInput (JDK 1.0)
java.io.DataOutput (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_11.htm (2 of 2) [20/12/2001 11:00:24]
// From DataInput
[Chapter 24] 24.12 java.io.DataOutput (JDK 1.0)
Chapter 24 The java.io Package
24.12 java.io.DataOutput (JDK 1.0) This interface defines the methods required for streams that can write character data or Java primitive data types in a machine-independent binary format. It is implemented by DataOutputStream and RandomAccessFile. See DataOutputStream for more information on the methods. public abstract interface DataOutput { // Public Instance Methods public abstract void write(int b) throws IOException; public abstract void write(byte[] b) throws IOException; public abstract void write(byte[] b, int off, int len) throws IOException; public abstract void writeBoolean(boolean v) throws IOException; public abstract void writeByte(int v) throws IOException; public abstract void writeBytes(String s) throws IOException; public abstract void writeChar(int v) throws IOException; public abstract void writeChars(String s) throws IOException; public abstract void writeDouble(double v) throws IOException; public abstract void writeFloat(float v) throws IOException; public abstract void writeInt(int v) throws IOException; public abstract void writeLong(long v) throws IOException; public abstract void writeShort(int v) throws IOException; public abstract void writeUTF(String str) throws IOException; }
Extended By: ObjectOutput
Implemented By: DataOutputStream, RandomAccessFile
java.io.DataInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_12.htm (1 of 2) [20/12/2001 11:00:25]
java.io.DataOutputStream (JDK 1.0)
[Chapter 24] 24.12 java.io.DataOutput (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_12.htm (2 of 2) [20/12/2001 11:00:25]
[Chapter 24] 24.13 java.io.DataOutputStream (JDK 1.0)
Chapter 24 The java.io Package
24.13 java.io.DataOutputStream (JDK 1.0) This class is a subclass of FilterOutputStream that allows you to write Java primitive data types in a portable binary format. Create a DataOutputStream by specifying the OutputStream that is to be filtered in the call to the constructor. Many of this class's methods write a single Java primitive type, in binary format to the output stream. write() writes a single byte, an array, or a subarray of bytes. flush() forces any buffered data to be output. size() returns the number of bytes written so far. writeUTF() outputs a Java string of Unicode characters using a slightly modified version of the UTF-8 "transformation format." UTF-8 is an ASCII-compatible encoding of Unicode characters that is often used for the transmission and storage of Unicode text. Except for the writeUTF() method, this class is used for binary output of data. Textual output should be done with PrintWriter, or PrintStream in Java 1.0. DataOutputStream only has methods to output primitive types. Use ObjectOutputStream to output object values. public class DataOutputStream extends FilterOutputStream implements DataOutput { // Public Constructor public DataOutputStream(OutputStream out); // Protected Instance Variables protected int written; // Public Instance Methods public void flush() throws IOException; // Overrides FilterOutputStream public final int size(); public synchronized void write(int b) throws IOException; // Overrides FilterOutputStream public synchronized void write(byte[] b, int off, int len) throws IOException; // Overrides FilterOutputStream public final void writeBoolean(boolean v) throws IOException; // From DataOutput public final void writeByte(int v) throws IOException; // From DataOutput public final void writeBytes(String s) throws IOException; // From DataOutput public final void writeChar(int v) throws IOException; // From DataOutput public final void writeChars(String s) throws IOException; // From DataOutput public final void writeDouble(double v) throws IOException; // From DataOutput public final void writeFloat(float v) throws IOException; // From DataOutput public final void writeInt(int v) throws IOException; // From DataOutput public final void writeLong(long v) throws IOException; // From DataOutput http://localhost/java/javaref/javanut/ch24_13.htm (1 of 2) [20/12/2001 11:00:25]
[Chapter 24] 24.13 java.io.DataOutputStream (JDK 1.0)
public final void writeShort(int v) throws IOException;
// From
DataOutput public final void writeUTF(String str) throws IOException; DataOutput }
Hierarchy: Object->OutputStream->FilterOutputStream->DataOutputStream(DataOutput)
java.io.DataOutput (JDK 1.0)
java.io.EOFException (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_13.htm (2 of 2) [20/12/2001 11:00:25]
// From
[Chapter 19] 19.3 java.awt.datatransfer.DataFlavor (JDK 1.1)
Chapter 19 The java.awt.datatransfer Package
19.3 java.awt.datatransfer.DataFlavor (JDK 1.1) Objects of this type define a data type or format for the purposes of data transfer. A DataFlavor is characterized by two values. The first is a descriptive human-readable name, passed to a DataFlavor() constructor or set with setHumanPresentableName(). The second component of a DataFlavor specifies the type of data to be transferred in a more machine-readable way. The two DataFlavor() constructors allow two distinct ways to specify this data type. One way is by directly specifying the representation class of the data. This is a Class object that defines the Java type that the recipient of a data transfer is passed. The other way to specify the data type represented by a DataFlavor is to pass a string that specifies the MIME type of the data to be transferred. When you construct a DataFlavor object by specifying the representation type of the data, the MIME type of the DataFlavor is automatically set to: application/x-java-serialized-object class=classname This indicates that the object is to be transferred using the data format of the Java object serialization protocol. When you pass a MIME type string to the DataFlavor() constructor, on the other hand, the representation class of the DataFlavor is automatically set to the Class object for java.io.InputStream. This means that the recipient of the data transfer is given an InputStream object from which it can read and parse data in the specified MIME format. Because the same MIME type can be specified with a number of slightly different strings, the DataFlavor class converts the MIME type to a canonical form so that it can be uniquely identified and compared. Use isMimeTypeEqual() to compare the MIME type of a DataFlavor object with another MIME type, or with the MIME type of another DataFlavor. Because textual data is so often transferred, the DataFlavor class defines constants for two commonly-used data flavors. stringFlavor represents text transferred as a String object, while plainTextFlavor represents text transferred through an InputStream, using the text/plain MIME type. public class DataFlavor extends Object { // Public Constructors public DataFlavor(Class representationClass, String humanPresentableName); public DataFlavor(String mimeType, String humanPresentableName); // Class Variables public static DataFlavor plainTextFlavor; public static DataFlavor stringFlavor; // Public Instance Methods public boolean equals(DataFlavor dataFlavor); public String getHumanPresentableName(); public String getMimeType(); public Class getRepresentationClass(); http://localhost/java/javaref/javanut/ch19_03.htm (1 of 2) [20/12/2001 11:00:25]
[Chapter 19] 19.3 java.awt.datatransfer.DataFlavor (JDK 1.1)
public boolean isMimeTypeEqual(String mimeType); public final boolean isMimeTypeEqual(DataFlavor dataFlavor); public void setHumanPresentableName(String humanPresentableName); // Protected Instance Methods protected String normalizeMimeType(String mimeType); protected String normalizeMimeTypeParameter(String parameterName, String parameterValue); }
Passed To: DataFlavor.equals(), DataFlavor.isMimeTypeEqual(), StringSelection.getTransferData(), StringSelection.isDataFlavorSupported(), Transferable.getTransferData(), Transferable.isDataFlavorSupported(), UnsupportedFlavorException()
Returned By: StringSelection.getTransferDataFlavors(), Transferable.getTransferDataFlavors()
Type Of: DataFlavor.plainTextFlavor, DataFlavor.stringFlavor
java.awt.datatransfer.ClipboardOwner (JDK 1.1)
http://localhost/java/javaref/javanut/ch19_03.htm (2 of 2) [20/12/2001 11:00:25]
java.awt.datatransfer.StringSelection (JDK 1.1)
[Chapter 13] Java Syntax
Chapter 13
13. Java Syntax Contents: Primitive Data Types Character Escape Sequences Operators Modifiers Reserved Words Java Documentation Comment Syntax
13.1 Primitive Data Types Java supports a complete set of primitive data types, listed in Table 13.1. In Java, the size of each type is defined by the language, and is not implementation dependent, as it is in C. Table 13.1: Java Primitive Data Types Type
Contains
Default Size
boolean true or false false 1 bit
Min Value Max Value N.A. N.A.
char byte short int long
Unicode character \u0000 16 bits \u0000 \uFFFF signed integer 8 bits -128 0 127 signed integer 16 bits -32768 0 32767 signed integer 32 bits -2147483648 0 2147483647 signed integer 64 bits -9223372036854775808 0
http://localhost/java/javaref/javanut/ch13_01.htm (1 of 2) [20/12/2001 11:00:25]
[Chapter 13] Java Syntax
float
IEEE 754 floating-point double IEEE 754 floating-point
0.0 0.0
9223372036854775807 32 bits +/-3.40282347E+38 +/-1.40239846E-45 64 bits +/-1.79769313486231570E+308 +/-4.94065645841246544E-324
Invoking a Named Method
http://localhost/java/javaref/javanut/ch13_01.htm (2 of 2) [20/12/2001 11:00:25]
Character Escape Sequences
[Chapter 25] 25.17 java.lang.Double (JDK 1.0)
Chapter 25 The java.lang Package
25.17 java.lang.Double (JDK 1.0) This class provides an immutable object wrapper around the double primitive data type. valueOf() converts a string to a Double, doubleValue() returns the primitive double value of a Double object, and there are other methods for returning a Double value as a variety of other primitive types. This class also provides some useful constants and static methods for testing double values. MIN_VALUE and MAX_VALUE are the smallest (closest to zero) and largest representable double values. isInfinite() in class method and instance method forms tests whether a double or a Double has an infinite value. Similarly, isNaN() tests whether a double or Double is not-a-number--this is a comparison that cannot be done directly because the NaN constant never tests equal to any other value, including itself. doubleToLongBits() and longBitsToDouble() allow you to manipulate the bit representation of a double directly. public final class Double extends Number { // Public Constructors public Double(double value); public Double(String s) throws NumberFormatException; // Constants public static final double MAX_VALUE; public static final double MIN_VALUE; public static final double NEGATIVE_INFINITY; public static final double NaN; public static final double POSITIVE_INFINITY; 1.1public static final Class TYPE; // Class Methods public static native long doubleToLongBits(double value); public static boolean isInfinite(double v); public static boolean isNaN(double v); public static native double longBitsToDouble(long bits); public static String toString(double d); public static Double valueOf(String s) throws NumberFormatException; // Public Instance Methods 1.1public byte byteValue(); // Overrides Number public double doubleValue(); // Defines Number public boolean equals(Object obj); // Overrides Object public float floatValue(); // Defines Number public int hashCode(); // Overrides Object public int intValue(); // Defines Number public boolean isInfinite(); public boolean isNaN(); public long longValue(); // Defines Number http://localhost/java/javaref/javanut/ch25_17.htm (1 of 2) [20/12/2001 11:00:26]
[Chapter 25] 25.17 java.lang.Double (JDK 1.0)
1.1public short shortValue(); public String toString();
// Overrides Number // Overrides Object
}
Hierarchy: Object->Number(Serializable)->Double
Returned By: Double.valueOf()
java.lang.Compiler (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_17.htm (2 of 2) [20/12/2001 11:00:26]
java.lang.Error (JDK 1.0)
[Chapter 25] 25.21 java.lang.Float (JDK 1.0)
Chapter 25 The java.lang Package
25.21 java.lang.Float (JDK 1.0) This class provides an immutable object wrapper around the float primitive data type. valueOf() converts a string to a Float, floatValue() returns the primitive float value of a Float object, and there are methods for returning a Float value as a variety of other primitive types. This class also provides some useful constants and static methods for testing float values. MIN_VALUE and MAX_VALUE are the smallest (closest to zero) and largest representable double values. isInfinite() in class method and instance method forms tests whether a float or a Float has an infinite value. Similarly, isNaN() tests whether a float or Float is not-a-number--this is a comparison that cannot be done directly because the NaN constant never tests equal to any other value, including itself. floatToIntBits() and intBitsToFloat() allow you to manipulate the bit representation of a float directly. public final class Float extends Number { // Public Constructors public Float(float value); public Float(double value); public Float(String s) throws NumberFormatException; // Constants public static final float MAX_VALUE; public static final float MIN_VALUE; public static final float NEGATIVE_INFINITY; public static final float NaN; public static final float POSITIVE_INFINITY; 1.1public static final Class TYPE; // Class Methods public static native int floatToIntBits(float value); public static native float intBitsToFloat(int bits); public static boolean isInfinite(float v); public static boolean isNaN(float v); public static String toString(float f); public static Float valueOf(String s) throws NumberFormatException; // Public Instance Methods 1.1public byte byteValue(); // Overrides Number public double doubleValue(); // Defines Number public boolean equals(Object obj); // Overrides Object public float floatValue(); // Defines Number public int hashCode(); // Overrides Object public int intValue(); // Defines Number public boolean isInfinite();
http://localhost/java/javaref/javanut/ch25_21.htm (1 of 2) [20/12/2001 11:00:26]
[Chapter 25] 25.21 java.lang.Float (JDK 1.0)
public boolean isNaN(); public long longValue(); // Defines Number 1.1public short shortValue(); // Overrides Number public String toString(); // Overrides Object }
Hierarchy: Object->Number(Serializable)->Float
Returned By: Float.valueOf()
java.lang.ExceptionInInitializerError (JDK 1.1)
http://localhost/java/javaref/javanut/ch25_21.htm (2 of 2) [20/12/2001 11:00:26]
java.lang.IllegalAccessError (JDK 1.0)
[Chapter 25] 25.32 java.lang.Integer (JDK 1.0)
Chapter 25 The java.lang Package
25.32 java.lang.Integer (JDK 1.0) This class provides an immutable object wrapper around the int primitive data type. This class also contains useful minimum and maximum constants and useful conversion methods. parseInt() and valueOf() convert a string to an int or to an Integer, respectively. Each can take a radix argument to specify the base that the value is represented in. decode() also converts a String to an Integer. It assumes a hexadecimal number if the string begins with "0X" or "0x," or an octal number if the string begins with "0". Otherwise, a decimal number is assumed. toString() converts in the other direction, and the static version takes a radix argument. toBinaryString(), toOctalString(), and toHexString() convert an int to a string using base 2, base 8, and base 16. These methods treat the integer as an unsigned value. Other routines return the value of an Integer as various primitive types, and finally, the getInteger() methods return the integer value of a named property from the system property list or the specified default value. public final class Integer extends Number { // Public Constructors public Integer(int value); public Integer(String s) throws NumberFormatException; // Constants public static final int MAX_VALUE; public static final int MIN_VALUE; 1.1public static final Class TYPE; // Class Methods 1.1public static Integer decode(String nm) throws NumberFormatException; public static Integer getInteger(String nm); public static Integer getInteger(String nm, int val); public static Integer getInteger(String nm, Integer val); public static int parseInt(String s, int radix) throws NumberFormatException; public static int parseInt(String s) throws NumberFormatException; public static String toBinaryString(int i); public static String toHexString(int i); public static String toOctalString(int i); public static String toString(int i, int radix); public static String toString(int i); public static Integer valueOf(String s, int radix) throws NumberFormatException; public static Integer valueOf(String s) throws NumberFormatException; // Public Instance Methods 1.1public byte byteValue(); // Overrides Number public double doubleValue(); // Defines Number http://localhost/java/javaref/javanut/ch25_32.htm (1 of 2) [20/12/2001 11:00:26]
[Chapter 25] 25.32 java.lang.Integer (JDK 1.0)
public boolean equals(Object obj); // Overrides Object public float floatValue(); // Defines Number public int hashCode(); // Overrides Object public int intValue(); // Defines Number public long longValue(); // Defines Number 1.1public short shortValue(); // Overrides Number public String toString(); // Overrides Object }
Hierarchy: Object->Number(Serializable)->Integer
Passed To: Integer.getInteger()
Returned By: Integer.decode(), Integer.getInteger(), Integer.valueOf()
java.lang.InstantiationException (JDK 1.0)
java.lang.InternalError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_32.htm (2 of 2) [20/12/2001 11:00:26]
[Chapter 25] 25.36 java.lang.Long (JDK 1.0)
Chapter 25 The java.lang Package
25.36 java.lang.Long (JDK 1.0) This class provides an immutable object wrapper around the long primitive data type. This class also contains useful minimum and maximum constants and useful conversion methods. parseLong() and valueOf() convert a string to a long or to a Long, respectively. Each can take a radix argument to specify the base that the value is represented in. toString() converts in the other direction and may also take a radix argument. toBinaryString(), toOctalString(), and toHexString() convert a long to a string using base 2, base 8, and base 16. These methods treat the long as an unsigned value. Other routines return the value of a Long as various primitive types, and finally, the getLong() methods return the long value of a named property or the value of the specified default. public final class Long extends Number { // Public Constructors public Long(long value); public Long(String s) throws NumberFormatException; // Constants public static final long MAX_VALUE; public static final long MIN_VALUE; 1.1public static final Class TYPE; // Class Methods public static Long getLong(String nm); public static Long getLong(String nm, long val); public static Long getLong(String nm, Long val); public static long parseLong(String s, int radix) throws NumberFormatException; public static long parseLong(String s) throws NumberFormatException; public static String toBinaryString(long i); public static String toHexString(long i); public static String toOctalString(long i); public static String toString(long i, int radix); public static String toString(long i); public static Long valueOf(String s, int radix) throws NumberFormatException; public static Long valueOf(String s) throws NumberFormatException; // Public Instance Methods 1.1public byte byteValue(); // Overrides Number public double doubleValue(); // Defines Number public boolean equals(Object obj); // Overrides Object public float floatValue(); // Defines Number public int hashCode(); // Overrides Object http://localhost/java/javaref/javanut/ch25_36.htm (1 of 2) [20/12/2001 11:00:27]
[Chapter 25] 25.36 java.lang.Long (JDK 1.0)
public int intValue(); // Defines Number public long longValue(); // Defines Number 1.1public short shortValue(); // Overrides Number public String toString(); // Overrides Object }
Hierarchy: Object->Number(Serializable)->Long
Passed To: Long.getLong()
Returned By: Long.getLong(), Long.valueOf()
java.lang.LinkageError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_36.htm (2 of 2) [20/12/2001 11:00:27]
java.lang.Math (JDK 1.0)
[Chapter 25] 25.55 java.lang.Short (JDK 1.1)
Chapter 25 The java.lang Package
25.55 java.lang.Short (JDK 1.1) This class provides an object wrapper around the short primitive type. It defines useful constants for the minimum and maximum values that can be stored by the short type, and also a Class object constant that represents the short type. It also provides various methods for converting Short values to and from strings and other numeric types. Most of the static methods of this class are used to convert a String to a Short object or a short value: the four parseShort() and valueOf() methods parse a number from the specified string, using an optionally specified radix, and return it in one of these two forms. The decode() method parses a number specified in base 10, base 8, or base 16 and returns it as a Short. If the string begins with "0x" or "#", it is interpreted as a hexadecimal number, or if it begins with "0", it is interpreted as an octal number. Otherwise, it is interpreted as a decimal number. Note that this class has two different toString() methods. One is static and converts a short primitive value to a String. The other is the usual toString() method that converts a Short object to a string. Most of the remaining methods convert a Short to various primitive numeric types. public final class Short extends Number { // Public Constructors public Short(short value); public Short(String s) throws NumberFormatException; // Constants public static final short MAX_VALUE; public static final short MIN_VALUE; public static final Class TYPE; // Class Methods public static Short decode(String nm) throws NumberFormatException; public static short parseShort(String s) throws NumberFormatException; public static short parseShort(String s, int radix) throws NumberFormatException; public static String toString(short s); public static Short valueOf(String s, int radix) throws NumberFormatException; public static Short valueOf(String s) throws NumberFormatException; // Public Instance Methods public byte byteValue(); // Overrides Number public double doubleValue(); // Defines Number public boolean equals(Object obj); // Overrides Object public float floatValue(); // Defines Number public int hashCode(); // Overrides Object public int intValue(); // Defines Number public long longValue(); // Defines Number public short shortValue(); // Overrides Number
http://localhost/java/javaref/javanut/ch25_55.htm (1 of 2) [20/12/2001 11:00:27]
[Chapter 25] 25.55 java.lang.Short (JDK 1.1)
public String toString();
// Overrides Object
}
Hierarchy: Object->Number(Serializable)->Short
Returned By: Short.decode(), Short.valueOf()
java.lang.SecurityManager (JDK 1.0)
java.lang.StackOverflowError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_55.htm (2 of 2) [20/12/2001 11:00:27]
[Chapter 28] 28.5 java.net.DatagramPacket (JDK 1.0)
Chapter 28 The java.net Package
28.5 java.net.DatagramPacket (JDK 1.0) This class implements a "packet" of data that may be sent or received over the network through a DatagramSocket. One of the DatagramPacket constructors specifies an array of binary data to be sent with its destination address and port. A packet created with this constructor may then be sent with the send() method of a DatagramSocket. The other DatagramPacket constructor specifies an array of bytes into which data should be received. The receive() method of DatagramSocket waits for data and stores it in a DatagramPacket created in this way. The contents and sender of a received packet may be queried with the DatagramPacket instance methods. public final class DatagramPacket extends Object { // Public Constructors public DatagramPacket(byte[] ibuf, int ilength); public DatagramPacket(byte[] ibuf, int ilength, InetAddress iaddr, int iport); // Public Instance Methods public synchronized InetAddress getAddress(); public synchronized byte[] getData(); public synchronized int getLength(); public synchronized int getPort(); 1.1public synchronized void setAddress(InetAddress iaddr); 1.1public synchronized void setData(byte[] ibuf); 1.1public synchronized void setLength(int ilength); 1.1public synchronized void setPort(int iport); }
Passed To: DatagramSocket.receive(), DatagramSocket.send(), DatagramSocketImpl.receive(), DatagramSocketImpl.send(), MulticastSocket.send()
java.net.ContentHandlerFactory (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_05.htm [20/12/2001 11:00:27]
java.net.DatagramSocket (JDK 1.0)
[Chapter 28] 28.7 java.net.DatagramSocketImpl (JDK 1.1)
Chapter 28 The java.net Package
28.7 java.net.DatagramSocketImpl (JDK 1.1) This abstract class defines the methods necessary to implement communication through datagram and multicast sockets. System programmers may create subclasses of this class when they need to implement datagram or multicast sockets in a nonstandard network environment, such as behind a firewall or on a network that uses a nonstandard transport protocol. Normal applications never need to use or subclass this class. public abstract class DatagramSocketImpl extends Object { // Default Constructor: public DatagramSocketImpl() // Protected Instance Variables protected FileDescriptor fd; protected int localPort; // Protected Instance Methods protected abstract void bind(int lport, InetAddress laddr) throws SocketException; protected abstract void close(); protected abstract void create() throws SocketException; protected FileDescriptor getFileDescriptor(); protected int getLocalPort(); protected abstract byte getTTL() throws IOException; protected abstract void join(InetAddress inetaddr) throws IOException; protected abstract void leave(InetAddress inetaddr) throws IOException; protected abstract int peek(InetAddress i) throws IOException; protected abstract void receive(DatagramPacket p) throws IOException; protected abstract void send(DatagramPacket p) throws IOException; protected abstract void setTTL(byte ttl) throws IOException; }
java.net.DatagramSocket (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_07.htm [20/12/2001 11:00:28]
java.net.FileNameMap (JDK 1.1)
[Chapter 30] 30.3 java.util.Date (JDK 1.0)
Chapter 30 The java.util Package
30.3 java.util.Date (JDK 1.0) This class represents dates and times. It lets you work with them in a system-independent way. You can create a Date by specifying the number of milliseconds from the epoch (midnight GMT, January 1st, 1970), or by specifying the year, month, date, and optionally, the hour, minute, and second. Years are specified as the number of years since 1900. If you call the Date constructor with no arguments, the Date is initialized to the current time and date. The instance methods of the class allow you to get and set the various date and time fields, to compare dates and times, and to convert dates to and from string representations. In Java 1.1, many of the date methods have been deprecated in favor of the methods of the Calendar class. public class Date extends Object implements Serializable, Cloneable { // Public Constructors public Date(); public Date(long date); # public Date(int year, int month, int date); # public Date(int year, int month, int date, int hrs, int min); # public Date(int year, int month, int date, int hrs, int min, int sec); # public Date(String s); // Class Methods # public static long UTC(int year, int month, int date, int hrs, int min, int sec); # public static long parse(String s); // Public Instance Methods public boolean after(Date when); public boolean before(Date when); public boolean equals(Object obj); // Overrides Object # public int getDate(); # public int getDay(); # public int getHours(); # public int getMinutes(); # public int getMonth(); # public int getSeconds(); public long getTime(); # public int getTimezoneOffset(); # public int getYear(); public int hashCode(); // Overrides Object # public void setDate(int date); # public void setHours(int hours); # public void setMinutes(int minutes); # public void setMonth(int month); # public void setSeconds(int seconds); public void setTime(long time); http://localhost/java/javaref/javanut/ch30_03.htm (1 of 2) [20/12/2001 11:00:29]
[Chapter 30] 30.3 java.util.Date (JDK 1.0)
# # #
public public public public
void setYear(int year); String toGMTString(); String toLocaleString(); String toString(); // Overrides Object
}
Passed To: Calendar.setTime(), Date.after(), Date.before(), DateFormat.format(), GregorianCalendar.setGregorianChange(), SimpleDateFormat.format(), SimpleTimeZone.inDaylightTime(), TimeZone.inDaylightTime()
Returned By: Calendar.getTime(), DateFormat.parse(), GregorianCalendar.getGregorianChange(), SimpleDateFormat.parse()
java.util.Calendar (JDK 1.1)
java.util.Dictionary (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_03.htm (2 of 2) [20/12/2001 11:00:29]
[Chapter 29] 29.7 java.text.DateFormat (JDK 1.1)
Chapter 29 The java.text Package
29.7 java.text.DateFormat (JDK 1.1) This class formats and parses dates and times in a locale-specific way. As an abstract class, it cannot be instantiated directly, but it provides a number of static methods that return instances of a concrete subclass which you can use to format dates in a variety of ways. The getDateInstance() methods return a DateFormat object suitable for formatting dates in either the default locale or a specified locale. A formatting style may also optionally be specified--the constants FULL, LONG, MEDIUM, SHORT, and DEFAULT specify this style. Similarly, the getTimeInstance() methods return a DateFormat object that formats and parses times, and the getDateTimeInstance() methods return a DateFormat object that formats both dates and times. These methods also optionally take a format style constant and a Locale. Finally, getInstance() returns a default DateFormat object that formats both dates and times in the SHORT format. Once you have created a DateFormat object, you can use the setCalendar() and setTimeZone() methods if you want to format the date using a calendar or time zone other than the default. The various format() methods convert java.util.Date objects to strings, using whatever format is encapsulated in the DateFormat object. The parse() and parseObject() methods perform the reverse operation--they parse a string formatted according to the rules of the DateFormat object and convert it into a Date object. The DEFAULT, FULL, MEDIUM, LONG, and SHORT constants are used to specify how verbose or compact the formatted date or time should be. The remaining constants, which all end with _FIELD, specify various fields of formatted dates and times and are used with the FieldPosition object that is optionally passed to format(). public abstract class DateFormat extends Format implements Cloneable { // Protected Constructor protected DateFormat(); // Format Style Constants public static final int DEFAULT; public static final int FULL; public static final int LONG; public static final int MEDIUM; public static final int SHORT; // Date and Time Field Constants public static final int ERA_FIELD; public static final int YEAR_FIELD; public static final int MONTH_FIELD; public static final int WEEK_OF_MONTH_FIELD, WEEK_OF_YEAR_FIELD; public static final int DATE_FIELD, DAY_OF_YEAR_FIELD; public static final int DAY_OF_WEEK_FIELD, DAY_OF_WEEK_IN_MONTH_FIELD; public static final int TIMEZONE_FIELD; public static final int AM_PM_FIELD; public static final int HOUR0_FIELD, HOUR1_FIELD; public static final int HOUR_OF_DAY0_FIELD, HOUR_OF_DAY1_FIELD; public static final int MINUTE_FIELD; public static final int SECOND_FIELD;
http://localhost/java/javaref/javanut/ch29_07.htm (1 of 3) [20/12/2001 11:00:29]
[Chapter 29] 29.7 java.text.DateFormat (JDK 1.1)
public static final int MILLISECOND_FIELD; // Protected Instance Variables protected Calendar calendar; protected NumberFormat numberFormat; // Class Methods public static Locale[] getAvailableLocales(); public static final DateFormat getDateInstance(); public static final DateFormat getDateInstance(int style); public static final DateFormat getDateInstance(int style, Locale aLocale); public static final DateFormat getDateTimeInstance(); public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle); public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale); public static final DateFormat getInstance(); public static final DateFormat getTimeInstance(); public static final DateFormat getTimeInstance(int style); public static final DateFormat getTimeInstance(int style, Locale aLocale); // Public Instance Methods public Object clone(); // Overrides Format public boolean equals(Object obj); // Overrides Object public final StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition); // Defines Format public abstract StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition); public final String format(Date date); public Calendar getCalendar(); public NumberFormat getNumberFormat(); public TimeZone getTimeZone(); public int hashCode(); // Overrides Object public boolean isLenient(); public Date parse(String text) throws ParseException; public abstract Date parse(String text, ParsePosition pos); public Object parseObject(String source, ParsePosition pos); // Defines Format public void setCalendar(Calendar newCalendar); public void setLenient(boolean lenient); public void setNumberFormat(NumberFormat newNumberFormat); public void setTimeZone(TimeZone zone); }
Hierarchy: Object->Format(Serializable, Cloneable)->DateFormat(Cloneable)
Extended By: SimpleDateFormat
http://localhost/java/javaref/javanut/ch29_07.htm (2 of 3) [20/12/2001 11:00:29]
[Chapter 29] 29.7 java.text.DateFormat (JDK 1.1)
Returned By: DateFormat.getDateInstance(), DateFormat.getDateTimeInstance(), DateFormat.getInstance(), DateFormat.getTimeInstance()
java.text.Collator (JDK 1.1)
java.text.DateFormatSymbols (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_07.htm (3 of 3) [20/12/2001 11:00:29]
[Chapter 29] 29.8 java.text.DateFormatSymbols (JDK 1.1)
Chapter 29 The java.text Package
29.8 java.text.DateFormatSymbols (JDK 1.1) This class defines accessor methods for the various pieces of data, such as names of months and days, used by SimpleDateFormat to format and parse dates and times. You do not typically use this class unless you are formatting dates for an unsupported locale or in some highly customized way. public class DateFormatSymbols extends Object implements Serializable, Cloneable { // Public Constructors public DateFormatSymbols(); public DateFormatSymbols(Locale locale); // Public Instance Methods public Object clone(); // Overrides Object public boolean equals(Object obj); // Overrides Object public String[] getAmPmStrings(); public String[] getEras(); public String getLocalPatternChars(); public String[] getMonths(); public String[] getShortMonths(); public String[] getShortWeekdays(); public String[] getWeekdays(); public String[][] getZoneStrings(); public int hashCode(); // Overrides Object public void setAmPmStrings(String[] newAmpms); public void setEras(String[] newEras); public void setLocalPatternChars(String newLocalPatternChars); public void setMonths(String[] newMonths); public void setShortMonths(String[] newShortMonths); public void setShortWeekdays(String[] newShortWeekdays); public void setWeekdays(String[] newWeekdays); public void setZoneStrings(String[][] newZoneStrings); }
Passed To: SimpleDateFormat(), SimpleDateFormat.setDateFormatSymbols()
Returned By: SimpleDateFormat.getDateFormatSymbols()
http://localhost/java/javaref/javanut/ch29_08.htm (1 of 2) [20/12/2001 11:00:29]
[Chapter 29] 29.8 java.text.DateFormatSymbols (JDK 1.1)
java.text.DateFormat (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_08.htm (2 of 2) [20/12/2001 11:00:29]
java.text.DecimalFormat (JDK 1.1)
[Chapter 29] 29.10 java.text.DecimalFormatSymbols (JDK 1.1)
Chapter 29 The java.text Package
29.10 java.text.DecimalFormatSymbols (JDK 1.1) This class defines the various characters and strings, such as the decimal point, percent sign, and thousands separator, used by DecimalFormat when formatting numbers. You do not typically use this class directly unless you are formatting dates for an unsupported locale or in some highly customized way. public final class DecimalFormatSymbols extends Object implements Cloneable, Serializable { // Public Constructors public DecimalFormatSymbols(); public DecimalFormatSymbols(Locale locale); // Public Instance Methods public Object clone(); // Overrides Object public boolean equals(Object obj); // Overrides Object public char getDecimalSeparator(); public char getDigit(); public char getGroupingSeparator(); public String getInfinity(); public char getMinusSign(); public String getNaN(); public char getPatternSeparator(); public char getPerMill(); public char getPercent(); public char getZeroDigit(); public int hashCode(); // Overrides Object public void setDecimalSeparator(char decimalSeparator); public void setDigit(char digit); public void setGroupingSeparator(char groupingSeparator); public void setInfinity(String infinity); public void setMinusSign(char minusSign); public void setNaN(String NaN); public void setPatternSeparator(char patternSeparator); public void setPerMill(char perMill); public void setPercent(char percent); public void setZeroDigit(char zeroDigit); }
http://localhost/java/javaref/javanut/ch29_10.htm (1 of 2) [20/12/2001 11:00:30]
[Chapter 29] 29.10 java.text.DecimalFormatSymbols (JDK 1.1)
Passed To: DecimalFormat(), DecimalFormat.setDecimalFormatSymbols()
Returned By: DecimalFormat.getDecimalFormatSymbols()
java.text.DecimalFormat (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_10.htm (2 of 2) [20/12/2001 11:00:30]
java.text.FieldPosition (JDK 1.1)
[Chapter 9] 9.2 Custom Serialization
Chapter 9 Object Serialization
9.2 Custom Serialization Not every piece of program state can, or should be, serialized. Some things, like FileDescriptor objects, are inherently platform-specific or virtual-machine-dependent. If a FileDescriptor were serialized, it would have no meaning when deserialized in a different virtual machine. For this reason, and also for important security reasons, not all objects can be serialized. Only classes that implement the Serializable or Externalizable interface can be written to or read from an object stream. Serializable is a marker interface, like Cloneable: it doesn't define any methods and serves only to specify whether an object is allowed to be serialized. The Externalizable interface does define methods, and is used by objects that want advanced control over the way they are written and read. We'll see more about Externalizable objects later in this chapter. It is worth noting at this point that Component implements Serializable, which means that all AWT components can be serialized. Even when an object is serializable, it may not make sense for it to serialize all of its state. For example, in the Scribble example shown in Chapter 8, New AWT Features, the last_x and last_y fields store the current position of the mouse and only contain valid data while the user has a mouse button pressed. The values of these fields will never be of interest (or use) when such an object is deserialized, so there is no need to bother saving the values of these fields as part of the Scribble object's state. To tell the serialization mechanism that a field should not be saved, simply declare it transient: protected transient short last_x, last_y; // Temporary fields for mouse pos. The transient modifier keyword has always been a legal part of the Java language, but it was not assigned any meaning until Java 1.1. There are situations where a field is not transient--i.e., it does contain an important part of an object's state--but for some reason it cannot be successfully serialized. One example is a custom AWT component that computes its preferred size based on the size of the text it displays. Because fonts have slight size variations from platform to platform, this pre-computed preferred size will not be valid if the component is serialized on one type of platform and deserialized on another. Since the preferred size fields will not be valid when deserialized, they should be declared transient so that they don't take up space in the serialized object. But in this case, their values should be re-computed when the object is deserialized. A class can define custom serialization and deserialization behavior for its objects by implementing writeObject() and readObject() methods. Suprisingly, these methods are not defined by any interface. The methods must be declared private, which is also suprising if you think about it, as they are called from outside of the class during serialization and deserialization. If a class defines these methods, the appropriate one is invoked by the ObjectOutputStream or ObjectInputStream when an object is serialized or deserialized. For example, our custom component might define a readObject() method to give it an opportunity to http://localhost/java/javaref/javanut/ch09_02.htm (1 of 3) [20/12/2001 11:00:30]
[Chapter 9] 9.2 Custom Serialization
re-compute its preferred size upon deserialization. The method might look like this: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Deserialize the component in the usual way. this.computePreferredSize(); // But then go recompute its size. } This method calls the defaultReadObject() method of the ObjectInputStream to deserialize the object as normal, and then takes care of the post-processing it needs to perform. Example 9.2 is a more complete example of custom serialization. It shows a class that implements a growable array of numbers. This class defines a writeObject() method to do some pre-processing before being serialized and a readObject() method to do post-processing after deserialization. Example 9.2: Serialization with Pre- and Post-Processing import java.io.*; /** A simple class that implements a growable array or ints, and knows * how to serialize itself as efficiently as a non-growable array. */ public class IntList implements Serializable { private int[] nums = new int[8]; // An array to store the numbers. private transient int size = 0; // Index of next unused element of nums[]. /** Return an element of the array */ public int elementAt(int index) throws ArrayIndexOutOfBoundsException { if (index >= size) throw new ArrayIndexOutOfBoundsException(index); else return nums[index]; } /** Add an int to the array, growing the array if necessary. */ public void add(int x) { if (nums.length == size) resize(nums.length*2); // Grow array, if needed. nums[size++] = x; // Store the int in it. } /** An internal method to change the allocated size of the array. */ protected void resize(int newsize) { int[] oldnums = nums; nums = new int[newsize]; // Create a new array. System.arraycopy(oldnums, 0, nums, 0, size); // Copy array elements. } /** Get rid of unused array elements before serializing the array. */ private void writeObject(ObjectOutputStream out) throws IOException { if (nums.length > size) resize(size); // Compact the array. out.defaultWriteObject(); // Then write it out normally. } /** Compute the transient size field after deserializing the array. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Read the array normally.
http://localhost/java/javaref/javanut/ch09_02.htm (2 of 3) [20/12/2001 11:00:30]
[Chapter 9] 9.2 Custom Serialization
size = nums.length;
// Restore the transient field.
} }
Simple Serialization
http://localhost/java/javaref/javanut/ch09_02.htm (3 of 3) [20/12/2001 11:00:30]
Serialization and Class Versioning
[Chapter 24] 24.39 java.io.ObjectInputStream (JDK 1.1)
Chapter 24 The java.io Package
24.39 java.io.ObjectInputStream (JDK 1.1) ObjectInputStream is used to deserialize objects, arrays, and other values from a stream that was previously created with an ObjectOutputStream. The readObject() method deserializes objects and arrays (which should then be cast to the appropriate type); various other methods are used to read primitive data values from the stream. Note that only objects that implement the Serializable interface or the Externalizable interface can be serialized and deserialized. The defaultReadObject() method may only be called from the readObject() method of an object that is currently being deserialized. It allows an object to perform additional processing after deserializing itself. The registerValidation() method may also only be called from the readObject() method of an object being deserialized. It registers an ObjectInputValidation object (typically the object being deserialized) to be notified when a complete tree of objects has been deserialized and the original call to the readObject() method of the ObjectInputStream is about to return to its caller. The remaining methods include miscellaneous stream manipulation methods and several protected methods for use by subclasses that want to customize the deserialization behavior of ObjectInputStream. public class ObjectInputStream extends InputStream implements ObjectInput { // Public Constructor public ObjectInputStream(InputStream in) throws IOException, StreamCorruptedException; // Public Instance Methods public int available() throws IOException; // Overrides InputStream public void close() throws IOException; // Overrides InputStream public final void defaultReadObject() throws IOException, ClassNotFoundException, NotActiveException; public int read() throws IOException; // Defines InputStream public int read(byte[] data, int offset, int length) throws IOException; // Overrides InputStream public boolean readBoolean() throws IOException; // From DataInput public byte readByte() throws IOException; // From DataInput public char readChar() throws IOException; // From DataInput public double readDouble() throws IOException; // From DataInput public float readFloat() throws IOException; // From DataInput public void readFully(byte[] data) throws IOException; // From DataInput public void readFully(byte[] data, int offset, int size) throws IOException; // From DataInput public int readInt() throws IOException; // From DataInput public String readLine() throws IOException; // From DataInput public long readLong() throws IOException; // From DataInput public final Object readObject() throws OptionalDataException, public final Object readObject() 'u'ClassNotFoundException, IOException; // From ObjectInput public short readShort() throws IOException; // From DataInput
http://localhost/java/javaref/javanut/ch24_39.htm (1 of 2) [20/12/2001 11:00:30]
[Chapter 24] 24.39 java.io.ObjectInputStream (JDK 1.1)
public public public public
String readUTF() throws IOException; // From DataInput int readUnsignedByte() throws IOException; // From DataInput int readUnsignedShort() throws IOException; // From DataInput synchronized void registerValidation(ObjectInputValidation obj,
int prio) public synchronized void registerValidation'u'throws NotActiveException, InvalidObjectException; public int skipBytes(int len) throws IOException; // From DataInput // Protected Instance Methods protected final boolean enableResolveObject(boolean enable) throws SecurityException; protected void readStreamHeader() throws IOException, StreamCorruptedException; protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException; protected Object resolveObject(Object obj) throws IOException; }
Hierarchy: Object->InputStream->ObjectInputStream(ObjectInput(DataInput))
java.io.ObjectInput (JDK 1.1)
java.io.ObjectInputValidation (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_39.htm (2 of 2) [20/12/2001 11:00:30]
[Chapter 24] 24.59 java.io.Serializable (JDK 1.1)
Chapter 24 The java.io Package
24.59 java.io.Serializable (JDK 1.1) The Serializable interface defines no methods or constants. A class should implement this interface simply to indicate that it allows itself to be serialized and deserialized with ObjectOutputStream.writeObject() and ObjectInputStream.readObject(). Objects that need special handling during serialization or deserialization may implement one or both of the following methods. Note, however, that these methods are not part of the Serializable interface: private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; Typically the writeObject() method performs any necessary cleanup or preparation for serialization, invokes the defaultWriteObject() method of the ObjectOutputStream to serialize the non-transient fields of the class, and then optionally writes any additional data that are required. Similarly, the readObject() method typically invokes the defaultReadObject() method of the ObjectInputStream, reads any additional data written by the corresponding writeObject() method, and finally performs any extra initialization required by the object. The readObject() method may also register an ObjectInputValidation object to validate the object once it is completely deserialized. public interface Serializable { }
Extended By: Externalizable
Implemented By: BitSet, Boolean, BorderLayout, BreakIterator, Calendar, CardLayout, Character, CheckboxGroup, Class, Collator, Color, Component, Cursor, Date, DateFormatSymbols, DecimalFormatSymbols, Dimension, Event, EventObject, File, FlowLayout, Font, FontMetrics, Format, GridBagConstraints, GridBagLayout, http://localhost/java/javaref/javanut/ch24_59.htm (1 of 2) [20/12/2001 11:00:30]
[Chapter 24] 24.59 java.io.Serializable (JDK 1.1)
GridLayout, Hashtable, InetAddress, Insets, Locale, MediaTracker, MenuComponent, MenuShortcut, Number, ObjectStreamClass, Point, Polygon, PropertyChangeSupport, Random, Rectangle, String, StringBuffer, SystemColor, Throwable, TimeZone, URL, Vector, VetoableChangeSupport
java.io.SequenceInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_59.htm (2 of 2) [20/12/2001 11:00:30]
java.io.StreamCorruptedException (JDK 1.1)
[Chapter 24] 24.42 java.io.ObjectOutputStream (JDK 1.1)
Chapter 24 The java.io Package
24.42 java.io.ObjectOutputStream (JDK 1.1) The ObjectOutputStream is used to serialize objects, arrays, and other values to a stream. The writeObject() method serializes an object or array, and various other methods are used to write primitive data values to the stream. Note that only objects that implement the Serializable interface or the Externalizable interface can be serialized. The defaultWriteObject() may only be called from the writeObject() method of a Serializable object. It allows an object to perform additional processing before or after serializing itself. The remaining methods of ObjectOutputStream are miscellaneous stream manipulation methods and protected methods for use by subclasses that want to customize its serialization behavior. public class ObjectOutputStream extends OutputStream implements ObjectOutput { // Public Constructor public ObjectOutputStream(OutputStream out) throws IOException; // Public Instance Methods public void close() throws IOException; // Overrides OutputStream public final void defaultWriteObject() throws IOException; public void flush() throws IOException; // Overrides OutputStream public void reset() throws IOException; public void write(int data) throws IOException; // Defines OutputStream public void write(byte[] b) throws IOException; // Overrides OutputStream public void write(byte[] b, int off, int len) throws IOException; // Overrides OutputStream public void writeBoolean(boolean data) throws IOException; // From DataOutput public void writeByte(int data) throws IOException; // From DataOutput public void writeBytes(String data) throws IOException; // From DataOutput public void writeChar(int data) throws IOException; // From DataOutput public void writeChars(String data) throws IOException; // From DataOutput public void writeDouble(double data) throws IOException; // From DataOutput public void writeFloat(float data) throws IOException; // From DataOutput public void writeInt(int data) throws IOException; // From DataOutput public void writeLong(long data) throws IOException; // From DataOutput public final void writeObject(Object obj) throws IOException; // From ObjectOutput public void writeShort(int data) throws IOException; // From DataOutput public void writeUTF(String data) throws IOException; // From DataOutput // Protected Instance Methods
http://localhost/java/javaref/javanut/ch24_42.htm (1 of 2) [20/12/2001 11:00:31]
[Chapter 24] 24.42 java.io.ObjectOutputStream (JDK 1.1)
protected protected protected SecurityException; protected protected }
void annotateClass(Class cl) throws IOException; void drain() throws IOException; final boolean enableReplaceObject(boolean enable) throws Object replaceObject(Object obj) throws IOException; void writeStreamHeader() throws IOException;
Hierarchy: Object->OutputStream->ObjectOutputStream(ObjectOutput(DataOutput))
Passed To: AWTEventMulticaster.save(), AWTEventMulticaster.saveInternal()
java.io.ObjectOutput (JDK 1.1)
java.io.ObjectStreamClass (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_42.htm (2 of 2) [20/12/2001 11:00:31]
[Chapter 31] 31.7 java.util.zip.Deflater (JDK 1.1)
Chapter 31 The java.util.zip Package
31.7 java.util.zip.Deflater (JDK 1.1) This class implements the general ZLIB data compression algorithm used by the gzip and PKZip compression programs. The constants defined by this class are used to specify the compression strategy to be used and the compression speed/strength trade-off level to be used. If you set the nowrap argument to the constructor to true, then the ZLIB header and checksum data are omitted from the compressed output, which is the format that both gzip and PKZip use. The important methods of this class are setInput(), which specifies input data to be compressed, and deflate(), which compresses the data and returns the compressed output. The remaining methods exist so that Deflater can be used for stream-based compression, as it is in higher-level classes such as GZIPOutputStream and ZipOutputStream. These stream classes are sufficient in most cases. Most applications do not need to use Deflater directly. The Inflater class uncompresses data compressed with a Deflater object. public class Deflater extends Object { // Public Constructors public Deflater(int level, boolean nowrap); public Deflater(int level); public Deflater(); // Constants public static final int BEST_COMPRESSION; public static final int BEST_SPEED; public static final int DEFAULT_COMPRESSION; public static final int DEFAULT_STRATEGY; public static final int DEFLATED; public static final int FILTERED; public static final int HUFFMAN_ONLY; public static final int NO_COMPRESSION; // Public Instance Methods public synchronized native int deflate(byte[] b, int off, int len); public int deflate(byte[] b); public synchronized native void end(); public synchronized void finish(); public synchronized boolean finished(); public synchronized native int getAdler(); public synchronized native int getTotalIn(); public synchronized native int getTotalOut(); public boolean needsInput(); public synchronized native void reset();
http://localhost/java/javaref/javanut/ch31_07.htm (1 of 2) [20/12/2001 11:00:31]
[Chapter 31] 31.7 java.util.zip.Deflater (JDK 1.1)
public synchronized native void setDictionary(byte[] b, int off, int len); public void setDictionary(byte[] b); public synchronized void setInput(byte[] b, int off, int len); public void setInput(byte[] b); public synchronized void setLevel(int Level); public synchronized void setStrategy(int strategy); // Protected Instance Methods protected void finalize(); // Overrides Object }
Passed To: DeflaterOutputStream()
Type Of: DeflaterOutputStream.def
java.util.zip.DataFormatException (JDK 1.1)
java.util.zip.DeflaterOutputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_07.htm (2 of 2) [20/12/2001 11:00:31]
[Chapter 4] 4.4 Deprecated Features
Chapter 4 What's New in Java 1.1
4.4 Deprecated Features Although you can use the old AWT event model in Java 1.1, it has been officially "deprecated," and its use in new software is discouraged. When you compile code that uses the 1.0 event model, you'll be made aware of this by the "deprecation warning" that the javac compiler issues. This warning notifies you that your code relies on methods or classes in the Java API that have been superseded by newer, preferred alternatives. If you compile using the -deprecation flag, javac provides a detailed warning about each use of a deprecated feature. You can simply ignore these warnings, but when time permits, the better approach is to update your code so that it no longer relies on deprecated features of the Java API. While it is not strictly true to say that deprecated features are "unsupported," they will almost certainly receive far less support in practice than the features that replace them. The reason that the compiler is able to issue deprecation warnings at all is the addition of a new @deprecated tag to the documentation-comment syntax of Java 1.1. As you may be aware, comments that begin with the /** character sequence are treated specially in Java, and are used by the javadoc tool to automatically generate online documentation for packages, classes, methods, and fields. Prior to Java 1.1, the compiler ignored the contents of documentation comments. In Java 1.1, however, it scans these comments for the @deprecated tag. If it is found, the compiler marks the class, interface, constructor, method, or field following the comment as deprecated, and issues a warning when the deprecated feature is used. The old AWT event-handling model is not the only Java 1.0 feature that has been deprecated in Java 1.1; merely the one you are most likely to encounter first. A number of common AWT component methods have been renamed, to follow a more regular naming scheme that fits the JavaBeans naming conventions. These methods can be invoked by the old name or the new, but if you use the old name, you'll be rewarded with a deprecation warning. Fortunately, in simple cases like this, it is trivial to write a script or program to mechanically convert from the old name to the new. Other areas of the Java API have been deprecated as well. You'll notice that a few of the input and output stream classes in the java.io package have been deprecated and superseded by "Reader" and "Writer" stream classes, for example.
The New AWT Event Model
http://localhost/java/javaref/javanut/ch04_04.htm [20/12/2001 11:00:31]
Other AWT Improvements
[Chapter 10] 10.9 Naming Patterns and Conventions
Chapter 10 Java Beans
10.9 Naming Patterns and Conventions As we've seen, beanbox programs may rely on introspection of a bean to determine the list of properties, events, and methods it supports. In order for this to work, bean developers must follow a set of standard naming conventions, sometimes referred to as JavaBeans "design patterns." These patterns specify, for example, that the getter and setter accessor methods for a property should begin with get and set. Not all of the patterns are absolute requirements. If a bean has accessor methods with different names, it is possible to use a PropertyDescriptor object, specified in a BeanInfo class, to specify the accessor methods for the property. Note, however, that although an accessor method name is not required to follow the pattern, the method is required to have the exact type signature specified by the pattern. This section lists the design patterns for bean properties, events, and methods. It also lists other conventions and requirements that you should keep in mind when developing beans.
Java Bean Patterns Beans class name: Any superclass: Any constructor: Must have a no-argument constructor, or a serialized template file packaging: JAR file manifest entry specifies Java-Bean: True Properties (property p of type T) getter: public T getP()
http://localhost/java/javaref/javanut/ch10_09.htm (1 of 5) [20/12/2001 11:00:31]
[Chapter 10] 10.9 Naming Patterns and Conventions
setter: public void setP(T value) Boolean Properties (property p of type boolean) getter: public boolean getP() (boolean value) or public boolean is P() setter: public void setP Indexed Properties (property p of type T[]) array getter: public T[] getP() array setter: public void setP(T[] value) element getter: public T getP(int index) element setter: public void setP(int index, T value) Bound Properties (property p of type T) getter: Same as regular property setter: Same as regular property listeners: One event listener list for all bound properties of a bean listener registration: public void addPropertyChangeListener (PropertyChangeListener l)
http://localhost/java/javaref/javanut/ch10_09.htm (2 of 5) [20/12/2001 11:00:31]
[Chapter 10] 10.9 Naming Patterns and Conventions
listener removal: public void removePropertyChangeListener (PropertyChangeListener l) Constrained Properties (property p of type T) getter: Same as regular property setter: public void setP(T value) throws PropertyVetoException listeners: One event listener list for all constrained properties of a bean listener registration: public void addVetoableChangeListener (VetoableChangeListener l) listener removal: public void removeVetoableChangeListener (VetoableChangeListener l) Events (event named E) event class name: EEvent listener name: EListener listener methods: public void methodname(EEvent e) listener registration: public void addEListener(EListener l) listener removal: public void removeEListener(EListener l) Unicast Events (event named E only one listener allowed)
http://localhost/java/javaref/javanut/ch10_09.htm (3 of 5) [20/12/2001 11:00:31]
[Chapter 10] 10.9 Naming Patterns and Conventions
listener registration: public void addEListener(EListener l) throws TooManyListenersException listener removal: public void removeEListener(EListener l) Methods method name: Any method args: Any; some tools only recognize no-argument methods BeanInfo Classes (for bean B) class name: BBeanInfo Property Editors (for properties of type T) class name: TEditor constructor: Must have a no-argument constructor Property Editors (for individual properties) class name: Any; register via PropertyDescriptor constructor: Must have a no-argument constructor Customizers (for bean B) class name: Any; register via BeanDescriptor (BCustomizer by convention) superclass: http://localhost/java/javaref/javanut/ch10_09.htm (4 of 5) [20/12/2001 11:00:31]
[Chapter 10] 10.9 Naming Patterns and Conventions
Must be a component; typically extends Panel constructor: Must have a no-argument constructor Documentation File (for bean B) default docs: B.html localized docs: locale/B.html
Defining a Bean Customizer
http://localhost/java/javaref/javanut/ch10_09.htm (5 of 5) [20/12/2001 11:00:31]
Internationalization
[Chapter 25] 25.49 java.lang.Process (JDK 1.0)
Chapter 25 The java.lang Package
25.49 java.lang.Process (JDK 1.0) This class describes a process that is running externally to the Java interpreter. Note that a Process is a very different thing than a Thread. The Process class is abstract and may not be instantiated. Call one of the Runtime.exec() methods to start a process and return a corresponding Process object. waitFor() blocks until the Process exits. exitValue() returns the exit code of the process. destroy() kills the process. getInputStream() returns an InputStream from which you can read any bytes the process sends to its standard error stream. getErrorStream() returns an InputStream from which you can read any bytes the process sends to its standard output stream. getOutputStream() returns an OutputStream that you can use to send bytes to the standard input stream of the process. public abstract class Process extends Object { // Default Constructor: public Process() // Public Instance Methods public abstract void destroy(); public abstract int exitValue(); public abstract InputStream getErrorStream(); public abstract InputStream getInputStream(); public abstract OutputStream getOutputStream(); public abstract int waitFor() throws InterruptedException; }
Returned By: Runtime.exec()
java.lang.OutOfMemoryError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_49.htm [20/12/2001 11:00:32]
java.lang.Runnable (JDK 1.0)
[Chapter 20] 20.29 java.awt.event.WindowEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.29 java.awt.event.WindowEvent (JDK 1.1) An event of this type indicates that an important action has occurred for a Window object. Call getWindow() to determine the Window object that is the source of this event. Call getID() to determine the specific type of event that has occurred. Each of the following seven constants corresponds to one of the methods of the WindowListener interface: WINDOW_OPENED This type indicates that the window has been created and opened; it is only delivered the first time that a window is opened. WINDOW_CLOSING This type indicates that the user has requested that the window be closed through the system menu, or through a close button on the window's border, or by invoking a platform-defined keystroke, such as Alt-F4 in Windows. The application should respond to this event by calling hide() or destroy() on the Window object. WINDOW_CLOSED This event type is delivered after a window is closed by a call to hide() or destroy(). WINDOW_ICONIFIED This event type is delivered when the user iconifies the window. WINDOW_DEICONIFIED This event type is delivered when the user de-iconifies the window. WINDOW_ACTIVATED This event type is delivered when the window is activated--that is, when it is given the keyboard focus and becomes the "active" window. WINDOW_DEACTIVATED This event type is delivered when the window ceases to be the active window, typically when the user activates some other window.
http://localhost/java/javaref/javanut/ch20_29.htm (1 of 2) [20/12/2001 11:00:32]
[Chapter 20] 20.29 java.awt.event.WindowEvent (JDK 1.1)
public class WindowEvent extends ComponentEvent { // Public Constructor public WindowEvent(Window source, int id); // Constants public static final int WINDOW_ACTIVATED; public static final int WINDOW_CLOSED; public static final int WINDOW_CLOSING; public static final int WINDOW_DEACTIVATED; public static final int WINDOW_DEICONIFIED; public static final int WINDOW_FIRST; public static final int WINDOW_ICONIFIED; public static final int WINDOW_LAST; public static final int WINDOW_OPENED; // Public Instance Methods public Window getWindow(); public String paramString(); // Overrides ComponentEvent }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ComponentEvent->WindowEvent
Passed To: AWTEventMulticaster.windowActivated(), AWTEventMulticaster.windowClosed(), AWTEventMulticaster.windowClosing(), AWTEventMulticaster.windowDeactivated(), AWTEventMulticaster.windowDeiconified(), AWTEventMulticaster.windowIconified(), AWTEventMulticaster.windowOpened(), Window.processWindowEvent(), WindowAdapter.windowActivated(), WindowAdapter.windowClosed(), WindowAdapter.windowClosing(), WindowAdapter.windowDeactivated(), WindowAdapter.windowDeiconified(), WindowAdapter.windowIconified(), WindowAdapter.windowOpened(), WindowListener.windowActivated(), WindowListener.windowClosed(), WindowListener.windowClosing(), WindowListener.windowDeactivated(), WindowListener.windowDeiconified(), WindowListener.windowIconified(), WindowListener.windowOpened()
java.awt.event.WindowAdapter (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_29.htm (2 of 2) [20/12/2001 11:00:32]
java.awt.event.WindowListener (JDK 1.1)
[Chapter 22] 22.8 java.awt.peer.DialogPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.8 java.awt.peer.DialogPeer (JDK 1.0) public abstract interface DialogPeer extends WindowPeer { // Public Instance Methods public abstract void setResizable(boolean resizeable); public abstract void setTitle(String title); }
Hierarchy: (DialogPeer(WindowPeer(ContainerPeer(ComponentPeer))))
Extended By: FileDialogPeer
Returned By: Toolkit.createDialog()
java.awt.peer.ContainerPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_08.htm [20/12/2001 11:00:32]
java.awt.peer.FileDialogPeer (JDK 1.0)
[Chapter 18] 18.22 java.awt.FileDialog (JDK 1.0)
Chapter 18 The java.awt Package
18.22 java.awt.FileDialog (JDK 1.0) This class represents a file selection dialog box. The constants LOAD and SAVE are values of an optional constructor argument that specifies whether the dialog should be an Open File dialog or a Save As dialog. You may specify a FilenameFilter object to control which files are displayed in the dialog. The inherited show() method pops the dialog up. For dialogs of this type, show() blocks, not returning until the user has selected a file and dismissed the dialog (which pops down automatically--you don't have to call hide()). Once show() has returned, use getFile() to get the name of the file the user selected. public class FileDialog extends Dialog { // Public Constructors 1.1 public FileDialog(Frame parent); public FileDialog(Frame parent, String title); public FileDialog(Frame parent, String title, int mode); // Constants public static final int LOAD; public static final int SAVE; // Public Instance Methods public void addNotify(); // Overrides Dialog public String getDirectory(); public String getFile(); public FilenameFilter getFilenameFilter(); public int getMode(); public synchronized void setDirectory(String dir); public synchronized void setFile(String file); public synchronized void setFilenameFilter(FilenameFilter filter); 1.1 public void setMode(int mode); // Protected Instance Methods protected String paramString(); // Overrides Dialog }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)-> Container->Window->Dialog->FileDialog
http://localhost/java/javaref/javanut/ch18_22.htm (1 of 2) [20/12/2001 11:00:33]
[Chapter 18] 18.22 java.awt.FileDialog (JDK 1.0)
Passed To: Toolkit.createFileDialog()
java.awt.EventQueue (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_22.htm (2 of 2) [20/12/2001 11:00:33]
java.awt.FlowLayout (JDK 1.0)
[Chapter 22] 22.9 java.awt.peer.FileDialogPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.9 java.awt.peer.FileDialogPeer (JDK 1.0) public abstract interface FileDialogPeer extends DialogPeer { // Public Instance Methods public abstract void setDirectory(String dir); public abstract void setFile(String file); public abstract void setFilenameFilter(FilenameFilter filter); }
Hierarchy: (FileDialogPeer(DialogPeer(WindowPeer(ContainerPeer(ComponentPeer)))))
Returned By: Toolkit.createFileDialog()
java.awt.peer.DialogPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_09.htm [20/12/2001 11:00:33]
java.awt.peer.FontPeer (JDK 1.1)
[Chapter 30] 30.4 java.util.Dictionary (JDK 1.0)
Chapter 30 The java.util Package
30.4 java.util.Dictionary (JDK 1.0) This abstract class is the superclass of Hashtable. Other hashtable-like data structures might also extend this class. See Hashtable for more information. public abstract class Dictionary extends Object { // Default Constructor: public Dictionary() // Public Instance Methods public abstract Enumeration elements(); public abstract Object get(Object key); public abstract boolean isEmpty(); public abstract Enumeration keys(); public abstract Object put(Object key, Object value); public abstract Object remove(Object key); public abstract int size(); }
Extended By: Hashtable
java.util.Date (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_04.htm [20/12/2001 11:00:33]
java.util.EmptyStackException (JDK 1.0)
[Chapter 16] javakey
Chapter 16 JDK Tools
javakey Name javakey---Key Management and Digital Signatures
Availability JDK 1.1 and later.
Synopsis javakey options
Description javakey provides a command-line interface to a number of complex key and certificate generation and management tasks, including the generation of digital signatures. There are quite a few options that perform a number of distinct operations. javakey manages a system database of entities. Each entity may have public and private keys and/or certificates associated with it, and in addition, each entity may be declared to be trusted or not. Any entity in the database may be an "identity" or a "signer." Identities have only a public key associated with them, while signers have both a public and private key, and thus may sign files. The different javakey operations are specified with the various options described below.
http://localhost/java/javaref/javanut/ch16_07.htm (1 of 4) [20/12/2001 11:00:34]
[Chapter 16] javakey
Options -c identity-name [true|false] Create. Create and add a new identity to the database, using the specified name. If the identity name is followed by true, declare the identity to be trusted. Otherwise make it untrusted. -cs signer-name [true|false] Create signer. Create and add a new signer entity to the database, using the specified name. If the name is followed by true, declare the signer to be trusted. Otherwise make it untrusted. -t entity-name true|false Assign trust. Specify whether the named entity is trusted (true) or not (false). -l List. List the names of all entities in the security database. -ld List details. List the names and other details about all entities in the security database. -li entity-name List information. List detailed information about the named entity from the security database. -r entity-name Remove. Remove the named entity from the security database. -ik identity-name keyfile Import key. Read a public key from the specified file and associate it with the named identity. The key must be in X.509 format. -ikp signer-name pubkeyfile privkeyfile Import key pair. Read the specified public key and private key files and associate them with the named signer entity. The keys must be in X.509 format. -ic entity-name certificate-file Import certificate. Read a certificate from the named certificate file and associate it with the named entity. If the entity already has a public key, compare it to the key in the certificate and issue a warning if they do not match. If the entity has not had a public key assigned, use the public key from the certificate. -ii entity-name Import information. This command allows you to enter arbitrary textual information about an entity into the database. -gk signer algorithm size [pubfile [privfile]] Generate key. Generate a public and private key and associate them with the named signer. Use the specified algorithm. Currently, the only supported algorithm is "DSA." Generates keys of the http://localhost/java/javaref/javanut/ch16_07.htm (2 of 4) [20/12/2001 11:00:34]
[Chapter 16] javakey
specified number of bits, which must be between 512 and 1024. If pubfile is specified, write the public key to the specified file. If privfile is specified, write the private key to the specified file. -g signer algorithm size [pubfile [privfile]] A synonym for the -gk command. -gc directivefile Generate certificate. Generate a certificate according to the parameters specified in the directive file. The directive file is a Properties file that must provide values for the following named properties: ❍ issuer.name. The name of the entity issuing the certificate. ❍ issuer.cert. The issuer's certificate number to be used to sign the generated certificate (unless the certificate will be self-signed.) ❍ subject.name. The database name of the entity that the certificate is being issued to. ❍ subject.real.name. The real name of the entity that the certificate is being issued to. ❍ subject.country. The country that the subject entity is in. ❍ subject.org. The organization that the subject entity is affiliated with. ❍ subject.org.unit. A division within the subject's organization. ❍ start.date. The starting date (and time) of the certificate. ❍ end.date. The ending date (and time) of the certificate. ❍ serial.number. A serial number for the certificate. This number must be unique among all certificates generated by the issuer. ❍ out.file. An optional filename that specifies what file the certificate should be written to. -dc certfile Display certificate. Display the contents of the certificate stored in certfile. -ec entity certificate-number file Export certificate. Output the numbered certificate of the specified entity into the specified file. Use the -li command to inspect the certificate numbers for a given entity. -ek entity pubfile [privfile] Export key. Output the public key of the specified entity into the specified file. If the entity is a signer, and the privfile is specified, additionally export the private key of the entity to that file. -gs directivefile jarfile Generate signature. Apply a digital signature to the specified JAR file using the directives in the specified directive file. The directive file is a Properties file that must provide values for the following named properties: ❍ signer. The entity name of the signer. ❍ cert. The certificate number to use for the signature. http://localhost/java/javaref/javanut/ch16_07.htm (3 of 4) [20/12/2001 11:00:34]
[Chapter 16] javakey
❍
❍
❍
chain. The length of a chain of certificates to include. This is not currently supported; specify 0. signature.file. The basename of the signature file and signature block to be inserted into the JAR file. It must be 8 characters or less. This name should not conflict with any other digital signatures that may be inserted into the JAR file. out.file. This optional property specifies the name that should be used for the signed JAR file that is generated.
See Also jar
javah
http://localhost/java/javaref/javanut/ch16_07.htm (4 of 4) [20/12/2001 11:00:34]
javap
[Chapter 18] 18.19 java.awt.Dimension (JDK 1.0)
Chapter 18 The java.awt Package
18.19 java.awt.Dimension (JDK 1.0) This class has two public instance variables that describe the width and height of something. The width and height fields are public and may be manipulated directly. public class Dimension extends Object implements Serializable { // Public Constructors public Dimension(); public Dimension(Dimension d); public Dimension(int width, int height); // Public Instance Variables public int height; public int width; // Public Instance Methods 1.1 public boolean equals(Object obj); // Overrides Object 1.1 public Dimension getSize(); 1.1 public void setSize(Dimension d); 1.1 public void setSize(int width, int height); public String toString(); // Overrides Object }
Passed To: Applet.resize(), Component.resize(), Component.setSize(), Dimension(), Dimension.setSize(), Rectangle(), Rectangle.setSize()
Returned By: Many methods
java.awt.Dialog (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_19.htm [20/12/2001 11:00:34]
java.awt.Event (JDK 1.0)
[Chapter 18] 18.44 java.awt.MenuItem (JDK 1.0)
Chapter 18 The java.awt Package
18.44 java.awt.MenuItem (JDK 1.0) This class encapsulates a menu item with a specified textual label. A MenuItem can be added to a menu pane with the Menu.add() method. The disable() method makes an item non-selectable; you might use it to "gray-out" a menu item when the command it represents is not valid in the current context. The enable() method makes an item selectable again. In Java 1.1, use setActionCommand() to specify an identifying string that is included in ActionEvent events generated by the menu item. public class MenuItem extends MenuComponent { // Public Constructors 1.1 public MenuItem(); public MenuItem(String label); 1.1 public MenuItem(String label, MenuShortcut s); // Public Instance Methods 1.1 public synchronized void addActionListener(ActionListener l); public void addNotify(); 1.1 public void deleteShortcut(); # public synchronized void disable(); # public synchronized void enable(); # public void enable(boolean b); 1.1 public String getActionCommand(); public String getLabel(); 1.1 public MenuShortcut getShortcut(); public boolean isEnabled(); public String paramString(); // Overrides MenuComponent 1.1 public synchronized void removeActionListener(ActionListener l); 1.1 public void setActionCommand(String command); 1.1 public synchronized void setEnabled(boolean b); public synchronized void setLabel(String label); 1.1 public void setShortcut(MenuShortcut s); // Protected Instance Methods 1.1 protected final void disableEvents(long eventsToDisable); 1.1 protected final void enableEvents(long eventsToEnable); 1.1 protected void processActionEvent(ActionEvent e); 1.1 protected void processEvent(AWTEvent e); // Overrides MenuComponent }
http://localhost/java/javaref/javanut/ch18_44.htm (1 of 2) [20/12/2001 11:00:34]
[Chapter 18] 18.44 java.awt.MenuItem (JDK 1.0)
Hierarchy: Object->MenuComponent(Serializable)->MenuItem
Extended By: CheckboxMenuItem, Menu
Passed To: Menu.add(), Menu.insert(), MenuPeer.addItem(), Toolkit.createMenuItem()
Returned By: Menu.add(), Menu.getItem(), MenuBar.getShortcutMenuItem()
java.awt.MenuContainer (JDK 1.0)
java.awt.MenuShortcut (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_44.htm (2 of 2) [20/12/2001 11:00:34]
[Chapter 28] 28.9 java.net.HttpURLConnection (JDK 1.1)
Chapter 28 The java.net Package
28.9 java.net.HttpURLConnection (JDK 1.1) This class is a specialization of URLConnection. An instance of this class is returned when the openConnection() method is called for a URL object that uses the HTTP protocol. The many constants defined by this class are the status codes returned by HTTP servers. setRequestMethod() specifies what kind of HTTP request is made. The contents of this request must be sent through the OutputStream returned by the getOutputStream() method of the superclass. Once an HTTP request has been sent, getResponseCode() returns the HTTP server's response code as an integer, and getResponseMessage() returns the server's response message. The disconnect() method closes the connection, and the static setFollowRedirects() specifies whether URL connections that use the HTTP protocol should automatically follow redirect responses sent by HTTP servers. In order to successfully use this class, you need to understand the details of the HTTP protocol. public abstract class HttpURLConnection extends URLConnection { // Protected Constructor protected HttpURLConnection(URL u); // Response Code Constants public static final int HTTP_ACCEPTED, HTTP_BAD_GATEWAY, HTTP_BAD_METHOD; public static final int HTTP_BAD_REQUEST, HTTP_CLIENT_TIMEOUT, HTTP_CONFLICT; public static final int HTTP_CREATED, HTTP_ENTITY_TOO_LARGE, HTTP_FORBIDDEN; public static final int HTTP_GATEWAY_TIMEOUT, HTTP_GONE, HTTP_INTERNAL_ERROR; public static final int HTTP_LENGTH_REQUIRED, HTTP_MOVED_PERM, HTTP_MOVED_TEMP; public static final int HTTP_MULT_CHOICE, HTTP_NOT_ACCEPTABLE, HTTP_NOT_AUTHORITATIVE; public static final int HTTP_NOT_FOUND, HTTP_NOT_MODIFIED, HTTP_NO_CONTENT; public static final int HTTP_OK, HTTP_PARTIAL, HTTP_PAYMENT_REQUIRED; public static final int HTTP_PRECON_FAILED, HTTP_PROXY_AUTH, HTTP_REQ_TOO_LONG; public static final int HTTP_RESET, HTTP_SEE_OTHER, HTTP_SERVER_ERROR; public static final int HTTP_UNAUTHORIZED, HTTP_UNAVAILABLE, HTTP_UNSUPPORTED_TYPE; public static final int HTTP_USE_PROXY, HTTP_VERSION; // Protected Instance Variables protected String method; protected int responseCode; protected String responseMessage; // Class Methods public static boolean getFollowRedirects();
http://localhost/java/javaref/javanut/ch28_09.htm (1 of 2) [20/12/2001 11:00:34]
[Chapter 28] 28.9 java.net.HttpURLConnection (JDK 1.1)
public static void setFollowRedirects(boolean set); // Public Instance Methods public abstract void disconnect(); public String getRequestMethod(); public int getResponseCode() throws IOException; public String getResponseMessage() throws IOException; public void setRequestMethod(String method) throws ProtocolException; public abstract boolean usingProxy(); }
Hierarchy: Object->URLConnection->HttpURLConnection
java.net.FileNameMap (JDK 1.1)
java.net.InetAddress (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_09.htm (2 of 2) [20/12/2001 11:00:34]
[Chapter 8] 8.3 Printing
Chapter 8 New AWT Features
8.3 Printing The popup menu visible in Example 8.1 shows that that example application supports a Print command. One of the most exciting new features of Java 1.1 is the ability of programs to generate hardcopy. You draw on a page in Java just as you draw on the screen: by invoking methods of a Graphics object. The difference, of course, is in the Graphics object. When drawing to the screen, you are given an instance of one subclass of Graphics, and when printing, you are given an instance of some other subclass. The two subclasses implement the necessary functionality for on-screen drawing and printing, respectively. To print in Java 1.1, follow these steps: ● First, you must begin the "print job." You do this by calling the getPrintJob() method of the Toolkit object. This method displays a dialog box to the user to request information about the print job, such as the name of the printer it should be sent to. getPrintJob() returns a PrintJob object. You can pass a Properties object to getPrintJob() and the user's printing preferences are stored in it. If the Properties object is used in a subsequent call to getPrintJob(), those preferences are reused in the dialog box. ● To begin printing a page, you call the getGraphics() method of the PrintJob object. This returns a Graphics object that implements the PrintGraphics interface to distinguish it from an on-screen Graphics object. ● Now you can use the various methods of the Graphics object to draw your desired output on the page. ● When you are done drawing the page, you call the dispose() method of the Graphics object to send that page description to the printer. If you need to print another page, you can call the getGraphics() method of the PrintJob again to obtain a new Graphics object for the next page, and repeat the process of drawing and calling dispose(). ● When you have printed all of your pages, you end the print job itself by calling the end() method of the PrintJob object. Printing AWT components and hierarchies of components is particularly easy. You simply pass a print Graphics object to the print() method of the component you want to print. By default, print() simply passes this Graphics object to the paint() method. If a component wants to display itself differently on paper than it does on screen, however, it might implement a custom print() method. To print a complete hierarchy of components, you simply call the printAll() method of the root component of the hierarchy. http://localhost/java/javaref/javanut/ch08_03.htm (1 of 2) [20/12/2001 11:00:35]
[Chapter 8] 8.3 Printing
An important restriction on printing is that applets cannot initiate print jobs. This does not mean that they cannot define custom print() methods to allow themselves to be printed; merely that the Web browser or applet viewer must initiate the print job, and invoke the printAll() method of the applet. The print() method of Example 8.1 shows how to generate hardcopy. Note that this Scribble.print() method happens to have the same name as the Component.print() method discussed above. The two methods have different arguments, however, so Scribble.print() does not override Component.print().
Popup Menus and Menu Shortcuts
http://localhost/java/javaref/javanut/ch08_03.htm (2 of 2) [20/12/2001 11:00:35]
Data Transfer with Cut-and-Paste
[Chapter 18] 18.26 java.awt.Frame (JDK 1.0)
Chapter 18 The java.awt Package
18.26 java.awt.Frame (JDK 1.0) This class represents an optionally resizable top-level application window with a titlebar and other platform-dependent window decorations. setTitle() specifies a title, setMenuBar() specifies a menu bar, setCursor() specifies a cursor, and setIconImage() specifies an icon for the window. Call the pack() method of Window to initiate layout management of the window and set its initial size appropriately. Call the show() method of Window to make a frame appear on the screen or to bring it to the front of the window stack. Call hide() to remove a frame from the screen. Call the dispose() method when the Frame is no longer needed so that it can release its window system resources for reuse. The constants defined by this class specify various cursor types. In Java 1.1, these constants and the cursor methods of Frame are deprecated in favor of the Cursor class and cursor methods of Component. public class Frame extends Window implements MenuContainer { // Public Constructors public Frame(); public Frame(String title); // Constants public static final int CROSSHAIR_CURSOR; public static final int DEFAULT_CURSOR; public static final int E_RESIZE_CURSOR; public static final int HAND_CURSOR; public static final int MOVE_CURSOR; public static final int NE_RESIZE_CURSOR; public static final int NW_RESIZE_CURSOR; public static final int N_RESIZE_CURSOR; public static final int SE_RESIZE_CURSOR; public static final int SW_RESIZE_CURSOR; public static final int S_RESIZE_CURSOR; public static final int TEXT_CURSOR; public static final int WAIT_CURSOR; public static final int W_RESIZE_CURSOR; // Public Instance Methods public void addNotify(); // Overrides Window public synchronized void dispose(); // Overrides Window # public int getCursorType(); public Image getIconImage(); public MenuBar getMenuBar(); public String getTitle(); public boolean isResizable(); public synchronized void remove(MenuComponent m); // Overrides Component # public synchronized void setCursor(int cursorType); public synchronized void setIconImage(Image image); public synchronized void setMenuBar(MenuBar mb); public synchronized void setResizable(boolean resizable);
http://localhost/java/javaref/javanut/ch18_26.htm (1 of 2) [20/12/2001 11:00:35]
[Chapter 18] 18.26 java.awt.Frame (JDK 1.0)
public synchronized void setTitle(String title); // Protected Instance Methods protected String paramString(); // Overrides Container }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Container->Window->Frame(MenuContainer)
Passed To: Dialog(), FileDialog(), Toolkit.createFrame(), Toolkit.getPrintJob(), Window()
java.awt.FontMetrics (JDK 1.0)
java.awt.Graphics (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_26.htm (2 of 2) [20/12/2001 11:00:35]
[Chapter 18] 18.51 java.awt.PrintJob (JDK 1.1)
Chapter 18 The java.awt Package
18.51 java.awt.PrintJob (JDK 1.1) A PrintJob object represents a single printing session or "job." The job may consist of one or more individual pages. PrintJob is abstract so it cannot be instantiated directly. Instead, you must call the getPrintJob() method of the Toolkit object. Calling this method posts an appropriate print dialog box to request information from the user, such as which printer should be used. An application has no control over this process, but may pass a Properties object in which the dialog stores the user's printing preferences. This Properties object can then be reused when initiating subsequent print jobs. Once a PrintJob object has been obtained from the Toolkit object, you call the getGraphics() method of PrintJob to obtain a Graphics object. Any drawing done with this Graphics object is printed rather than being displayed on-screen. The object returned by getGraphics() implements the PrintGraphics interface. Do not make any assumptions about the initial state of the Graphics object; in particular note that you must specify a font before you can draw any text. When you are done drawing all the desired output on a page, call the dispose() method of the Graphics object to force the current page to be printed. You can call PrintJob.getGraphics() and Graphics.dispose() repeatedly to print any number of pages required by your application. Note, however, that if the lastPageFirst() method returns true, the user has requested that pages be printed in reverse order. It is up to your application to implement this feature. The getPageDimension() method returns the size of the page in pixels. getPageResolution() returns the resolution of the page in pixels per inch. This resolution is closer to a screen resolution (70 to 100 pixels per inch) rather than a typical printer resolution (300 to 600 pixels per inch). This means that on-screen drawings can be drawn directly to the printer without scaling. It also means, however, that you cannot take full advantage of the extra resolution provided by printers. When you are done with a PrintJob, and you have called dispose() on the Graphics object returned by getGraphics(), you should call end() to terminate the job. public abstract class PrintJob extends Object { // Default Constructor: public PrintJob() // Public Instance Methods public abstract void end();
http://localhost/java/javaref/javanut/ch18_51.htm (1 of 2) [20/12/2001 11:00:35]
[Chapter 18] 18.51 java.awt.PrintJob (JDK 1.1)
public public public public public
void finalize(); // Overrides Object abstract Graphics getGraphics(); abstract Dimension getPageDimension(); abstract int getPageResolution(); abstract boolean lastPageFirst();
}
Returned By: PrintGraphics.getPrintJob(), Toolkit.getPrintJob()
java.awt.PrintGraphics (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_51.htm (2 of 2) [20/12/2001 11:00:35]
java.awt.Rectangle (JDK 1.0)
[Chapter 18] 18.48 java.awt.Polygon (JDK 1.0)
Chapter 18 The java.awt Package
18.48 java.awt.Polygon (JDK 1.0) This class defines a polygon as an array of points. The points of the polygon may be specified by the constructor, or with the addPoint() method. getBoundingBox() returns the smallest Rectangle that contains the polygon, and inside() tests whether a specified point is within the Polygon. Note that the arrays of X and Y points and the number of points in the polygon (not necessarily the same as the array size) are defined as public variables. Polygon objects are used when drawing polygons with the Graphics.drawPolygon() and Graphics.fillPolygon() methods. public class Polygon extends Object implements Shape, Serializable { // Public Constructors public Polygon(); public Polygon(int[] xpoints, int[] ypoints, int npoints); // Public Instance Variables public int npoints; public int[] xpoints; public int[] ypoints; // Protected Instance Variables 1.1 protected Rectangle bounds; // Public Instance Methods public void addPoint(int x, int y); 1.1 public boolean contains(Point p); 1.1 public boolean contains(int x, int y); # public Rectangle getBoundingBox(); 1.1 public Rectangle getBounds(); // From Shape # public boolean inside(int x, int y); 1.1 public void translate(int deltaX, int deltaY); }
http://localhost/java/javaref/javanut/ch18_48.htm (1 of 2) [20/12/2001 11:00:35]
[Chapter 18] 18.48 java.awt.Polygon (JDK 1.0)
Passed To: Graphics.drawPolygon(), Graphics.fillPolygon()
java.awt.Point (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_48.htm (2 of 2) [20/12/2001 11:00:35]
java.awt.PopupMenu (JDK 1.1)
[Chapter 18] 18.59 java.awt.TextField (JDK 1.0)
Chapter 18 The java.awt Package
18.59 java.awt.TextField (JDK 1.0) This Component displays a line of optionally editable text. Most of its interesting methods are defined by the TextComponent superclass. Use setEchoCharacter() to specify a character to be echoed when requesting sensitive input such as a password. See also TextComponent and TextArea. public class TextField extends TextComponent { // Public Constructors public TextField(); public TextField(String text); public TextField(int columns); public TextField(String text, int columns); // Public Instance Methods 1.1 public synchronized void addActionListener(ActionListener l); public void addNotify(); // Overrides Component public boolean echoCharIsSet(); public int getColumns(); public char getEchoChar(); 1.1 public Dimension getMinimumSize(int columns); 1.1 public Dimension getMinimumSize(); // Overrides Component 1.1 public Dimension getPreferredSize(int columns); 1.1 public Dimension getPreferredSize(); // Overrides Component # public Dimension minimumSize(int columns); # public Dimension minimumSize(); // Overrides Component # public Dimension preferredSize(int columns); # public Dimension preferredSize(); // Overrides Component 1.1 public synchronized void removeActionListener(ActionListener l); 1.1 public void setColumns(int columns); 1.1 public void setEchoChar(char c); # public void setEchoCharacter(char c); // Protected Instance Methods protected String paramString(); // Overrides TextComponent 1.1 protected void processActionEvent(ActionEvent e); 1.1 protected void processEvent(AWTEvent e); // Overrides TextComponent }
http://localhost/java/javaref/javanut/ch18_59.htm (1 of 2) [20/12/2001 11:00:35]
[Chapter 18] 18.59 java.awt.TextField (JDK 1.0)
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->TextComponent->TextField
Passed To: Toolkit.createTextField()
java.awt.TextComponent (JDK 1.0)
java.awt.Toolkit (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_59.htm (2 of 2) [20/12/2001 11:00:35]
[Chapter 30] 30.10 java.util.Hashtable (JDK 1.0)
Chapter 30 The java.util Package
30.10 java.util.Hashtable (JDK 1.0) This class implements a hashtable data structure, which allows you to associate values with a key and to efficiently look up the value associated with a given key. A hashtable is essentially an associative array, which stores objects with non-numeric array indices. put() associates a value with a key in a Hashtable. get() retrieves a value for a specified key. remove() deletes a key/value association. keys() and elements() return Enumeration objects that allow you to iterate through the complete set of keys and values stored in the table. public class Hashtable extends Dictionary implements Cloneable, Serializable { // Public Constructors public Hashtable(int initialCapacity, float loadFactor); public Hashtable(int initialCapacity); public Hashtable(); // Public Instance Methods public synchronized void clear(); public synchronized Object clone(); // Overrides Object public synchronized boolean contains(Object value); public synchronized boolean containsKey(Object key); public synchronized Enumeration elements(); // Defines Dictionary public synchronized Object get(Object key); // Defines Dictionary public boolean isEmpty(); // Defines Dictionary public synchronized Enumeration keys(); // Defines Dictionary public synchronized Object put(Object key, Object value); // Defines Dictionary public synchronized Object remove(Object key); // Defines Dictionary public int size(); // Defines Dictionary public synchronized String toString(); // Overrides Object // Protected Instance Methods protected void rehash(); }
Hierarchy: Object->Dictionary->Hashtable(Cloneable, Serializable)
Extended By: Properties
http://localhost/java/javaref/javanut/ch30_10.htm (1 of 2) [20/12/2001 11:00:36]
[Chapter 30] 30.10 java.util.Hashtable (JDK 1.0)
Passed To: CropImageFilter.setProperties(), ImageConsumer.setProperties(), ImageFilter.setProperties(), MemoryImageSource(), PixelGrabber.setProperties(), ReplicateScaleFilter.setProperties()
Type Of: GridBagLayout.comptable
java.util.GregorianCalendar (JDK 1.1)
java.util.ListResourceBundle (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_10.htm (2 of 2) [20/12/2001 11:00:36]
[Chapter 30] 30.5 java.util.EmptyStackException (JDK 1.0)
Chapter 30 The java.util Package
30.5 java.util.EmptyStackException (JDK 1.0) Signals that a Stack object is empty. public class EmptyStackException extends RuntimeException { // Public Constructor public EmptyStackException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->EmptyStackException
java.util.Dictionary (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_05.htm [20/12/2001 11:00:36]
java.util.Enumeration (JDK 1.0)
[Chapter 31] 31.15 java.util.zip.ZipFile (JDK 1.1)
Chapter 31 The java.util.zip Package
31.15 java.util.zip.ZipFile (JDK 1.1) This class reads the contents of ZIP files. It uses a random access file internally so that the entries of the ZIP file do not have to be read sequentially as they do with the ZipInputStream class. A ZipFile object can be created by specifying the ZIP file to be read either as a String filename or as a File object. Once created, the getEntry() method returns a ZipEntry object for a named entry, and the entries() method returns an Enumeration object that allows you to loop through all the ZipEntry objects for the file. To read the contents of a specific ZipEntry within the ZIP file, pass the ZipEntry to getInputStream()--this returns an InputStream object from which you can read the entry's contents. public class ZipFile extends Object { // Public Constructors public ZipFile(String name) throws IOException; public ZipFile(File file) throws ZipException, IOException; // Public Instance Methods public void close() throws IOException; public Enumeration entries(); public ZipEntry getEntry(String name); public InputStream getInputStream(ZipEntry ze) throws IOException; public String getName(); }
java.util.zip.ZipException (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_15.htm [20/12/2001 11:00:36]
java.util.zip.ZipInputStream (JDK 1.1)
[Chapter 30] 30.6 java.util.Enumeration (JDK 1.0)
Chapter 30 The java.util Package
30.6 java.util.Enumeration (JDK 1.0) This interface defines the methods necessary to enumerate, or iterate through, a set of values, such as the set of values contained in a hashtable or binary tree. It is particularly useful for data structures, like hashtables, for which elements cannot simply be looked up by index, as they can in arrays. An Enumeration is usually not instantiated directly, but instead is created by the object that is to have its values enumerated. A number of classes, such as Vector and Hashtable, have methods that return Enumeration objects. To use an Enumeration object, you use its two methods in a loop: hasMoreElements() returns true if there are more values to be enumerated, and can be used to determine whether a loop should continue. Within a loop, a call to nextElement() returns a value from the enumeration. An Enumeration makes no guarantees about the order in which the values are returned. The values in an Enumeration may be iterated through only once--there is no way to reset it to the beginning. public abstract interface Enumeration { // Public Instance Methods public abstract boolean hasMoreElements(); public abstract Object nextElement(); }
Implemented By: StringTokenizer
Passed To: SequenceInputStream()
Returned By: AppletContext.getApplets(), Dictionary.elements(), Dictionary.keys(), FeatureDescriptor.attributeNames(), Hashtable.elements(), Hashtable.keys(), ListResourceBundle.getKeys(), MenuBar.shortcuts(), Properties.propertyNames(), PropertyResourceBundle.getKeys(), ResourceBundle.getKeys(), Vector.elements(), ZipFile.entries() http://localhost/java/javaref/javanut/ch30_06.htm (1 of 2) [20/12/2001 11:00:36]
[Chapter 30] 30.6 java.util.Enumeration (JDK 1.0)
java.util.EmptyStackException (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_06.htm (2 of 2) [20/12/2001 11:00:36]
java.util.EventListener (JDK 1.1)
[Chapter 24] 24.14 java.io.EOFException (JDK 1.0)
Chapter 24 The java.io Package
24.14 java.io.EOFException (JDK 1.0) An IOException that signals the end-of-file. public class EOFException extends IOException { // Public Constructors public EOFException(); public EOFException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->EOFException
java.io.DataOutputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_14.htm [20/12/2001 11:00:37]
java.io.Externalizable (JDK 1.1)
[Chapter 25] 25.18 java.lang.Error (JDK 1.0)
Chapter 25 The java.lang Package
25.18 java.lang.Error (JDK 1.0) This class forms the root of the error hierarchy in Java. Subclasses of Error, unlike subclasses of Exception, should generally not be caught, and generally cause termination of the program. Subclasses of Error need not be declared in the throws clause of a method definition. getMessage() returns a message associated with the error. See Throwable for other methods. public class Error extends Throwable { // Public Constructors public Error(); public Error(String s); }
Hierarchy: Object->Throwable(Serializable)->Error
Extended By: AWTError, LinkageError, ThreadDeath, VirtualMachineError
java.lang.Double (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_18.htm [20/12/2001 11:00:37]
java.lang.Exception (JDK 1.0)
[Chapter 11] 11.5 Localizing User-Visible Messages
Chapter 11 Internationalization
11.5 Localizing User-Visible Messages The third task of internationalization involves ensuring that there are no user-visible strings that are hard-coded in an application, instead of being looked up based on the locale. In Example 11.3, for example, the strings "Portfolio value", "Symbol", "Shares", and others are hard-coded in the application and appear in English, even when the program is run in the French locale. The only way to prevent this is to fetch all user-visible messages at runtime, and to translate every message into each of the languages that your application must support. Java 1.1 helps you handle this task with the ResourceBundle class of the java.util package. This class represents a "bundle" of resources that can be looked up by name. You define a localized resource bundle for each locale you want to support, and Java takes care of loading the correct bundle for the default (or specified) locale. With the correct bundle loaded, you can look up the resources (typically strings) that your program needs at runtime.
Working with Resource Bundles To define a bundle of localized resources, you create a subclass of ResourceBundle and provide definitions for the handleGetObject() and getKeys() methods. handleGetObject() is passed the name of a resource; it should return an appropriate localized version of that resource. getKeys() should return an Enumeration object that gives the user a list of all resource names defined in the ResourceBundle. Instead of subclassing ResourceBundle directly, however, it is often easier to subclass ListResourceBundle. You can also simply provide a property file (see the java.util.Properties class) that ResourceBundle.getBundle() uses to create an instance of PropertyResourceBundle. To use localized resources from a ResourceBundle in a program, you should first call the static getBundle() method, which dynamically loads and instantiates a ResourceBundle, as described below. The returned ResourceBundle has the name you specify and is appropriate for the specified locale (or for the default locale, if no locale is explicitly specified). Once you have obtained a ResourceBundle object with getBundle(), you use the getObject() method to look up resources by name. Note that there is a convenience method, getString(), that simply casts the value returned by getObject() to be a String object. When you call getBundle(), you specify the base name of the desired ResourceBundle and a desired locale (if you don't want to rely on the default locale). Recall that a Locale is specified with a two-letter language code, an optional two-letter country code, and an optional variant string. getBundle() looks for an appropriate ResourceBundle class for the locale by appending this locale information to the base name for the bundle. The method looks for an appropriate class with the following algorithm: 1. Search for a class with the following name: basename_language_country_variant If no such class is found, or no variant string is specified for the locale, it goes to the next step. 2. Search for a class with the following name: http://localhost/java/javaref/javanut/ch11_05.htm (1 of 5) [20/12/2001 11:00:37]
[Chapter 11] 11.5 Localizing User-Visible Messages
basename_language_country If no such class is found, or no country code is specified for the locale, it goes to the next step. 3. Search for a class with the following name: basename_language If no such class is found, it goes to the final step. 4. Search for a class which has the same name as the basename, or in other words, seach for a class with the following name: basename This represents a default resource bundle used by any locale that is not explicitly supported. At each step in the above process, getBundle() checks first for a class file with the given name. If no class file is found, it uses the getResourceAsStream() method of ClassLoader to look for a Properties file with the same name as the class and a .properties extension. If such a properties file is found, its contents are used to create a Properties object and getBundle() instantiates and returns a PropertyResourceBundle that exports the properties in the Properties file through the ResourceBundle API. If getBundle() cannot find a class or properties file for the specified locale in any of the four search steps above, it repeats the search using the default locale instead of the specified locale. If no appropriate ResourceBundle is found in this search either, getBundle() throws a MissingResourceException. Any ResourceBundle object may have a parent ResourceBundle specified for it. When you look up a named resource in a ResourceBundle, getObject() first looks in the specified bundle, but if the named resource is not defined in that bundle, it recursively looks in the parent bundle. Thus, every ResourceBundle "inherits" the resources of its parent, and may choose to "override" some, or all, of these resources. (Note that we are using the terms "inherit" and "override" in a different sense than we do when talking about classes that inherit and override methods in their superclass.) What this means is that every ResourceBundle you define does not have to define every resource required by your application. For example, you might define a ResourceBundle of messages to display to French-speaking users. Then you might define a smaller and more specialized ResourceBundle that overrides a few of these messages so that they are appropriate for French-speaking users who live in Canada. Your application is not required to find and set up the parent objects for the ResourceBundle objects it uses. The getBundle() method actually does this for you. When getBundle() finds an appropriate class or properties file as described above, it does not immediately return the ResourceBundle it has found. Instead, it continues through the remaining steps in the search process listed above, looking for less-specific class or properties files from which the ResourceBundle may "inherit" resources. If and when getBundle() finds these less-specific resource bundles, it sets them up as the appropriate ancestors of the original bundle. Only once it has checked all possibilities does it return the original ResourceBundle object that it created. To continue the example begun above, when a program runs in Québec, getBundle() might first find a small specialized ResourceBundle class that has only a few specific Québecois resources. Next, it looks for a more general ResourceBundle that contains French messages and it sets this bundle as the parent of the original Québecois bundle. Finally, getBundle() looks for (and probably finds) a class that defines a default set of resources, probably written in English (assuming that English is the native tongue of the original programmer). This default bundle is set as the parent of the French bundle (which makes it the grandparent of the Québecois bundle). When the application looks up a named resource, the Québecois bundle is searched first. If the resource is not defined there, then the French bundle is searched, and finally, any named resource not found in the French bundle is looked up in the default bundle. http://localhost/java/javaref/javanut/ch11_05.htm (2 of 5) [20/12/2001 11:00:37]
[Chapter 11] 11.5 Localizing User-Visible Messages
ResourceBundle Example Examining some code makes this discussion of resource bundles much clearer. Example 11.4 is a convenience routine for creating menu panes. Given a list of menu item names, it looks up labels and menu shortcuts for those named menu items in a resource bundle and creates a localized menu pane. The example has a simple test program attached. Figure 11.2 shows the menus it creates in the American, British, and French locales. This program could not run, of course, without localized resource bundles from which the localized menu labels are looked up. Example 11.4 shows American, British, and French resource files used to create each of the menus shown in the figure. Figure 11.2: Localized menu panes
Example 11.4: Creating Localized Menu Panes import java.awt.*; import java.awt.event.*; import java.util.Locale; import java.util.ResourceBundle; import java.util.MissingResourceException; /** A convenience class to automatically create localized menu panes. */ public class SimpleMenu { /** The convenience method that creates menu panes. */ public static Menu create(String bundlename, String menuname, String[] itemnames, ActionListener listener, boolean popup) { // Get the resource bundle used for this menu. ResourceBundle b = ResourceBundle.getBundle(bundlename); // Get the menu title from the bundle. Use name as default label. String menulabel; try { menulabel = b.getString(menuname + ".label"); } catch(MissingResourceException e) { menulabel = menuname; } // Create the menu pane.
http://localhost/java/javaref/javanut/ch11_05.htm (3 of 5) [20/12/2001 11:00:37]
[Chapter 11] 11.5 Localizing User-Visible Messages
Menu m; if (popup) m = new PopupMenu(menulabel); else m = new Menu(menulabel); // For each named item in the menu. for(int i = 0; i < itemnames.length; i++) { // Look up the label for the item, using name as default. String itemlabel; try { itemlabel=b.getString(menuname + "." + itemnames[i] + ".label"); } catch (MissingResourceException e) { itemlabel = itemnames[i]; } // Look up a shortcut for the item, and create the menu shortcut, if any. String shortcut; try{shortcut = b.getString(menuname + "." + itemnames[i]+".shortcut"); } catch (MissingResourceException e) { shortcut = null; } MenuShortcut ms = null; if (shortcut != null) ms = new MenuShortcut(shortcut.charAt(0)); // Create the menu item. MenuItem mi; if (ms != null) mi = new MenuItem(itemlabel, ms); else mi = new MenuItem(itemlabel); // Register an action listener and command for the item. if (listener != null) { mi.addActionListener(listener); mi.setActionCommand(itemnames[i]); } // Add the item to the menu. m.add(mi); } // Return the automatically created localized menu. return m; } /** A simple test program for the above code. */ public static void main(String[] args) { // Set the default locale based on the command-line args. if (args.length == 2) Locale.setDefault(new Locale(args[0], args[1])); Frame f = new Frame("SimpleMenu Test"); // Create a window. MenuBar menubar = new MenuBar(); // Create a menubar. f.setMenuBar(menubar); // Add menubar to window. // Create a menu using our convenience routine (and the default locale). Menu colors = SimpleMenu.create("Menus", "colors", new String[] { "red", "green", "blue" }, null, false); menubar.add(colors); // Add the menu to the menubar. f.setSize(300, 150); // Set the window size. f.show(); // Pop the window up. } } This example does not stand alone. It relies on resource bundles to localize the menu. Example 11.5 shows three property files that serve as resource bundles for this example. Note that this single example listing actually contains the bodies of three separate files.
http://localhost/java/javaref/javanut/ch11_05.htm (4 of 5) [20/12/2001 11:00:37]
[Chapter 11] 11.5 Localizing User-Visible Messages
Example 11.5: Property Files as Resource Bundles # The file Menus.properties is the default "Menus" resource bundle. # As an American programmer, I made my own locale the default. colors.label=Colors colors.red.label=Red colors.red.shortcut=R colors.green.label=Green colors.green.shortcut=G colors.blue.label=Blue colors.blue.shortcut=B # This is the file Menus_en_GB.properties. It is the resource bundle for # British English. Note that it overrides only a single resource definition # and simply inherits the rest from the default (American) bundle. colors.label=Colours # This is the file Menus_fr.properties. It is the resource bundle for all # French-speaking locales. It overrides most, but not all, of the resources # in the default bundle. colors.label=Couleurs colors.red.label=Rouge colors.green.label=Vert colors.green.shortcut=V colors.blue.label=Bleu
Handling Local Customs
http://localhost/java/javaref/javanut/ch11_05.htm (5 of 5) [20/12/2001 11:00:37]
Formatted Messages
[Chapter 6] 6.4 Handling Events
Chapter 6 Applets
6.4 Handling Events The previous two applets have only displayed output. If an applet is to be interactive in any way, it has to receive and respond to user input. Example 6.3 shows a simple applet that lets the user do a freehand sketch (or scribble) with the mouse. Figure 6.3 shows such a scribble. Figure 6.3: Scribbling with the scribble applet
The mouseDown() and mouseDrag() methods are called by the system when the user presses a mouse button and moves the mouse with the button down, respectively. This very simple applet draws lines directly in response to these events. It does not have a paint() method, which means that the user's scribble is lost any time that the applet is redrawn (for example, when a Web browser scrolls down a page and then scrolls back up again). http://localhost/java/javaref/javanut/ch06_04.htm (1 of 2) [20/12/2001 11:00:38]
[Chapter 6] 6.4 Handling Events
Note that both mouseDown() and mouseDrag() return true. This is to tell the system that they've handled the Event object that was passed to them, and that the event should not be processed any further. The mouseDown() and mouseDrag() methods shown here work in both Java 1.0 and Java 1.1, but they (and related methods) have been deprecated in Java 1.1 and replaced with a new, more flexible, event handling model. Event processing is often the central task of applets and of GUI-based applications, and is a big topic in its own right. Chapter 7, Events explains and demonstrates the Java 1.1 and 1.0 event processing models in more detail. Example 6.3: The Scribble Applet import java.applet.*; import java.awt.*; public class Scribble extends Applet { private int last_x = 0, last_y = 0; // Fields to store a point in. // Called when the user clicks. public boolean mouseDown(Event e, int x, int y) { last_x = x; last_y = y; // Remember the location of the click. return true; } // Called when the mouse moves with the button down. public boolean mouseDrag(Event e, int x, int y) { Graphics g = getGraphics(); // Get a Graphics to draw with. g.drawLine(last_x, last_y, x, y); // Draw a line from last point to this. last_x = x; last_y = y; // And update the saved location. return true; } }
Drawing Graphics
http://localhost/java/javaref/javanut/ch06_04.htm (2 of 2) [20/12/2001 11:00:38]
Reading Applet Parameters
[Chapter 10] 10.4 Custom Events
Chapter 10 Java Beans
10.4 Custom Events Beans can use the standard AWT event types defined in the java.awt.event package, but they do not have to. Our YesNoDialog class defines its own event type, AnswerEvent. Defining a new event class is really quite simple; AnswerEvent is shown in Example 10.3. Example 10.3: The AnswerEvent Class package oreilly.beans.yesno; public class AnswerEvent extends java.util.EventObject { protected int id; public static final int YES = 0, NO = 1, CANCEL = 2; public AnswerEvent(Object source, int id) { super(source); this.id = id; } public int getID() { return id; } } Along with the AnswerEvent class, YesNoDialog also defines a new type of event listener interface, ActionListener, that defines the methods that must be implemented by any object that wants to receive notification from a YesNoDialog. The definition of AnswerListener is shown in Example 10.4. Example 10.4: The AnswerListener Interface package oreilly.beans.yesno; public interface AnswerListener extends java.util.EventListener { public void yes(AnswerEvent e); public void no(AnswerEvent e); public void cancel(AnswerEvent e); }
http://localhost/java/javaref/javanut/ch10_04.htm (1 of 2) [20/12/2001 11:00:38]
[Chapter 10] 10.4 Custom Events
A More Complex Bean
http://localhost/java/javaref/javanut/ch10_04.htm (2 of 2) [20/12/2001 11:00:38]
Specifying Bean Information
[Chapter 18] 18.20 java.awt.Event (JDK 1.0)
Chapter 18 The java.awt Package
18.20 java.awt.Event (JDK 1.0) This class contains public instance variables that describe some kind of GUI event. In Java 1.1, this class has been superseded by AWTEvent and the java.awt.event package. The class contains a large number of constants. Some of the constants specify the event type and are values for the id variable. Other constants are values for keys, like the function keys, that do not have ASCII (or Latin-1) values, and are set on the key field. Other constants are mask values that are ORed into the modifiers field to describe the state of the modifier keys on the keyboard. The target field is very important--it is the object for which the event occurred. The when field specifies when the event occurred. The x and y fields specify the mouse coordinates at which it occurred. Finally, the arg field is a value specific to the type of the event. Not all fields have valid values for all types of events. public class Event extends Object implements Serializable { // Public Constructors public Event(Object target, long when, int id, int x, int y, int key, int modifiers, Object arg); public Event(Object target, long when, int id, int x, int y, int key, int modifiers); public Event(Object target, int id, Object arg); // Event Type Constants public static final int ACTION_EVENT; public static final int GOT_FOCUS, LOST_FOCUS; public static final int KEY_ACTION, KEY_ACTION_RELEASE; public static final int KEY_PRESS, KEY_RELEASE; public static final int LIST_SELECT, LIST_DESELECT; public static final int LOAD_FILE, SAVE_FILE; public static final int MOUSE_DOWN, MOUSE_UP; public static final int MOUSE_DRAG, MOUSE_MOVE; public static final int MOUSE_ENTER, MOUSE_EXIT; public static final int SCROLL_ABSOLUTE; 1.1 public static final int SCROLL_BEGIN, SCROLL_END; public static final int SCROLL_LINE_DOWN, SCROLL_LINE_UP; public static final int SCROLL_PAGE_DOWN, SCROLL_PAGE_UP; public static final int WINDOW_EXPOSE; public static final int WINDOW_ICONIFY, WINDOW_DEICONIFY; public static final int WINDOW_DESTROY; public static final int WINDOW_MOVED; // Keyboard Modifier Constants public static final int ALT_MASK; public static final int CTRL_MASK; public static final int META_MASK; public static final int SHIFT_MASK; // Function Key Constants public static final int F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11,
http://localhost/java/javaref/javanut/ch18_20.htm (1 of 2) [20/12/2001 11:00:38]
[Chapter 18] 18.20 java.awt.Event (JDK 1.0)
F12; public static final int LEFT, RIGHT, UP, DOWN; public static final int PGUP, PGDN; public static final int HOME, END; 1.1 public static final int INSERT, DELETE; 1.1 public static final int BACK_SPACE; 1.1 public static final int ENTER; 1.1 public static final int ESCAPE; 1.1 public static final int TAB; 1.1 public static final int CAPS_LOCK, NUM_LOCK, SCROLL_LOCK; 1.1 public static final int PAUSE, PRINT_SCREEN; // Public Instance Variables public Object arg; public int clickCount; public Event evt; public int id; public int key; public int modifiers; public Object target; public long when; public int x; public int y; // Public Instance Methods public boolean controlDown(); public boolean metaDown(); public boolean shiftDown(); public String toString(); // Overrides Object public void translate(int x, int y); // Protected Instance Methods protected String paramString(); }
Passed To: AWTEvent(), Component.action(), Component.deliverEvent(), Component.gotFocus(), Component.handleEvent(), Component.keyDown(), Component.keyUp(), Component.lostFocus(), Component.mouseDown(), Component.mouseDrag(), Component.mouseEnter(), Component.mouseExit(), Component.mouseMove(), Component.mouseUp(), Component.postEvent(), Container.deliverEvent(), MenuComponent.postEvent(), MenuContainer.postEvent(), PopupMenuPeer.show(), Window.postEvent()
Type Of: Event.evt
java.awt.Dimension (JDK 1.0)
java.awt.EventQueue (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_20.htm (2 of 2) [20/12/2001 11:00:38]
[Chapter 30] 30.7 java.util.EventListener (JDK 1.1)
Chapter 30 The java.util Package
30.7 java.util.EventListener (JDK 1.1) EventListener is a base interface for the Java 1.1 AWT event model. This interface defines no method or constants. Its purpose is to serve as a tag to identify objects that serve as event listeners. The event listener interfaces in the java.awt.event, and java.beans packages extend this interface. public interface EventListener { }
Extended By: ActionListener, AdjustmentListener, ComponentListener, ContainerListener, FocusListener, ItemListener, KeyListener, MouseListener, MouseMotionListener, PropertyChangeListener, TextListener, VetoableChangeListener, WindowListener
Passed To: AWTEventMulticaster(), AWTEventMulticaster.addInternal(), AWTEventMulticaster.remove(), AWTEventMulticaster.removeInternal(), AWTEventMulticaster.save()
Returned By: AWTEventMulticaster.addInternal(), AWTEventMulticaster.remove(), AWTEventMulticaster.removeInternal()
Type Of: AWTEventMulticaster.a, AWTEventMulticaster.b
java.util.Enumeration (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_07.htm [20/12/2001 11:00:38]
java.util.EventObject (JDK 1.1)
[Chapter 30] 30.8 java.util.EventObject (JDK 1.1)
Chapter 30 The java.util Package
30.8 java.util.EventObject (JDK 1.1) EventObject serves as a superclass for all events objects used by the Java 1.1 AWT event model and the JavaBeans event model. This class defines a very generic type of event; it is extended by the more specific event classes in the java.awt, java.awt.event, and java.beans packages. The only common feature shared by all events is a source object, which is the object that in some way "generated" the event. The source object is passed to the EventObject() constructor, and is returned by the getSource() method. public class EventObject extends Object implements Serializable { // Public Constructor public EventObject(Object source); // Protected Instance Variables protected transient Object source; // Public Instance Methods public Object getSource(); public String toString(); // Overrides Object }
Extended By: AWTEvent, PropertyChangeEvent
java.util.EventListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_08.htm [20/12/2001 11:00:39]
java.util.GregorianCalendar (JDK 1.1)
[Chapter 18] 18.21 java.awt.EventQueue (JDK 1.1)
Chapter 18 The java.awt Package
18.21 java.awt.EventQueue (JDK 1.1) This class implements an event queue for AWT events in Java 1.1. When an EventQueue is created, a new thread is automatically created and started to remove events from the front of the queue and dispatch them to the appropriate component. It is this thread, created by the EventQueue, that notifies event listeners and executes most of the code in a typical GUI-driven application. An application can create and use its own private EventQueue, but all AWT events are placed on and dispatched from a single system EventQueue. Use the getSystemEventQueue() method of the Toolkit class to get the system EventQueue object. getNextEvent() removes and returns the event at the front of the queue. It blocks if there are no events in the queue. peekEvent() returns the event at the front of the queue without removing it from the queue. Passed an optional AWTEvent id field, it returns the first event of the specified type. Finally, postEvent() places a new event on the end of the event queue. Most applications do not need to use the EventQueue class at all; they can simply rely on the system to dispatch events automatically. public class EventQueue extends Object { // Public Constructor public EventQueue(); // Public Instance Methods public synchronized AWTEvent getNextEvent() throws InterruptedException; public synchronized AWTEvent peekEvent(); public synchronized AWTEvent peekEvent(int id); public synchronized void postEvent(AWTEvent theEvent); }
Returned By: Toolkit.getSystemEventQueue(), Toolkit.getSystemEventQueueImpl()
java.awt.Event (JDK 1.0)
java.awt.FileDialog (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_21.htm [20/12/2001 11:00:39]
[Chapter 23] 23.5 java.beans.EventSetDescriptor (JDK 1.1)
Chapter 23 The java.beans Package
23.5 java.beans.EventSetDescriptor (JDK 1.1) An EventSetDescriptor object is a type of FeatureDescriptor that describes a single set of events supported by a Java bean. A "set" of events corresponds to the one or more methods supported by a single EventListener interface. The BeanInfo class for a Java bean optionally creates EventSetDescriptor objects to describe the event sets the bean supports. Typically, only application builders and similar tools use the get and is methods of EventSetDescriptor objects to obtain the event-set description information. To create an EventSetDescriptor object, you must specify the class of the bean that supports the event set, the base name of the event set, the class of the EventListener interface that corresponds to the event set, and the methods within this interface that are invoked when particular events within the set occur. Optionally, you may also specify the methods of the bean class that are used to add and remove EventListener objects. The various constructors allow you to specify methods by name, as java.lang.reflect.Method objects, or as MethodDescriptor objects. Once you have created an EventSetDescriptor, you can use setUnicast() to specify whether it represents a unicast event and setInDefaultEventSet() to specify whether the event set should be treated as the default event set by builder applications. The methods of the FeatureDescriptor superclass allow additional information about the property to be specified. public class EventSetDescriptor extends FeatureDescriptor { // Public Constructors public EventSetDescriptor(Class sourceClass, String eventSetName, Class listenerType, public EventSetDescriptor'u'String listenerMethodName) throws IntrospectionException; public EventSetDescriptor(Class sourceClass, String eventSetName, Class listenerType, public EventSetDescriptor'u'String[] listenerMethodNames, String addListenerMethodName public EventSetDescriptor'u'String removeListenerMethodName) throws IntrospectionException; public EventSetDescriptor(String eventSetName, Class listenerType, Method[] listenerMethods, public EventSetDescriptor'u'Method addListenerMethod, Method removeListenerMethod) public EventSetDescriptor'u'throws IntrospectionException; public EventSetDescriptor(String eventSetName, Class listenerType, public EventSetDescriptor'u'MethodDescriptor[] listenerMethodDescriptors, Method addListenerMethod, public EventSetDescriptor'u'Method removeListenerMethod) throws IntrospectionException; // Public Instance Methods public Method getAddListenerMethod(); public MethodDescriptor[] getListenerMethodDescriptors();
http://localhost/java/javaref/javanut/ch23_05.htm (1 of 2) [20/12/2001 11:00:39]
[Chapter 23] 23.5 java.beans.EventSetDescriptor (JDK 1.1)
public public public public public public public
Method[] getListenerMethods(); Class getListenerType(); Method getRemoveListenerMethod(); boolean isInDefaultEventSet(); boolean isUnicast(); void setInDefaultEventSet(boolean inDefaultEventSet); void setUnicast(boolean unicast);
}
Hierarchy: Object->FeatureDescriptor->EventSetDescriptor
Returned By: BeanInfo.getEventSetDescriptors(), SimpleBeanInfo.getEventSetDescriptors()
java.beans.Customizer (JDK 1.1)
java.beans.FeatureDescriptor (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_05.htm (2 of 2) [20/12/2001 11:00:39]
[Chapter 20] 20.12 java.awt.event.FocusEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.12 java.awt.event.FocusEvent (JDK 1.1) An event of this type indicates that a Component has gained or lost focus on a temporary or permanent basis. Use the inherited getComponent() method to determine which component has gained or lost focus. Use getID() to determine the type of focus event; it returns FOCUS_GAINED or FOCUS_LOST. When focus is lost, you can call isTemporary() to determine whether it is a temporary loss of focus. Temporary focus loss occurs when the window that contains the component loses focus, for example, or when focus is temporarily diverted to a popup menu or a scrollbar. Similarly, you can also use isTemporary() to determine whether focus is being granted to a component on a temporary basis. public class FocusEvent extends ComponentEvent { // Public Constructors public FocusEvent(Component source, int id, boolean temporary); public FocusEvent(Component source, int id); // Constants public static final int FOCUS_FIRST; public static final int FOCUS_GAINED; public static final int FOCUS_LAST; public static final int FOCUS_LOST; // Public Instance Methods public boolean isTemporary(); public String paramString(); // Overrides ComponentEvent }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ComponentEvent->FocusEvent
Passed To: AWTEventMulticaster.focusGained(), AWTEventMulticaster.focusLost(), Component.processFocusEvent(), FocusAdapter.focusGained(), FocusAdapter.focusLost(), FocusListener.focusGained(), FocusListener.focusLost()
http://localhost/java/javaref/javanut/ch20_12.htm (1 of 2) [20/12/2001 11:00:39]
[Chapter 20] 20.12 java.awt.event.FocusEvent (JDK 1.1)
java.awt.event.FocusAdapter (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_12.htm (2 of 2) [20/12/2001 11:00:39]
java.awt.event.FocusListener (JDK 1.1)
[Chapter 7] 7.5 Scribbling with Inner Classes
Chapter 7 Events
7.5 Scribbling with Inner Classes The Java 1.1 event model was designed to work well with another new Java 1.1 feature: inner classes. Example 7.3 shows what the applet looks like when the event listeners are implemented as anonymous inner classes. Note how succinct this representation is. This is perhaps the most common way to use the Java 1.1 event model, so you'll probably see a lot of code that looks like this. In this case, our simple applet is nothing but event-handling code, so this version of it consists almost entirely of anonymous class definitions. Note that we've added a feature to the applet. It now includes a Clear button. An ActionListener object is registered with the button; it clears the scribble when the appropriate event occurs. Example 7.3: Scribble: Using Inner Classes import java.applet.*; import java.awt.*; import java.awt.event.*; public class Scribble3 extends Applet { int last_x, last_y; public void init() { // Define, instantiate, and register a MouseListener object. this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { last_x = e.getX(); last_y = e.getY(); } }); // Define, instantiate, and register a MouseMotionListener object. this.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { Graphics g = getGraphics(); int x = e.getX(), y = e.getY(); g.setColor(Color.black); g.drawLine(last_x, last_y, x, y); last_x = x; last_y = y; } }); // Create a clear button. Button b = new Button("Clear");
http://localhost/java/javaref/javanut/ch07_05.htm (1 of 2) [20/12/2001 11:00:40]
[Chapter 7] 7.5 Scribbling with Inner Classes
// Define, instantiate, and register a listener to handle button presses. b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // clear the scribble Graphics g = getGraphics(); g.setColor(getBackground()); g.fillRect(0, 0, getSize().width, getSize().height); } }); // And add the button to the applet. this.add(b); } }
Scribbling in Java 1.1
http://localhost/java/javaref/javanut/ch07_05.htm (2 of 2) [20/12/2001 11:00:40]
Inside the Java 1.1 Event Model
[Chapter 20] 20.15 java.awt.event.ItemEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.15 java.awt.event.ItemEvent (JDK 1.1) An event of this type indicates that an item within an ItemSelectable component has had its selection state changed. getItemSelectable() is a convenient alternative to getSource() that returns the ItemSelectable object that originated the event. getItem() returns an object that represents the item that was selected or deselected. getID() returns the type of the ItemEvent. The standard AWT components always generate item events of type ITEM_STATE_CHANGED. The getStateChange() method returns the new selection state of the item: it returns one of the constants SELECTED or DESELECTED. (This value can be misleading for Checkbox components that are part of a CheckboxGroup. If the user attempts to deselect a selected component, a DESELECTED event is delivered, but the CheckboxGroup immediately re-selects the component to enforce its requirement that at least one Checkbox be selected at all times.) public class ItemEvent extends AWTEvent { // Public Constructor public ItemEvent(ItemSelectable source, int id, Object item, int stateChange); // Constants public static final int DESELECTED; public static final int ITEM_FIRST; public static final int ITEM_LAST; public static final int ITEM_STATE_CHANGED; public static final int SELECTED; // Public Instance Methods public Object getItem(); public ItemSelectable getItemSelectable(); public int getStateChange(); public String paramString(); // Overrides AWTEvent }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ItemEvent
http://localhost/java/javaref/javanut/ch20_15.htm (1 of 2) [20/12/2001 11:00:40]
[Chapter 20] 20.15 java.awt.event.ItemEvent (JDK 1.1)
Passed To: AWTEventMulticaster.itemStateChanged(), Checkbox.processItemEvent(), CheckboxMenuItem.processItemEvent(), Choice.processItemEvent(), ItemListener.itemStateChanged(), List.processItemEvent()
java.awt.event.InputEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_15.htm (2 of 2) [20/12/2001 11:00:40]
java.awt.event.ItemListener (JDK 1.1)
[Chapter 20] 20.21 java.awt.event.MouseEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.21 java.awt.event.MouseEvent (JDK 1.1) An event of this type indicates that the user has moved the mouse or pressed one of the mouse buttons. Call getID() to determine the specific type of mouse event that has occurred. This method returns one of the following seven constants, which corresponds to a method in either the MouseListener or MouseMotionListener interface. MOUSE_PRESSED The user has pressed a mouse button. MOUSE_RELEASED The user has released a mouse button. MOUSE_CLICKED The user has pressed and released a mouse button without any intervening mouse drag. MOUSE_DRAGGED The user has moved the mouse while holding a button down MOUSE_MOVED The user has moved the mouse without holding any buttons down. MOUSE_ENTERED The mouse pointer has entered the component. MOUSE_EXITED The mouse pointer has left the component Use getX() and getY() or getPoint() to obtain the coordinates of the mouse event. Use translatePoint() to modify these coordinates by a specified amount. Use getModifiers() and other methods and constants inherited from InputEvent to determine the mouse button or keyboard modifiers that were down when the event occurred. See InputEvent for details. Note that mouse button modifiers are not reported for MOUSE_RELEASED events, since, technically, the mouse button in question is no longer pressed. This can be surprising. Use getComponent(), inherited from ComponentEvent, to determine over which component the event occurred. For mouse events of type MOUSE_CLICKED, MOUSE_PRESSED, or MOUSE_RELEASED, call getClickCount() to determine how many consecutive clicks have occurred. If you are using popup menus, use isPopupTrigger() to test whether the current event represents the standard platform-dependent popup menu trigger event. public class MouseEvent extends InputEvent { // Public Constructor http://localhost/java/javaref/javanut/ch20_21.htm (1 of 2) [20/12/2001 11:00:40]
[Chapter 20] 20.21 java.awt.event.MouseEvent (JDK 1.1)
public MouseEvent(Component source, int id, long when, int modifiers, int x, int y, public MouseEvent'u'int clickCount, boolean popupTrigger); // Constants public static final int MOUSE_CLICKED; public static final int MOUSE_DRAGGED; public static final int MOUSE_ENTERED; public static final int MOUSE_EXITED; public static final int MOUSE_FIRST; public static final int MOUSE_LAST; public static final int MOUSE_MOVED; public static final int MOUSE_PRESSED; public static final int MOUSE_RELEASED; // Public Instance Methods public int getClickCount(); public Point getPoint(); public int getX(); public int getY(); public boolean isPopupTrigger(); public String paramString(); // Overrides ComponentEvent public synchronized void translatePoint(int x, int y); }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ComponentEvent->InputEvent->MouseEvent
Passed To: AWTEventMulticaster.mouseClicked(), AWTEventMulticaster.mouseDragged(), AWTEventMulticaster.mouseEntered(), AWTEventMulticaster.mouseExited(), AWTEventMulticaster.mouseMoved(), AWTEventMulticaster.mousePressed(), AWTEventMulticaster.mouseReleased(), Component.processMouseEvent(), Component.processMouseMotionEvent(), MouseAdapter.mouseClicked(), MouseAdapter.mouseEntered(), MouseAdapter.mouseExited(), MouseAdapter.mousePressed(), MouseAdapter.mouseReleased(), MouseListener.mouseClicked(), MouseListener.mouseEntered(), MouseListener.mouseExited(), MouseListener.mousePressed(), MouseListener.mouseReleased(), MouseMotionAdapter.mouseDragged(), MouseMotionAdapter.mouseMoved(), MouseMotionListener.mouseDragged(), MouseMotionListener.mouseMoved()
java.awt.event.MouseAdapter (JDK 1.1)
java.awt.event.MouseListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_21.htm (2 of 2) [20/12/2001 11:00:40]
[Chapter 20] 20.25 java.awt.event.PaintEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.25 java.awt.event.PaintEvent (JDK 1.1) An event of this type indicates that a component should have its update() method invoked. (The update() method typically, by default, invokes the paint() method.) PaintEvent differs from the other event types in java.awt.event in that it does not have a corresponding EventListener interface. PaintEvent is essentially for internal use by the AWT redisplay framework, so your programs should not try to handle it the way they handle other events. Instead, applets and custom components should simply override their paint() and/or update() methods to redraw themselves appropriately. AWT automatically invokes update() (which typically invokes paint()) when a PaintEvent arrives. Although you do not typically use the PaintEvent, redraw events are implemented through this class for simplicity, so that they are on equal footing with other event types, and so that advanced programs can manipulate them through the EventQueue. public class PaintEvent extends ComponentEvent { // Public Constructor public PaintEvent(Component source, int id, Rectangle updateRect); // Constants public static final int PAINT; public static final int PAINT_FIRST; public static final int PAINT_LAST; public static final int UPDATE; // Public Instance Methods public Rectangle getUpdateRect(); public String paramString(); // Overrides ComponentEvent public void setUpdateRect(Rectangle updateRect); }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->ComponentEvent->PaintEvent
java.awt.event.MouseMotionListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_25.htm [20/12/2001 11:00:40]
java.awt.event.TextEvent (JDK 1.1)
[Chapter 20] 20.26 java.awt.event.TextEvent (JDK 1.1)
Chapter 20 The java.awt.event Package
20.26 java.awt.event.TextEvent (JDK 1.1) An event of this type indicates that the user has edited the text value that appears in a TextField, TextArea, or other TextComponent. This event is triggered by any change to the displayed text. Note that this is not the same as the ActionEvent sent by the TextField object when the user edits the text and strikes the Return key. Use the inherited getSource() to determine the object that was the source of this event. You have to cast that object to its TextComponent type. Call getID() to determine the type of a TextEvent. The standard AWT components always generate text events of type TEXT_VALUE_CHANGED. public class TextEvent extends AWTEvent { // Public Constructor public TextEvent(Object source, int id); // Constants public static final int TEXT_FIRST; public static final int TEXT_LAST; public static final int TEXT_VALUE_CHANGED; // Public Instance Methods public String paramString(); // Overrides AWTEvent }
Hierarchy: Object->EventObject(Serializable)->AWTEvent->TextEvent
Passed To: AWTEventMulticaster.textValueChanged(), TextComponent.processTextEvent(), TextListener.textValueChanged()
java.awt.event.PaintEvent (JDK 1.1) http://localhost/java/javaref/javanut/ch20_26.htm (1 of 2) [20/12/2001 11:00:40]
java.awt.event.TextListener (JDK 1.1)
[Chapter 20] 20.26 java.awt.event.TextEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_26.htm (2 of 2) [20/12/2001 11:00:40]
[Chapter 25] 25.19 java.lang.Exception (JDK 1.0)
Chapter 25 The java.lang Package
25.19 java.lang.Exception (JDK 1.0) This class forms the root of the exception hierarchy in Java. An Exception signals an abnormal condition that must be specially handled to prevent program termination. Exceptions may be caught and handled. Exceptions that are not subclasses of RuntimeException must be declared in the throws clause of any method that can throw them. getMessage() returns a message associated with the exception. See Throwable for other methods. public class Exception extends Throwable { // Public Constructors public Exception(); public Exception(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception
Extended By: AWTException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, IllegalAccessException, InstantiationException, InterruptedException, IntrospectionException, InvocationTargetException, IOException, NoSuchFieldException, NoSuchMethodException, ParseException, PropertyVetoException, RuntimeException, TooManyListenersException, UnsupportedFlavorException
Passed To: WriteAbortedException()
http://localhost/java/javaref/javanut/ch25_19.htm (1 of 2) [20/12/2001 11:00:41]
[Chapter 25] 25.19 java.lang.Exception (JDK 1.0)
Type Of: WriteAbortedException.detail
java.lang.Error (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_19.htm (2 of 2) [20/12/2001 11:00:41]
java.lang.ExceptionInInitializerError (JDK 1.1)
[Chapter 25] 25.20 java.lang.ExceptionInInitializerError (JDK 1.1)
Chapter 25 The java.lang Package
25.20 java.lang.ExceptionInInitializerError (JDK 1.1) This error is thrown by the Java Virtual Machine when an exception occurs in the static initializer of a class. You can use the getException() method to obtain the Throwable object that was thrown from the initializer. public class ExceptionInInitializerError extends LinkageError { // Public Constructors public ExceptionInInitializerError(); public ExceptionInInitializerError(Throwable thrown); public ExceptionInInitializerError(String s); // Public Instance Methods public Throwable getException(); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->ExceptionInInitializerError
java.lang.Exception (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_20.htm [20/12/2001 11:00:41]
java.lang.Float (JDK 1.0)
[Chapter 3] 3.5 Object Destruction
Chapter 3 Classes and Objects in Java
3.5 Object Destruction Now that we've seen how you can create and use objects, the next obvious question, a question that C and C++ programmers have been itching to have answered, is how do you destroy objects when they are no longer needed? The answer is: You don't! Objects are not passed to any free() method, as allocated memory in C is. And there is no delete operator as there is in C++. Java takes care of object destruction for you, and lets you concentrate on other, more important things, like the algorithm you're working on.
Garbage Collection The technique Java uses to get rid of objects once they are no longer needed is called garbage collection. It is a technique that has been around for years in languages such as Lisp. The Java interpreter knows what objects it has allocated. It can also figure out which variables refer to which objects, and which objects refer to which other objects. Thus, it can figure out when an allocated object is no longer referred to by any other object or variable. When it finds such an object, it knows that it can destroy it safely, and does so. The garbage collector can also detect and destroy "cycles" of objects that refer to each other, but are not referred to by any other objects. The Java garbage collector runs as a low-priority thread, and does most of its work when nothing else is going on. Generally, it runs during idle time while waiting for user input in the form of keystrokes or mouse events. The only time the garbage collector must run while something high-priority is going on (i.e., the only time it will actually slow down the system) is when the interpreter has run out of memory. This doesn't happen often because there is that low-priority thread cleaning things up in the background. This scheme may sound extremely slow and wasteful of memory. Actually though, good garbage collectors can be surprisingly efficient. No, garbage collection will never be as efficient as explicit, well-written memory allocation and deallocation. But it does make programming a lot easier and less prone to bugs. And for most real-world programs, rapid development, lack of bugs, and easy maintenance are more important features than raw speed or memory efficiency.
Putting the Trash Out What garbage collection means for your programs is that when you are done with an object, you can just forget about it--the garbage collector finds it and takes care of it. Example 3.7 shows an example. Example 3.7: Leaving an Object Out for Garbage Collection
http://localhost/java/javaref/javanut/ch03_05.htm (1 of 3) [20/12/2001 11:00:41]
[Chapter 3] 3.5 Object Destruction
String processString(String s) { // Create a StringBuffer object to process the string in. StringBuffer b = new StringBuffer(s); // Process it somehow... // Peturn it as a String. Just forget about the StringBuffer object: // it will be automatically garbage collected. return b.toString(); } If you're a C or C++ programmer, conditioned to allocating and deallocating your own dynamic memory, you may at first feel a nagging sense of misgiving when you write procedures that allocate and then forget objects. You'll get used to it though, and even learn to love it! There is an instance where you may want to take some action to help the garbage collection process along by "forgetting quickly." Example 3.8 explains. Example 3.8: Forced Forgetting of an Object public static void main(String argv[]) { int big_array[] = new int[100000]; // Do some computations with big_array and get a result. int result = compute(big_array); // We no longer need big_array. It will get garbage collected when // there are no more references. Since big_array is a local variable, // it refers to the array until this method returns. But this // method doesn't return. So we've got to get rid of the reference // ourselves, just to help out the garbage collector. big_array = null; // Loop forever, handling the user's input. for(;;) handle_input(); }
Object Finalization Just as a constructor method performs initialization for an object, a Java finalizer method performs finalization for an object. Garbage collection automatically frees up the memory resources used by objects. But objects may hold other kinds of resources, such as file descriptors or sockets, as well. The garbage collector can't free these resources up for you, so you should write a finalizer method that takes care of things like closing open files, terminating network connections, and so on. Example 3.9 shows the finalizer method from the Java FileOutputStream class. Note that a finalizer is an instance method (i.e., non-static), takes no arguments, returns no value (i.e., void), and must be named finalize(). [6]
http://localhost/java/javaref/javanut/ch03_05.htm (2 of 3) [20/12/2001 11:00:41]
[Chapter 3] 3.5 Object Destruction
[6] C++ programmers, take note! Although Java constructor methods are named like C++ constructors, Java finalization methods are not named like C++ destructor methods. Example 3.9: A Finalizer Method /** * Closes the stream when garbage is collected. * Checks the file descriptor first to make sure it is not already closed. */ protected void finalize() throws IOException { if (fd != null) close(); } There are some additional things to be aware of about finalizers: ● If an object has a finalizer, that method is invoked before the system garbage collects the object. ● The Java interpreter may exit without garbage collecting all outstanding objects, so some finalizers may never be invoked. In this case, though, any outstanding resources are usually freed by the operating system. ● Java makes no guarantees about when garbage collection will occur, or what order objects will be collected in. Therefore, Java can make no guarantees about when a finalizer will be invoked, or in what order finalizers will be invoked, or what thread will execute finalizers. ● After a finalizer is invoked, objects are not freed right away. This is because a finalizer method may "resurrect" an object by storing the this pointer somewhere, so that the object once again has references. Thus, after finalize() is called, an object must once again be determined to be unreferenced before it can actually be garbage collected. Even if an object is "resurrected," the finalizer method is never invoked more than once. Note that resurrecting an object is never a useful thing to do--just a strange quirk of object finalization. ● The finalizer shown in Example 3.9 declares that it may throw an exception (exceptions are described in detail in Chapter 2, How Java Differs from C). If an uncaught exception actually occurs in a finalizer method, however, the exception is ignored by the system.
Class Methods
http://localhost/java/javaref/javanut/ch03_05.htm (3 of 3) [20/12/2001 11:00:41]
Subclasses and Inheritance
[Chapter 25] 25.64 java.lang.Throwable (JDK 1.0)
Chapter 25 The java.lang Package
25.64 java.lang.Throwable (JDK 1.0) This is the root class of the Java exception and error hierarchy. All exceptions and errors are subclasses of Throwable. The getMessage() method retrieves any error message associated with the exception or error. printStackTrace() prints a stack trace that shows where the exception occurred. fillInStackTrace() extends the stack trace when the exception is partially handled, and then re-thrown. public class Throwable extends Object implements Serializable { // Public Constructors public Throwable(); public Throwable(String message); // Public Instance Methods public native Throwable fillInStackTrace(); 1.1public String getLocalizedMessage(); public String getMessage(); public void printStackTrace(); public void printStackTrace(PrintStream s); 1.1public void printStackTrace(PrintWriter s); public String toString(); // Overrides Object }
Extended By: Error, Exception
Passed To: ExceptionInInitializerError(), InvocationTargetException(), Thread.stop(), ThreadGroup.uncaughtException()
http://localhost/java/javaref/javanut/ch25_64.htm (1 of 2) [20/12/2001 11:00:41]
[Chapter 25] 25.64 java.lang.Throwable (JDK 1.0)
Returned By: ExceptionInInitializerError.getException(), InvocationTargetException.getTargetException(), Throwable.fillInStackTrace()
Thrown By: Object.finalize()
java.lang.ThreadGroup (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_64.htm (2 of 2) [20/12/2001 11:00:41]
java.lang.UnknownError (JDK 1.0)
[Chapter 25] 25.51 java.lang.Runtime (JDK 1.0)
Chapter 25 The java.lang Package
25.51 java.lang.Runtime (JDK 1.0) This class encapsulates a number of platform-dependent system functions. The static method getRuntime() returns the Runtime object for the current platform, and this object can be used to perform system functions in a platform-independent way. exec() starts a new process running externally to the interpreter. Note that any processes run outside of Java may be system-dependent. exit() causes the Java interpreter to exit and return a specified return code. freeMemory() returns the approximate amount of free memory. totalMemory() returns the total amount of memory available to the Java interpreter. gc() forces the garbage collector to run synchronously, which may free up more memory. Similarly, runFinalization() forces the finalize() methods of unreferenced objects to be run immediately. This may free up system resources that those objects were holding. load() loads a dynamic library with a fully specified path name. loadLibrary() loads a dynamic library with only the library name specified; it looks in platform-dependent locations for the specified library. These libraries generally contain native code definitions for native methods. traceInstructions() and traceMethodCalls() enable and disable tracing by the interpreter. Note that some of the Runtime methods are more commonly called via the static methods of the System class. public class Runtime extends Object { // No Constructor // Class Methods public static Runtime getRuntime(); 1.1public static void runFinalizersOnExit(boolean value); // Public Instance Methods public Process exec(String command) throws IOException; public Process exec(String command, String[] envp) throws IOException; public Process exec(String[] cmdarray) throws IOException; public Process exec(String[] cmdarray, String[] envp) throws IOException; public void exit(int status); public native long freeMemory(); public native void gc(); # public InputStream getLocalizedInputStream(InputStream in); # public OutputStream getLocalizedOutputStream(OutputStream out); public synchronized void load(String filename); public synchronized void loadLibrary(String libname); public native void runFinalization(); public native long totalMemory(); public native void traceInstructions(boolean on); public native void traceMethodCalls(boolean on); } http://localhost/java/javaref/javanut/ch25_51.htm (1 of 2) [20/12/2001 11:00:42]
[Chapter 25] 25.51 java.lang.Runtime (JDK 1.0)
Returned By: Runtime.getRuntime()
java.lang.Runnable (JDK 1.0)
java.lang.RuntimeException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_51.htm (2 of 2) [20/12/2001 11:00:42]
[Chapter 4] 4.7 Object Serialization
Chapter 4 What's New in Java 1.1
4.7 Object Serialization Object serialization is one of the major new features of Java 1.1. It refers to the ability to write the complete state of an object (including any objects it refers to) to an output stream, and then recreate that object at some later time by reading its serialized state from an input stream. You can serialize an object simply by passing it to the writeObject() method of an ObjectOutputStream. Similarly, you can create an object from a serialized object stream by calling the readObject() method of an ObjectInputStream. Both of these new object stream types are part of the java.io package. Typically, object serialization is as simple as calling writeObject() and readObject(). There are a few additional twists, however, that are worth mentioning here. First, only objects that subclass the Serializable (or Externalizable) interface can be serialized. The Serializable interface does not define any methods, but merely acts as a marker that indicates whether serialization is allowed on a given object. Second, fields of a class declared transient are not serialized as part of an object's state. The transient modifier was legal in Java 1.0, but had no defined behavior. Third, some objects may need to implement custom serialization or de-serialization behavior. They can do this by implementing special readObject() and writeObject() methods. Chapter 9, Object Serialization describes all of these aspects of object serialization in more detail. Despite the fact that only a few classes and interfaces are part of the Object Serialization API, serialization is a very important technology and is used in several places in Java 1.1. It is used as the basis for transferring objects via cut-and-paste. It is used to transfer objects between a client and a server for remote method invocation. It is used by the JavaBeans API--beans are often provided as pre-initialized, serialized objects, rather than merely as class files. Java 1.1 also adds the capability for applets to be loaded into an applet viewer or browser as serialized objects. One common use we are likely to see for object serialization is as a way to save user preferences and other application states--a serialized object is an instant file format that works for any application. Another use that should be popular with GUI builder tools is saving the complete Component hierarchy of an application's GUI as a serialized object, and then later loading in that object in order to automatically recreate the GUI.
Internationalization
http://localhost/java/javaref/javanut/ch04_07.htm [20/12/2001 11:00:42]
Reflection
[Chapter 24] 24.15 java.io.Externalizable (JDK 1.1)
Chapter 24 The java.io Package
24.15 java.io.Externalizable (JDK 1.1) This interface defines the methods that must be implemented by an object that wants complete control over the way it is serialized. The writeExternal() and readExternal() methods should be implemented to write and read object data in some arbitrary format, using the methods of the DataOutput and DataInput objects. Externalizable objects must serialize their own fields, and are also responsible for serializing the fields of their superclasses. Most objects do not need to define a custom output format and can use the Serializable interface instead of Externalizable for serialization. public abstract interface Externalizable extends Serializable { // Public Instance Methods public abstract void readExternal(ObjectInput in) throws IOException, ClassNotFoundException; public abstract void writeExternal(ObjectOutput out) throws IOException; }
java.io.EOFException (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_15.htm [20/12/2001 11:00:42]
java.io.File (JDK 1.0)
[Chapter 23] 23.6 java.beans.FeatureDescriptor (JDK 1.1)
Chapter 23 The java.beans Package
23.6 java.beans.FeatureDescriptor (JDK 1.1) The FeatureDescriptor class is the base class for MethodDescriptor and PropertyDescriptor, as well as other classes used by the JavaBeans introspection mechanism. It provides basic information about a feature (method, property, event, etc.) of a bean. Typically, the methods that begin with get and is are used by application builders or other tools to query the features of a bean. The set methods, on the other hand, may be used by bean authors to define information about the bean. setName() specifies the locale-independent, programmatic name of the feature. setDisplayName() specifies a localized, human-readable name. setShortDescription() specifies a short localized string (about 40 characters) that describes the feature. Both the short description and the localized name default to the value of the programmatic name. setExpert() and setHidden() allow you to indicate that the feature is for use only by experts, or for use only by the builder tool, and should be hidden from users of the builder. Finally, the setValue() method allows you to associate an arbitrary named value with the feature. public class FeatureDescriptor extends Object { // Public Constructor public FeatureDescriptor(); // Public Instance Methods public Enumeration attributeNames(); public String getDisplayName(); public String getName(); public String getShortDescription(); public Object getValue(String attributeName); public boolean isExpert(); public boolean isHidden(); public void setDisplayName(String displayName); public void setExpert(boolean expert); public void setHidden(boolean hidden); public void setName(String name); public void setShortDescription(String text); public void setValue(String attributeName, Object value); } http://localhost/java/javaref/javanut/ch23_06.htm (1 of 2) [20/12/2001 11:00:42]
[Chapter 23] 23.6 java.beans.FeatureDescriptor (JDK 1.1)
Extended By: BeanDescriptor, EventSetDescriptor, MethodDescriptor, ParameterDescriptor, PropertyDescriptor
java.beans.EventSetDescriptor (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_06.htm (2 of 2) [20/12/2001 11:00:42]
java.beans.IndexedPropertyDescriptor (JDK 1.1)
[Chapter 26] 26.3 java.lang.reflect.Field (JDK 1.1)
Chapter 26 The java.lang.reflect Package
26.3 java.lang.reflect.Field (JDK 1.1) This class represents a field of a class. Instances of Field are obtained by calling the getField() and related methods of java.lang.Class. Field implements the Member interface, so once you have obtained a Field object, you can use getName(), getModifiers(), and getDeclaringClass() to determine the name, modifiers, and class of the field. Additionally, getType() returns the type of the field. The set() method sets the value of the represented field for a specified object to a given value. (If the represented field is static, then no object need be specified for it to be set upon, of course.) If the field is of a primitive type, its value can be specified using a wrapper object of type Boolean, Integer, and so on, or it can be set using the setBoolean(), setInt(), and related methods. Similarly, the get() method queries the value of the represented field for a specified object and returns the field value as an Object. Various other methods query the field value and return it as various primitive types. public final class Field extends Object implements Member { // No Constructor // Public Instance Methods public boolean equals(Object obj); // Overrides Object public native Object get(Object obj) throws IllegalArgumentException, IllegalAccessException; public native boolean getBoolean(Object obj) throws IllegalArgumentException, IllegalAccessException; public native byte getByte(Object obj) throws IllegalArgumentException, IllegalAccessException; public native char getChar(Object obj) throws IllegalArgumentException, IllegalAccessException; public Class getDeclaringClass(); // From Member public native double getDouble(Object obj) throws IllegalArgumentException, IllegalAccessException; public native float getFloat(Object obj) throws IllegalArgumentException, IllegalAccessException; public native int getInt(Object obj) throws IllegalArgumentException, IllegalAccessException; public native long getLong(Object obj) throws IllegalArgumentException, IllegalAccessException; public native int getModifiers(); // From Member public String getName(); // From Member public native short getShort(Object obj) throws IllegalArgumentException, IllegalAccessException; public Class getType(); public int hashCode(); // Overrides Object public native void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException;
http://localhost/java/javaref/javanut/ch26_03.htm (1 of 2) [20/12/2001 11:00:42]
[Chapter 26] 26.3 java.lang.reflect.Field (JDK 1.1)
public native IllegalArgumentException, public native IllegalArgumentException, public native IllegalArgumentException, public native IllegalArgumentException, public native IllegalArgumentException, public native IllegalArgumentException, public native IllegalArgumentException, public native IllegalArgumentException, public String }
void setBoolean(Object obj, boolean z) throws IllegalAccessException; void setByte(Object obj, byte b) throws IllegalAccessException; void setChar(Object obj, char c) throws IllegalAccessException; void setDouble(Object obj, double d) throws IllegalAccessException; void setFloat(Object obj, float f) throws IllegalAccessException; void setInt(Object obj, int i) throws IllegalAccessException; void setLong(Object obj, long l) throws IllegalAccessException; void setShort(Object obj, short s) throws IllegalAccessException; toString(); // Overrides Object
Returned By: Class.getDeclaredField(), Class.getDeclaredFields(), Class.getField(), Class.getFields()
java.lang.reflect.Constructor (JDK 1.1)
java.lang.reflect.InvocationTargetException (JDK 1.1)
http://localhost/java/javaref/javanut/ch26_03.htm (2 of 2) [20/12/2001 11:00:42]
[Chapter 29] 29.11 java.text.FieldPosition (JDK 1.1)
Chapter 29 The java.text Package
29.11 java.text.FieldPosition (JDK 1.1) FieldPosition objects are optionally passed to the format() methods of the Format class and its subclasses to return additional information about the formatting that has been performed. The getBeginIndex() and getEndIndex() methods of this class are used to return the starting and ending character positions of some field of the formatted string. The integer value passed to the FieldPosition() constructor specifies what field of the returned string should have its bounds returned. The NumberFormat and DateFormat classes define various constants (which end with the string _FIELD) that can be used here. Typically, this bounds information is useful for aligning formatted strings in columns--for example, aligning the decimal points in a column of numbers. public class FieldPosition extends Object { // Public Constructor public FieldPosition(int field); // Public Instance Methods public int getBeginIndex(); public int getEndIndex(); public int getField(); }
Passed To: ChoiceFormat.format(), DateFormat.format(), DecimalFormat.format(), Format.format(), MessageFormat.format(), NumberFormat.format(), SimpleDateFormat.format()
java.text.DecimalFormatSymbols (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_11.htm [20/12/2001 11:00:43]
java.text.Format (JDK 1.1)
[Chapter 25] 25.40 java.lang.NoSuchFieldError (JDK 1.0)
Chapter 25 The java.lang Package
25.40 java.lang.NoSuchFieldError (JDK 1.0) Signals that a specified field could not be found. public class NoSuchFieldError extends IncompatibleClassChangeError { // Public Constructors public NoSuchFieldError(); public NoSuchFieldError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->IncompatibleClassChangeError->NoSuchFieldError
java.lang.NoClassDefFoundError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_40.htm [20/12/2001 11:00:43]
java.lang.NoSuchFieldException (JDK 1.1)
[Chapter 25] 25.41 java.lang.NoSuchFieldException (JDK 1.1)
Chapter 25 The java.lang Package
25.41 java.lang.NoSuchFieldException (JDK 1.1) This exception signals that the specified field does not exist in the specified class. public class NoSuchFieldException extends Exception { // Public Constructors public NoSuchFieldException(); public NoSuchFieldException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->NoSuchFieldException
Thrown By: Class.getDeclaredField(), Class.getField()
java.lang.NoSuchFieldError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_41.htm [20/12/2001 11:00:43]
java.lang.NoSuchMethodError (JDK 1.0)
[Chapter 24] 24.24 java.io.FilterInputStream (JDK 1.0)
Chapter 24 The java.io Package
24.24 java.io.FilterInputStream (JDK 1.0) This class provides method definitions required to filter data obtained from the InputStream specified when the FilterInputStream is created. It must be subclassed to perform some sort of filtering operation, and may not be instantiated directly. See the subclasses BufferedInputStream, DataInputStream, and PushbackInputStream. public class FilterInputStream extends InputStream { // Protected Constructor protected FilterInputStream(InputStream in); // Protected Instance Variables protected InputStream in; // Public Instance Methods public int available() throws IOException; // Overrides InputStream public void close() throws IOException; // Overrides InputStream public synchronized void mark(int readlimit); // Overrides InputStream public boolean markSupported(); // Overrides InputStream public int read() throws IOException; // Defines InputStream public int read(byte[] b) throws IOException; // Overrides InputStream public int read(byte[] b, int off, int len) throws IOException; // Overrides InputStream public synchronized void reset() throws IOException; // Overrides InputStream public long skip(long n) throws IOException; // Overrides InputStream }
Hierarchy: Object->InputStream->FilterInputStream
Extended By: BufferedInputStream, CheckedInputStream, DataInputStream, InflaterInputStream, LineNumberInputStream, PushbackInputStream
java.io.FilenameFilter (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_24.htm [20/12/2001 11:00:43]
java.io.FilterOutputStream (JDK 1.0)
[Chapter 24] 24.17 java.io.FileDescriptor (JDK 1.0)
Chapter 24 The java.io Package
24.17 java.io.FileDescriptor (JDK 1.0) This class is a platform-independent representation of a low-level handle to an open file or an open socket. The static in, out, and err variables are FileDescriptor objects that represent the system standard input, output, and error streams, respectively. There is no public constructor method to create a FileDescriptor object. You can obtain one with the getFD() method of FileInputStream, FileOutputStream, and RandomAccessFile. public final class FileDescriptor extends Object { // Default Constructor: public FileDescriptor() // Constants public static final FileDescriptor err; public static final FileDescriptor in; public static final FileDescriptor out; // Public Instance Methods 1.1 public native void sync() throws SyncFailedException; public native boolean valid(); }
Passed To: FileInputStream(), FileOutputStream(), FileReader(), FileWriter(), SecurityManager.checkRead(), SecurityManager.checkWrite()
Returned By: DatagramSocketImpl.getFileDescriptor(), FileInputStream.getFD(), FileOutputStream.getFD(), RandomAccessFile.getFD(), SocketImpl.getFileDescriptor()
Type Of: DatagramSocketImpl.fd, FileDescriptor.err, FileDescriptor.in, FileDescriptor.out, SocketImpl.fd
http://localhost/java/javaref/javanut/ch24_17.htm (1 of 2) [20/12/2001 11:00:43]
[Chapter 24] 24.17 java.io.FileDescriptor (JDK 1.0)
java.io.File (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_17.htm (2 of 2) [20/12/2001 11:00:43]
java.io.FileInputStream (JDK 1.0)
[Chapter 28] 28.8 java.net.FileNameMap (JDK 1.1)
Chapter 28 The java.net Package
28.8 java.net.FileNameMap (JDK 1.1) This interface defines a single method that is called to obtain the MIME type of a file based on the name of a file. The fileNameMap field of the URLConnection class refers to an object that implements this interface. The filename-to-file-type map it implements is used by the static URLConnection.guessContentTypeFromName() method. public abstract interface FileNameMap { // Public Instance Methods public abstract String getContentTypeFor(String fileName); }
Type Of: URLConnection.fileNameMap
java.net.DatagramSocketImpl (JDK 1.1)
http://localhost/java/javaref/javanut/ch28_08.htm [20/12/2001 11:00:43]
java.net.HttpURLConnection (JDK 1.1)
[Chapter 24] 24.19 java.io.FileNotFoundException (JDK 1.0)
Chapter 24 The java.io Package
24.19 java.io.FileNotFoundException (JDK 1.0) An IOException that signals that a specified file cannot be found. public class FileNotFoundException extends IOException { // Public Constructors public FileNotFoundException(); public FileNotFoundException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->FileNotFoundException
Thrown By: FileInputStream(), FileReader()
java.io.FileInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_19.htm [20/12/2001 11:00:44]
java.io.FileOutputStream (JDK 1.0)
[Chapter 24] 24.21 java.io.FileReader (JDK 1.1)
Chapter 24 The java.io Package
24.21 java.io.FileReader (JDK 1.1) FileReader is a convenience subclass of InputStreamReader that is useful when you want to read text (as opposed to binary data) from a file. You create a FileReader by specifying the file to be read, in any of three possible forms. The FileReader constructor internally creates a FileInputStream to read bytes from the specified file, and uses the functionality of its superclass, InputStreamReader, to convert those bytes from characters in the local encoding to the Unicode characters used by Java. Because FileReader is a trivial subclass of InputStreamReader, it does not define any read() methods or other methods of its own. Instead, it inherits all its methods from its superclass. If you want to read Unicode characters from a file that uses some encoding other than the default encoding for the locale, you must explicitly create your own InputStreamReader to perform the byte-to-character conversion. public class FileReader extends InputStreamReader { // Public Constructors public FileReader(String fileName) throws FileNotFoundException; public FileReader(File file) throws FileNotFoundException; public FileReader(FileDescriptor fd); }
Hierarchy: Object->Reader->InputStreamReader->FileReader
java.io.FileOutputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_21.htm [20/12/2001 11:00:44]
java.io.FileWriter (JDK 1.1)
[Chapter 24] 24.22 java.io.FileWriter (JDK 1.1)
Chapter 24 The java.io Package
24.22 java.io.FileWriter (JDK 1.1) FileWriter is a convenience subclass of OutputStreamWriter that is useful when you want to write text (as opposed to binary data) to a file. You create a FileWriter by specifying the file to be written to, and optionally specifying whether the data should be appended to the end of an existing file instead of overwriting that file. The FileWriter class creates an internal FileOutputStream to write bytes to the specified file, and uses the functionality of its superclass, OutputStreamWriter, to convert the Unicode characters written to the stream characters into bytes using the default encoding of the default locale. (If you want to use an encoding other than the default, you cannot use FileWriter; in that case you must create your own OutputStreamWriter and FileOutputStream.) Because FileWriter is a trivial subclass of OutputStreamWriter, it does not define any methods of its own, but simply inherits them from its superclass. public class FileWriter extends OutputStreamWriter { // Public Constructors public FileWriter(String fileName) throws IOException; public FileWriter(String fileName, boolean append) throws IOException; public FileWriter(File file) throws IOException; public FileWriter(FileDescriptor fd); }
Hierarchy: Object->Writer->OutputStreamWriter->FileWriter
java.io.FileReader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_22.htm [20/12/2001 11:00:44]
java.io.FilenameFilter (JDK 1.0)
[Chapter 24] 24.56 java.io.RandomAccessFile (JDK 1.0)
Chapter 24 The java.io Package
24.56 java.io.RandomAccessFile (JDK 1.0) This class allows reading and writing of arbitrary bytes, text, and primitive Java data types from or to any specified location in a file. Because this class provides random, rather than sequential, access to files, it is neither a subclass of InputStream nor of OutputStream, but provides an entirely independent method for reading and writing data from or to files. RandomAccessFile implements the same interfaces as DataInputStream and DataOutputStream, and thus defines the same methods for reading and writing data as those classes do. The seek() method provides random access to the file--it is used to select the position in the file from which, or to which, data should be read or written. The mode argument to the constructor methods should be "r" for a file that is to be read-only, and "rw" for a file that is to be written (and perhaps read as well). public class RandomAccessFile extends Object implements DataOutput, DataInput { // Public Constructors public RandomAccessFile(String name, String mode) throws IOException; public RandomAccessFile(File file, String mode) throws IOException; // Public Instance Methods public native void close() throws IOException; public final FileDescriptor getFD() throws IOException; public native long getFilePointer() throws IOException; public native long length() throws IOException; public native int read() throws IOException; public int read(byte[] b, int off, int len) throws IOException; public int read(byte[] b) throws IOException; public final boolean readBoolean() throws IOException; // From DataInput public final byte readByte() throws IOException; // From DataInput public final char readChar() throws IOException; // From DataInput public final double readDouble() throws IOException; // From DataInput public final float readFloat() throws IOException; // From DataInput public final void readFully(byte[] b) throws IOException; // From DataInput public final void readFully(byte[] b, int off, int len) throws IOException; // From DataInput public final int readInt() throws IOException; // From DataInput public final String readLine() throws IOException; // From DataInput public final long readLong() throws IOException; // From DataInput public final short readShort() throws IOException; // From DataInput public final String readUTF() throws IOException; // From DataInput public final int readUnsignedByte() throws IOException; // From DataInput public final int readUnsignedShort() throws IOException; // From DataInput public native void seek(long pos) throws IOException; public int skipBytes(int n) throws IOException; // From DataInput
http://localhost/java/javaref/javanut/ch24_56.htm (1 of 2) [20/12/2001 11:00:44]
[Chapter 24] 24.56 java.io.RandomAccessFile (JDK 1.0)
public public public From DataOutput public DataOutput public DataOutput public DataOutput public DataOutput public DataOutput public DataOutput public DataOutput public public DataOutput public DataOutput public DataOutput }
native void write(int b) throws IOException; // From DataOutput void write(byte[] b) throws IOException; // From DataOutput void write(byte[] b, int off, int len) throws IOException; // final void writeBoolean(boolean v) throws IOException; final void writeByte(int v) throws IOException;
// From
final void writeBytes(String s) throws IOException; final void writeChar(int v) throws IOException;
// From
// From
// From
final void writeChars(String s) throws IOException; final void writeDouble(double v) throws IOException;
// From
final void writeFloat(float v) throws IOException;
// From // From
final void writeInt(int v) throws IOException; // From DataOutput final void writeLong(long v) throws IOException; // From final void writeShort(int v) throws IOException;
// From
final void writeUTF(String str) throws IOException;
java.io.PushbackReader (JDK 1.1)
java.io.Reader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_56.htm (2 of 2) [20/12/2001 11:00:44]
// From
[Chapter 21] 21.5 java.awt.image.FilteredImageSource (JDK 1.0)
Chapter 21 The java.awt.image Package
21.5 java.awt.image.FilteredImageSource (JDK 1.0) This class is an ImageProducer that produces image data filtered from some other ImageProducer. A FilteredImageSource is created with a specified ImageProducer and a specified ImageFilter. For example, an applet might use the following code to download and crop an image: Image full_image = getImage(getDocumentBase(), "images/1.gif"); ImageFilter cropper = new CropImageFilter(10, 10, 100, 100); ImageProducer prod = new FilteredImageSource(full_image.getSource(), cropper); Image cropped_image = createImage(prod); The methods of this class are the standard ImageProducer methods that you can invoke to add and remove ImageConsumer objects. public class FilteredImageSource extends Object implements ImageProducer { // Public Constructor public FilteredImageSource(ImageProducer orig, ImageFilter imgf); // Public Instance Methods public synchronized void addConsumer(ImageConsumer ic); // From ImageProducer public synchronized boolean isConsumer(ImageConsumer ic); // From ImageProducer public synchronized void removeConsumer(ImageConsumer ic); // From ImageProducer public void requestTopDownLeftRightResend(ImageConsumer ic); // From ImageProducer public void startProduction(ImageConsumer ic); // From ImageProducer }
java.awt.image.DirectColorModel (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_05.htm [20/12/2001 11:00:45]
java.awt.image.ImageConsumer (JDK 1.0)
[Chapter 24] 24.25 java.io.FilterOutputStream (JDK 1.0)
Chapter 24 The java.io Package
24.25 java.io.FilterOutputStream (JDK 1.0) This class provides method definitions required to filter the data to be written to the OutputStream specified when the FilterOutputStream is created. It must be subclassed to perform some sort of filtering operation and may not be instantiated directly. See the subclasses BufferedOutputStream and DataOutputStream. public class FilterOutputStream extends OutputStream { // Public Constructor public FilterOutputStream(OutputStream out); // Protected Instance Variables protected OutputStream out; // Public Instance Methods public void close() throws IOException; // Overrides OutputStream public void flush() throws IOException; // Overrides OutputStream public void write(int b) throws IOException; // Defines OutputStream public void write(byte[] b) throws IOException; // Overrides OutputStream public void write(byte[] b, int off, int len) throws IOException; // Overrides OutputStream }
Hierarchy: Object->OutputStream->FilterOutputStream
Extended By: BufferedOutputStream, CheckedOutputStream, DataOutputStream, DeflaterOutputStream, PrintStream
java.io.FilterInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_25.htm [20/12/2001 11:00:45]
java.io.FilterReader (JDK 1.1)
[Chapter 24] 24.26 java.io.FilterReader (JDK 1.1)
Chapter 24 The java.io Package
24.26 java.io.FilterReader (JDK 1.1) This abstract class is intended to act as a superclass for character input streams that read data from some other character input stream, filter it in some way, and then return the filtered data when their own read() methods are called. FilterReader is declared abstract, so that it cannot be instantiated. But none of its methods are themselves abstract: they all simply call the requested operation on the input stream passed to the FilterReader() constructor. If you were allowed to instantiate a FilterReader, you'd find that it is a "null filter"--i.e., it simply reads characters from the specified input stream and returns them without filtering of any kind. Because FilterReader implements a "null filter," it is an ideal superclass for classes that want to implement simple filters, but do not want to override all of the methods of Reader. In order to create your own filtered character input stream, you should subclass FilterReader and override both of its read() methods to perform the desired filtering operation. Note that you can implement one of the read() methods in terms of the other, and thus only implement the filtration once. Recall that the other read() methods defined by Reader are implemented in terms of these methods, so you do not need to override those. In some cases, you may also need to override other methods of FilterReader as well, and you may want to provide methods or constructors that are specific to your subclass. FilterReader is the character-stream analog to FilterInputStream. public abstract class FilterReader extends Reader { // Protected Constructor protected FilterReader(Reader in); // Protected Instance Variables protected Reader in; // Public Instance Methods public void close() throws IOException; // Defines Reader public void mark(int readAheadLimit) throws IOException; // Overrides Reader public boolean markSupported(); // Overrides Reader public int read() throws IOException; // Overrides Reader public int read(char[] cbuf, int off, int len) throws IOException; // Defines Reader public boolean ready() throws IOException; // Overrides Reader public void reset() throws IOException; // Overrides Reader public long skip(long n) throws IOException; // Overrides Reader }
Hierarchy: Object->Reader->FilterReader
http://localhost/java/javaref/javanut/ch24_26.htm (1 of 2) [20/12/2001 11:00:45]
[Chapter 24] 24.26 java.io.FilterReader (JDK 1.1)
Extended By: PushbackReader
java.io.FilterOutputStream (JDK 1.0)
java.io.FilterWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_26.htm (2 of 2) [20/12/2001 11:00:45]
[Chapter 24] 24.27 java.io.FilterWriter (JDK 1.1)
Chapter 24 The java.io Package
24.27 java.io.FilterWriter (JDK 1.1) This abstract class is intended to act as a superclass for character output streams that filter the data written to them before writing it to some other character output stream. FilterWriter is declared abstract, so that it cannot be instantiated. But none of its methods are themselves abstract: they all simply invoke the corresponding method on the output stream that was passed to the FilterWriter constructor. If you were allowed to instantiate a FilterWriter object, you'd find that it acts as a "null filter"--that it simply passes the characters written to it along, without any filtration. Because FilterWriter implements a "null filter," it is an ideal superclass for classes that want to implement simple filters without having to override all of the methods of Writer. In order to create your own filtered character output stream, you should subclass FilterWriter and override all of its write() methods to perform the desired filtering operation. Note that you can implement two of the write() methods in terms of the third, and thus only implement your filtering algorithm once. In some cases, you may want to override other Writer methods as well, and you may often want to add other methods or constructors that are specific to your subclass. FilterWriter is the character-stream analog of FilterOutputStream. public abstract class FilterWriter extends Writer { // Protected Constructor protected FilterWriter(Writer out); // Protected Instance Variables protected Writer out; // Public Instance Methods public void close() throws IOException; // Defines Writer public void flush() throws IOException; // Defines Writer public void write(int c) throws IOException; // Overrides Writer public void write(char[] cbuf, int off, int len) throws IOException; // Defines Writer public void write(String str, int off, int len) throws IOException; // Overrides Writer }
Hierarchy: Object->Writer->FilterWriter
java.io.FilterReader (JDK 1.1)
java.io.InputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_27.htm [20/12/2001 11:00:45]
[Chapter 23] 23.17 java.beans.PropertyEditorManager (JDK 1.1)
Chapter 23 The java.beans Package
23.17 java.beans.PropertyEditorManager (JDK 1.1) The PropertyEditorManager class is never meant to be instantiated; it defines static methods for registering and looking up PropertyEditor classes for a specified property type. A Java bean may specify a particular PropertyEditor class for a given property by specifying it in a PropertyDescriptor object for the property. If it does not do this, the PropertyEditorManager is used to register and look up editors. A bean or an application builder tool may call the registerEditor() method to register a PropertyEditor for properties of a specified type. Application builders and bean Customizer classes may call the findEditor() method to obtain a PropertyEditor for a given property type. If no editor has been registered for a given type, the PropertyEditorManager attempts to locate one. For a type x, it looks for a class xEditor first in the same package as x, and then in each package listed in the property editor search path. public class PropertyEditorManager extends Object { // Default Constructor: public PropertyEditorManager() // Class Methods public static PropertyEditor findEditor(Class targetType); public static String[] getEditorSearchPath(); public static void registerEditor(Class targetType, Class editorClass); public static void setEditorSearchPath(String[] path); }
java.beans.PropertyEditor (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_17.htm [20/12/2001 11:00:46]
java.beans.PropertyEditorSupport (JDK 1.1)
[Chapter 23] 23.14 java.beans.PropertyChangeSupport (JDK 1.1)
Chapter 23 The java.beans Package
23.14 java.beans.PropertyChangeSupport (JDK 1.1) The PropertyChangeSupport class is a convenience class that maintains a list of registered PropertyChangeListener objects and provides the firePropertyChange() method for sending a PropertyChangeEvent object to all registered listeners. Because there are some tricky thread synchronization issues involved in doing this correctly, it is recommended that all Java beans that support "bound" properties either extend this class, or, more commonly, create an instance of this class to which they can delegate the task of maintaining the list of listeners. public class PropertyChangeSupport extends Object implements Serializable { // Public Constructor public PropertyChangeSupport(Object sourceBean); // Public Instance Methods public synchronized void addPropertyChangeListener(PropertyChangeListener listener); public void firePropertyChange(String propertyName, Object oldValue, Object newValue); public synchronized void removePropertyChangeListener(PropertyChangeListener listener); }
java.beans.PropertyChangeListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_14.htm [20/12/2001 11:00:46]
java.beans.PropertyDescriptor (JDK 1.1)
[Chapter 23] 23.22 java.beans.VetoableChangeSupport (JDK 1.1)
Chapter 23 The java.beans Package
23.22 java.beans.VetoableChangeSupport (JDK 1.1) VetoableChangeSupport is a convenience class that maintains a list of registered VetoableChangeListener objects and provides a fireVetoableChange() method for sending a PropertyChangeEvent to all registered listeners. If any of the registered listeners veto the proposed change, fireVetoableChange() send out another PropertyChangeEvent notifying previously notified listeners that the property has changed back to its original value. Because of the extra complexity of correctly handling vetoable changes, and because of some tricky thread synchronization issues involved in maintaining the list of listeners, it is recommended that all Java beans that support "constrained" events create a VetoableChangeSupport object to which they can delegate the tasks of maintaining the list of listeners and of firing events. public class VetoableChangeSupport extends Object implements Serializable { // Public Constructor public VetoableChangeSupport(Object sourceBean); // Public Instance Methods public synchronized void addVetoableChangeListener(VetoableChangeListener listener); public void fireVetoableChange(String propertyName, Object oldValue, Object newValue) public void fireVetoableChange'u'throws PropertyVetoException; public synchronized void removeVetoableChangeListener(VetoableChangeListener listener); }
java.beans.VetoableChangeListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_22.htm [20/12/2001 11:00:46]
java.beans.Visibility (JDK 1.1)
[Chapter 18] 18.23 java.awt.FlowLayout (JDK 1.0)
Chapter 18 The java.awt Package
18.23 java.awt.FlowLayout (JDK 1.0) This class implements the LayoutManager interface to lay out Component objects in a Container. FlowLayout arranges components in a container like words on a page: from left to right and top to bottom. It fits as many components as it can in a row before moving on to the next row. The constructor allows you to specify one of three constants as an alignment value for the rows, and also allows you to specify horizontal spacing between components and vertical spacing between rows. Note that applications should never call the LayoutManager methods of this class directly; the Container for which the FlowLayout is registered does this. public class FlowLayout extends Object implements LayoutManager, Serializable { // Public Constructors public FlowLayout(); public FlowLayout(int align); public FlowLayout(int align, int hgap, int vgap); // Constants public static final int CENTER; public static final int LEFT; public static final int RIGHT; // Public Instance Methods public void addLayoutComponent(String name, Component comp); // From LayoutManager 1.1 public int getAlignment(); 1.1 public int getHgap(); 1.1 public int getVgap(); public void layoutContainer(Container target); // From LayoutManager public Dimension minimumLayoutSize(Container target); // From LayoutManager public Dimension preferredLayoutSize(Container target); // From LayoutManager public void removeLayoutComponent(Component comp); // From LayoutManager 1.1 public void setAlignment(int align); 1.1 public void setHgap(int hgap); 1.1 public void setVgap(int vgap); public String toString(); // Overrides Object }
java.awt.FileDialog (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_23.htm [20/12/2001 11:00:46]
java.awt.Font (JDK 1.0)
[Chapter 20] 20.13 java.awt.event.FocusListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.13 java.awt.event.FocusListener (JDK 1.1) This interface defines the methods that an object must implement to "listen" for focus events on AWT components. When a FocusEvent occurs, an AWT component notifies its registered FocusListener objects by invoking one of their methods. An easy way to implement this interface is by subclassing the FocusAdapter class. public abstract interface FocusListener extends EventListener { // Public Instance Methods public abstract void focusGained(FocusEvent e); public abstract void focusLost(FocusEvent e); }
Implemented By: AWTEventMulticaster, FocusAdapter
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), Component.addFocusListener(), Component.removeFocusListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
java.awt.event.FocusEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_13.htm [20/12/2001 11:00:46]
java.awt.event.InputEvent (JDK 1.1)
[Chapter 18] 18.25 java.awt.FontMetrics (JDK 1.0)
Chapter 18 The java.awt Package
18.25 java.awt.FontMetrics (JDK 1.0) This class represents font metrics for a specified Font. The methods allow you to determine the overall metrics for the font (ascent, descent, etc.), and also to compute the width of strings that are to be displayed in a particular font. You can obtain a FontMetrics object for a font with the getFontMetrics() method of Component or Toolkit. public abstract class FontMetrics extends Object implements Serializable { // Protected Constructor protected FontMetrics(Font font); // Protected Instance Variables protected Font font; // Public Instance Methods public int bytesWidth(byte[] data, int off, int len); public int charWidth(int ch); public int charWidth(char ch); public int charsWidth(char[] data, int off, int len); public int getAscent(); public int getDescent(); public Font getFont(); public int getHeight(); public int getLeading(); public int getMaxAdvance(); public int getMaxAscent(); # public int getMaxDecent(); public int getMaxDescent(); public int[] getWidths(); public int stringWidth(String str); public String toString(); // Overrides Object }
Returned By: Component.getFontMetrics(), ComponentPeer.getFontMetrics(), Graphics.getFontMetrics(), Toolkit.getFontMetrics()
http://localhost/java/javaref/javanut/ch18_25.htm (1 of 2) [20/12/2001 11:00:47]
[Chapter 18] 18.25 java.awt.FontMetrics (JDK 1.0)
java.awt.Font (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_25.htm (2 of 2) [20/12/2001 11:00:47]
java.awt.Frame (JDK 1.0)
[Chapter 18] 18.24 java.awt.Font (JDK 1.0)
Chapter 18 The java.awt Package
18.24 java.awt.Font (JDK 1.0) This class represents a font in a platform-independent way. The constructor accepts a font name, style, and point size. In Java 1.0, supported font names are: "TimesRoman," "Helvetica," "Courier," "Dialog," and "DialogInput." In Java 1.1, "Serif," "SansSerif," and "Monospaced" should be used in preference to the first three names. The style may be one of the constants PLAIN, BOLD, or ITALIC, or the sum BOLD+ITALIC. The class method getFont() looks up the specified name in the system properties list and returns the font specified as the value of that property. It takes an optional Font default to use if the named font property is not found. This allows user customizability. Use the FontMetrics class if you need to know how tall a font is or how wide a string drawn using that font will be. public class Font extends Object implements Serializable { // Public Constructor public Font(String name, int style, int size); // Constants public static final int BOLD; public static final int ITALIC; public static final int PLAIN; // Protected Instance Variables protected String name; protected int size; protected int style; // Class Methods 1.1 public static Font decode(String str); public static Font getFont(String nm); public static Font getFont(String nm, Font font); // Public Instance Methods public boolean equals(Object obj); // Overrides Object public String getFamily(); public String getName(); 1.1 public FontPeer getPeer(); http://localhost/java/javaref/javanut/ch18_24.htm (1 of 2) [20/12/2001 11:00:47]
[Chapter 18] 18.24 java.awt.Font (JDK 1.0)
public public public public public public public
int getSize(); int getStyle(); int hashCode(); // Overrides Object boolean isBold(); boolean isItalic(); boolean isPlain(); String toString(); // Overrides Object
}
Passed To: Component.getFontMetrics(), Component.setFont(), ComponentPeer.getFontMetrics(), ComponentPeer.setFont(), Font.getFont(), FontMetrics(), Graphics.getFontMetrics(), Graphics.setFont(), MenuComponent.setFont(), Toolkit.getFontMetrics()
Returned By: Component.getFont(), Font.decode(), Font.getFont(), FontMetrics.getFont(), Graphics.getFont(), MenuComponent.getFont(), MenuContainer.getFont()
Type Of: FontMetrics.font
java.awt.FlowLayout (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_24.htm (2 of 2) [20/12/2001 11:00:47]
java.awt.FontMetrics (JDK 1.0)
[Chapter 22] 22.10 java.awt.peer.FontPeer (JDK 1.1)
Chapter 22 The java.awt.peer Package
22.10 java.awt.peer.FontPeer (JDK 1.1) public interface FontPeer { }
Returned By: Font.getPeer(), Toolkit.getFontPeer()
java.awt.peer.FileDialogPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_10.htm [20/12/2001 11:00:48]
java.awt.peer.FramePeer (JDK 1.0)
[Chapter 18] 18.42 java.awt.MenuComponent (JDK 1.0)
Chapter 18 The java.awt Package
18.42 java.awt.MenuComponent (JDK 1.0) This class is the superclass of all menu-related classes: You never need to instantiate a MenuComponent directly. setFont() specifies the font to be used for all text within the menu component. public abstract class MenuComponent extends Object implements Serializable { // Default Constructor: public MenuComponent() // Public Instance Methods 1.1 public final void dispatchEvent(AWTEvent e); public Font getFont(); 1.1 public String getName(); public MenuContainer getParent(); # public MenuComponentPeer getPeer(); public boolean postEvent(Event evt); public void removeNotify(); public void setFont(Font f); 1.1 public void setName(String name); public String toString(); // Overrides Object // Protected Instance Methods protected String paramString(); 1.1 protected void processEvent(AWTEvent e); }
Extended By: MenuBar, MenuItem
Passed To: Component.remove(), Frame.remove(), Menu.remove(), MenuBar.remove(), MenuContainer.remove()
java.awt.MenuBar (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_42.htm [20/12/2001 11:00:48]
java.awt.MenuContainer (JDK 1.0)
[Chapter 29] 29.12 java.text.Format (JDK 1.1)
Chapter 29 The java.text Package
29.12 java.text.Format (JDK 1.1) This abstract class is the base class for all number, date, and string formatting classes in the java.text package. It defines two abstract methods that are implemented by subclasses. format() converts an object to a string using the formatting rules encapsulated by the Format subclass and optionally appends the resulting string to an existing StringBuffer. parseObject() performs the reverse operation--it parses a formatted string and returns the corresponding object. Status information for these two operations is returned in FieldPosition and ParsePosition objects. The non-abstract methods of this class are simple shortcuts that rely on implementations of the abstract methods. See ChoiceFormat, DateFormat, MessageFormat, and NumberFormat. public abstract class Format extends Object implements Serializable, Cloneable { // Default Constructor: public Format() // Public Instance Methods public Object clone(); // Overrides Object public final String format(Object obj); public abstract StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos); public abstract Object parseObject(String source, ParsePosition status); public Object parseObject(String source) throws ParseException; }
Extended By: DateFormat, MessageFormat, NumberFormat
Passed To: MessageFormat.setFormat(), MessageFormat.setFormats()
Returned By: MessageFormat.getFormats()
java.text.FieldPosition (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_12.htm [20/12/2001 11:00:48]
java.text.MessageFormat (JDK 1.1)
[Chapter 11] 11.6 Formatted Messages
Chapter 11 Internationalization
11.6 Formatted Messages We've seen that in order to internationalize programs, you must place all user-visible messages into resource bundles. This is straightforward when the text to be localized consists of simple labels like those on buttons and menu items. It is trickier, however, with messages that consist partially of static text and partially of dynamic values. For example, a compiler might have to display a message like "Error at line 5 of file 'hello.java'," in which the line number and filename are dynamic and locale-independent, while the rest of the message is static and needs to be localized. The MessageFormat class of the java.text package helps tremendously with these types of messages. To use it, you store only the static parts of a message in the ResourceBundle and include special characters that indicate where the dynamic parts of the message are to be placed. For example, one resource bundle might contain the message: "Error at line {0} of file {1}." And another resource bundle might contain a "translation" that looks like this: "Erreur: {1}: {0}." To use such a localized message, you create a MessageFormat object from the static part of the message, and then call its format() method, passing in an array of the values to be substituted. In this case, the array would contain an Integer object that specifies the line number and a String object that specifies the filename. The MessageFormat class knows about other Format classes defined in java.text. It creates and uses NumberFormat objects to format numbers and DateFormat objects to format dates and times. In addition, you can design messages that create ChoiceFormat objects to convert from numbers to strings--this is useful when working with enumerated types such as numbers that correspond to month names, or when you need to use the singular or plural form of a word based on the value of some number. Example 11.6 demonstrates this kind of MessageFormat usage. It is a convenience class with a single static method for the localized display of exception and error messages. When invoked, the code attempts to load a ResourceBundle with the basename "Errors." If found, it looks up a message resource using the class name of the exception object that was passed. If such a resource is found, it is used to display the error message. An array of five values is passed to the format() method. The localized error message can include any or all of these arguments. The LocalizedError.display() method defined in this example was used in Example 11.1 at the beginning of this chapter. Example 11.7 shows the default Errors.properties resource bundle used in conjunction with that example. Error message display for the program is nicely internationalized. Porting the program's error message to a new locale is simply a matter of translating (localizing) the Errors.properties file. Example 11.6: Internationalizing Error Message Display with MessageFormat import java.text.*; import java.io.*; import java.util.*; /**
http://localhost/java/javaref/javanut/ch11_06.htm (1 of 4) [20/12/2001 11:00:49]
[Chapter 11] 11.6 Formatted Messages
* A convenience class that can display a localized exception message * depending on the class of the exception. It uses a MessageFormat, * and passes five arguments that the localized message may include: * {0}: the message included in the exception or error. * {1}: the full class name of the exception or error. * {2}: a guess at what file the exception was caused by. * {3}: a line number in that file. * {4}: the current date and time. * Messages are looked up in a ResourceBundle with the basename * "Errors," using the full class name of the exception object as * the resource name. If no resource is found for a given exception * class, the superclasses are checked. */ public class LocalizedError { public static void display(Throwable error) { ResourceBundle bundle; // Try to get the resource bundle. // If none, print the error in a non-localized way. try { bundle = ResourceBundle.getBundle("Errors"); } catch (MissingResourceException e) { error.printStackTrace(System.err); return; } // Look up a localized message resource in that bundle, using the // classname of the error (or its superclasses) as the resource name. // If no resource was found, display the error without localization. String message = null; Class c = error.getClass(); while((message == null) && (c != Object.class)) { try { message = bundle.getString(c.getName()); } catch (MissingResourceException e) { c = c.getSuperclass(); } } if (message == null) { error.printStackTrace(System.err); return; } // Try to figure out the filename and line number of the // exception. Output the error's stack trace into a string, and // use the heuristic that the first line number that appears in // the stack trace is after the first or second colon. We assume that // this stack frame is the first one the programmer has any control // over, and so report it as the location of the exception. String filename = ""; int linenum = 0; try { StringWriter sw = new StringWriter(); // Output stream into a string. PrintWriter out = new PrintWriter(sw); // PrintWriter wrapper. error.printStackTrace(out); // Print stacktrace. String trace = sw.toString(); // Get it as a string. int pos = trace.indexOf(':'); // Look for first colon. if (error.getMessage() != null) // If the error has a message pos = trace.indexOf(':', pos+1); // look for second colon. int pos2 = trace.indexOf(')', pos); // Look for end of line number. linenum = Integer.parseInt(trace.substring(pos+1,pos2)); // Get linenum.
http://localhost/java/javaref/javanut/ch11_06.htm (2 of 4) [20/12/2001 11:00:49]
[Chapter 11] 11.6 Formatted Messages
pos2 = trace.lastIndexOf('(', pos); // Back to start of filename. filename = trace.substring(pos2+1, pos); // Get filename. } catch (Exception e) { ; } // Ignore exceptions. // Set up an array of arguments to use with the message. String errmsg = error.getMessage(); Object[] args = { ((errmsg!= null)?errmsg:""), error.getClass().getName(), filename, new Integer(linenum), new Date() }; // Finally, display the localized error message, using // MessageFormat.format() to substitute the arguments into the message. System.out.println(MessageFormat.format(message, args)); } } Example 11.7 shows the resource bundle properties file used to localize the set of possible error messages that could be thrown by the ConvertEncoding class shown at the beginning of this chapter. With a resource bundle like this, ConvertEncoding produces error messages like the following: Error: Specified encoding not supported Error occurred at line 46 of file "ConvertEncoding.java" at 7:55:28 PM on 08-Apr-97 Example 11.7: A ResourceBundle Properties File Containing Localized Error Messages # # This is the file Errors.properties. # One property for each class of exceptions that our program might # report. Note the use of backslashes to continue long lines onto the # next. Also note the use of \n and \t for newlines and tabs. # java.io.FileNotFoundException: \ Error: File "{0}" not found\n\t\ Error occurred at line {3} of file "{2}"\n\tat {4} java.io.UnsupportedEncodingException: \ Error: Specified encoding not supported\n\t\ Error occurred at line {3} of file "{2}"\n\tat {4,time} on {4,date} java.io.CharConversionException:\ Error: Character conversion failure. Input data is not in specified format. # A generic resource. Display a message for any error or exception that # is not handled by a more specific resource. java.lang.Throwable:\ Error: {1}: {0}\n\t\ Error occurred at line {3} of file "{2}"\n\t{4,time,long} {4,date,long}
Localizing User-Visible Messages
http://localhost/java/javaref/javanut/ch11_06.htm (3 of 4) [20/12/2001 11:00:49]
Reflection
[Chapter 11] 11.6 Formatted Messages
http://localhost/java/javaref/javanut/ch11_06.htm (4 of 4) [20/12/2001 11:00:49]
[Chapter 29] 29.14 java.text.NumberFormat (JDK 1.1)
Chapter 29 The java.text Package
29.14 java.text.NumberFormat (JDK 1.1) This class formats and parses numbers in a locale-specific way. As an abstract class, it cannot be instantiated directly, but it provides a number of static methods that return instances of a concrete subclass which you can use for formatting. The getInstance() method returns a NumberFormat object suitable for normal formatting of numbers in either the default locale or in a specified locale. getCurrencyInstance() and getPercentInstance() return NumberFormat objects for formatting numbers that represent monetary amounts and percentages in either the default locale or in a specified locale. getAvailableLocales() returns an array of locales for which NumberFormat objects are available. Once you have created a suitable NumberFormat object, you may customize its locale-independent behavior with setMaximumFractionDigits(), setGroupingUsed() and similar set methods. In order to customize the locale-dependent behavior, you can use instanceof to test if the NumberFormat object is an instance of DecimalFormat, and if so, cast it to that type. The DecimalFormat class provides complete control over number formatting. Note, however, that a NumberFormat customized in this way may no longer be appropriate for the desired locale. After creating and customizing a NumberFormat object, you can use the various format() methods to convert numbers to strings or string buffers, and you can use the parse() or parseObject() methods to convert strings to numbers. The constants defined by this class are intended to be used by the FieldPosition object. The NumberFormat class in not intended for the display of very large or very small numbers that require exponential notation, and it may not gracefully handle infinite or NaN (not-a-number) values. public abstract class NumberFormat extends Format implements Cloneable { // Default Constructor: public NumberFormat() // Constants public static final int FRACTION_FIELD; public static final int INTEGER_FIELD; // Class Methods public static Locale[] getAvailableLocales(); public static final NumberFormat getCurrencyInstance(); public static NumberFormat getCurrencyInstance(Locale inLocale); public static final NumberFormat getInstance(); public static NumberFormat getInstance(Locale inLocale); public static final NumberFormat getNumberInstance(); public static NumberFormat getNumberInstance(Locale inLocale); public static final NumberFormat getPercentInstance(); public static NumberFormat getPercentInstance(Locale inLocale); // Public Instance Methods public Object clone(); // Overrides Format public boolean equals(Object obj); // Overrides Object public final StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos); // Defines Format public final String format(double number);
http://localhost/java/javaref/javanut/ch29_14.htm (1 of 2) [20/12/2001 11:00:49]
[Chapter 29] 29.14 java.text.NumberFormat (JDK 1.1)
public final String format(long number); public abstract StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos); public abstract StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos); public int getMaximumFractionDigits(); public int getMaximumIntegerDigits(); public int getMinimumFractionDigits(); public int getMinimumIntegerDigits(); public int hashCode(); // Overrides Object public boolean isGroupingUsed(); public boolean isParseIntegerOnly(); public abstract Number parse(String text, ParsePosition parsePosition); public Number parse(String text) throws ParseException; public final Object parseObject(String source, ParsePosition parsePosition); // Defines Format public void setGroupingUsed(boolean newValue); public void setMaximumFractionDigits(int newValue); public void setMaximumIntegerDigits(int newValue); public void setMinimumFractionDigits(int newValue); public void setMinimumIntegerDigits(int newValue); public void setParseIntegerOnly(boolean value); }
Hierarchy: Object->Format(Serializable, Cloneable)->NumberFormat(Cloneable)
Extended By: ChoiceFormat, DecimalFormat
Passed To: DateFormat.setNumberFormat()
Returned By: DateFormat.getNumberFormat(), NumberFormat.getCurrencyInstance(), NumberFormat.getInstance(), NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()
Type Of: DateFormat.numberFormat
java.text.MessageFormat (JDK 1.1)
java.text.ParseException (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_14.htm (2 of 2) [20/12/2001 11:00:49]
[Chapter 22] 22.11 java.awt.peer.FramePeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.11 java.awt.peer.FramePeer (JDK 1.0) public abstract interface FramePeer extends WindowPeer { // Public Instance Methods public abstract void setIconImage(Image im); public abstract void setMenuBar(MenuBar mb); public abstract void setResizable(boolean resizeable); public abstract void setTitle(String title); }
Hierarchy: (FramePeer(WindowPeer(ContainerPeer(ComponentPeer))))
Returned By: Toolkit.createFrame()
java.awt.peer.FontPeer (JDK 1.1)
http://localhost/java/javaref/javanut/ch22_11.htm [20/12/2001 11:00:49]
java.awt.peer.LabelPeer (JDK 1.0)
[Chapter 25] 25.48 java.lang.OutOfMemoryError (JDK 1.0)
Chapter 25 The java.lang Package
25.48 java.lang.OutOfMemoryError (JDK 1.0) Signals that the interpreter has run out of memory (and that garbage collection is unable to free any memory). public class OutOfMemoryError extends VirtualMachineError { // Public Constructors public OutOfMemoryError(); public OutOfMemoryError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->VirtualMachineError->OutOfMemoryError
java.lang.Object (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_48.htm [20/12/2001 11:00:50]
java.lang.Process (JDK 1.0)
[Chapter 28] 28.10 java.net.InetAddress (JDK 1.0)
Chapter 28 The java.net Package
28.10 java.net.InetAddress (JDK 1.0) This class represents an Internet address, and is used when creating DatagramPacket or Socket objects. The class does not have a public constructor function, but instead supports three static methods which return one or more instances of InetAddress. getLocalHost() returns an InetAddress for the local host. getByName() returns the InetAddress of a host specified by name. getAllByName() returns an array of InetAddress that represents all of the available addresses for a host specified by name. Instance methods are getHostName(), which returns the hostname of an InetAddress, and getAddress(), which returns the Internet IP address as an array of bytes, with the highest-order byte as the first element of the array. public final class InetAddress extends Object implements Serializable { // No Constructor // Class Methods public static InetAddress[] getAllByName(String host) throws UnknownHostException; public static InetAddress getByName(String host) throws UnknownHostException; public static InetAddress getLocalHost() throws UnknownHostException; // Public Instance Methods public boolean equals(Object obj); // Overrides Object public byte[] getAddress(); public String getHostAddress(); public String getHostName(); public int hashCode(); // Overrides Object 1.1public boolean isMulticastAddress(); public String toString(); // Overrides Object }
Passed To: DatagramPacket(), DatagramPacket.setAddress(), DatagramSocket(), DatagramSocketImpl.bind(), DatagramSocketImpl.join(), DatagramSocketImpl.leave(), DatagramSocketImpl.peek(), MulticastSocket.joinGroup(), MulticastSocket.leaveGroup(), MulticastSocket.setInterface(), SecurityManager.checkMulticast(), ServerSocket(), Socket(), SocketImpl.bind(), SocketImpl.connect()
Returned By: DatagramPacket.getAddress(), DatagramSocket.getLocalAddress(), InetAddress.getAllByName(), InetAddress.getByName(), InetAddress.getLocalHost(), MulticastSocket.getInterface(), ServerSocket.getInetAddress(), Socket.getInetAddress(), Socket.getLocalAddress(), SocketImpl.getInetAddress()
http://localhost/java/javaref/javanut/ch28_10.htm (1 of 2) [20/12/2001 11:00:50]
[Chapter 28] 28.10 java.net.InetAddress (JDK 1.0)
Type Of: SocketImpl.address
java.net.HttpURLConnection (JDK 1.1)
java.net.MalformedURLException (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_10.htm (2 of 2) [20/12/2001 11:00:50]
[Chapter 30] 30.24 java.util.TimeZone (JDK 1.1)
Chapter 30 The java.util Package
30.24 java.util.TimeZone (JDK 1.1) The TimeZone class represents a time zone; it is used with the Calendar and DateFormat classes. As an abstract class, TimeZone cannot be directly instantiated. Instead, you should call the static getDefault() method to obtain a TimeZone object that represents the time zone inherited from the host operating system. Or, you should call getTimeZone() (also static), passing the name of the desired zone. You can obtain a list of the supported time zone names by calling the static getAvailableIDs() method. Once you have a TimeZone object, you can call inDaylightTime() to determine whether, for a given Date, daylight savings time is in effect for that time zone. Call getID() to obtain the name of the time zone, and call getOffset() for a given date to determine the number of milliseconds to add to GMT to convert to the time zone. public abstract class TimeZone extends Object implements Serializable, Cloneable { // Default Constructor: public TimeZone() // Class Methods public static synchronized String[] getAvailableIDs(int rawOffset); public static synchronized String[] getAvailableIDs(); public static synchronized TimeZone getDefault(); public static synchronized TimeZone getTimeZone(String ID); public static synchronized void setDefault(TimeZone zone); // Public Instance Methods public Object clone(); // Overrides Object public String getID(); public abstract int getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds); public abstract int getRawOffset(); public abstract boolean inDaylightTime(Date date); public void setID(String ID); public abstract void setRawOffset(int offsetMillis); public abstract boolean useDaylightTime(); }
Extended By: SimpleTimeZone
Passed To: Calendar(), Calendar.getInstance(), Calendar.setTimeZone(), DateFormat.setTimeZone(), GregorianCalendar(), TimeZone.setDefault()
http://localhost/java/javaref/javanut/ch30_24.htm (1 of 2) [20/12/2001 11:00:50]
[Chapter 30] 30.24 java.util.TimeZone (JDK 1.1)
Returned By: Calendar.getTimeZone(), DateFormat.getTimeZone(), TimeZone.getDefault(), TimeZone.getTimeZone()
java.util.StringTokenizer (JDK 1.0)
java.util.TooManyListenersException (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_24.htm (2 of 2) [20/12/2001 11:00:50]
[Chapter 30] 30.12 java.util.Locale (JDK 1.1)
Chapter 30 The java.util Package
30.12 java.util.Locale (JDK 1.1) The Locale class represents a locale: a political, geographical, or cultural region that typically has a distinct language and distinct customs and conventions for such things as formatting dates, times, and numbers. The Locale class defines a number of constants that represent commonly used locales. Locale also defines a static getDefault() method that returns the default Locale object, which represents a locale value inherited from the host system. Furthermore, many locale-sensitive classes, such as DateFormat, provide getAvailableLocales() methods that return a list of supported Locale objects. If none of these methods for obtaining a Locale object is suitable, you can also explicitly create your own Locale object. To do this, you must specify a language code, a country code, and an optional variant string. The Locale class does not implement any internationalization behavior itself; it merely serves as a locale identifier for those classes that can localize their behavior. Given a Locale object, you can invoke the various getDisplay methods to obtain a description of the locale suitable for display to a user. Note that these methods may themselves take a Locale argument so that the names of languages and countries can be localized as appropriate. public final class Locale extends Object implements Cloneable, Serializable { // Public Constructors public Locale(String language, String country, String variant); public Locale(String language, String country); // Constants public static final Locale CANADA; public static final Locale CANADA_FRENCH; public static final Locale CHINA; public static final Locale CHINESE; public static final Locale ENGLISH; public static final Locale FRANCE; public static final Locale FRENCH; public static final Locale GERMAN; public static final Locale GERMANY; public static final Locale ITALIAN; public static final Locale ITALY; public static final Locale JAPAN; public static final Locale JAPANESE; public static final Locale KOREA; public static final Locale KOREAN; public static final Locale PRC;
http://localhost/java/javaref/javanut/ch30_12.htm (1 of 3) [20/12/2001 11:00:50]
[Chapter 30] 30.12 java.util.Locale (JDK 1.1)
public static final Locale SIMPLIFIED_CHINESE; public static final Locale TAIWAN; public static final Locale TRADITIONAL_CHINESE; public static final Locale UK; public static final Locale US; // Class Methods public static synchronized Locale getDefault(); public static synchronized void setDefault(Locale newLocale); // Public Instance Methods public Object clone(); // Overrides Object public boolean equals(Object obj); // Overrides Object public String getCountry(); public final String getDisplayCountry(); public String getDisplayCountry(Locale inLocale); public final String getDisplayLanguage(); public String getDisplayLanguage(Locale inLocale); public final String getDisplayName(); public String getDisplayName(Locale inLocale); public final String getDisplayVariant(); public String getDisplayVariant(Locale inLocale); public String getISO3Country() throws MissingResourceException; public String getISO3Language() throws MissingResourceException; public String getLanguage(); public String getVariant(); public synchronized int hashCode(); // Overrides Object public final String toString(); // Overrides Object }
Passed To: BreakIterator.getCharacterInstance(), BreakIterator.getLineInstance(), BreakIterator.getSentenceInstance(), BreakIterator.getWordInstance(), Calendar(), Calendar.getInstance(), Collator.getInstance(), Component.setLocale(), DateFormat.getDateInstance(), DateFormat.getDateTimeInstance(), DateFormat.getTimeInstance(), DateFormatSymbols(), DecimalFormatSymbols(), GregorianCalendar(), Locale.getDisplayCountry(), Locale.getDisplayLanguage(), Locale.getDisplayName(), Locale.getDisplayVariant(), Locale.setDefault(), MessageFormat.setLocale(), NumberFormat.getCurrencyInstance(), NumberFormat.getInstance(), NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance(), ResourceBundle.getBundle(), SimpleDateFormat(), String.toLowerCase(), String.toUpperCase()
Returned By: Applet.getLocale(), BreakIterator.getAvailableLocales(), Calendar.getAvailableLocales(), Collator.getAvailableLocales(), Component.getLocale(), DateFormat.getAvailableLocales(), Locale.getDefault(), MessageFormat.getLocale(), NumberFormat.getAvailableLocales(), Window.getLocale()
java.util.ListResourceBundle (JDK 1.1)
java.util.MissingResourceException (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_12.htm (2 of 3) [20/12/2001 11:00:50]
[Chapter 30] 30.12 java.util.Locale (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_12.htm (3 of 3) [20/12/2001 11:00:50]
[Chapter 23] 23.2 java.beans.BeanInfo (JDK 1.1)
Chapter 23 The java.beans Package
23.2 java.beans.BeanInfo (JDK 1.1) The BeanInfo interface defines the methods that a class must implement in order to export information about a Java bean. The Introspector class knows how to obtain all the basic information required about a bean. A bean that wants to be more "programmer-friendly" may provide a class that implements this interface, however, in order to provide additional information about itself (such as an icon and description strings for each of its properties, events, and methods). Note that a bean developer defines a class that implements the methods of this interface. Typically only builder applications and similar tools actually invoke the methods defined here. The methods getBeanDescriptor(), getEventSetDescriptors(), getPropertyDescriptors(), and getMethodDescriptors() should return appropriate descriptor objects for the bean, or null, if the bean does not provide explicit bean, event set, property, or method descriptor objects. The getDefaultEventIndex() and getDefaultPropertyIndex() methods return values that specify the "default" event and property--i.e., that are most likely to be of interest to a programmer using the bean. These methods should return -1 if there are no defaults. The getIcon() method should return an image object suitable for representing the bean in a palette or menu of available beans. The argument passed to this method is one of the four constants defined by the class; it specifies the type and size of icon requested. If the requested icon cannot be provided, getIcon() should return null. A BeanInfo class is allowed to return null or -1 if it cannot provide the requested information. In this case, the Introspector class provides basic values for the omitted information from its own introspection of the bean. See SimpleBeanInfo for a trivial implementation of this interface, suitable for convenient subclassing. public abstract interface BeanInfo { // Constants public static final int ICON_COLOR_16x16; public static final int ICON_COLOR_32x32; public static final int ICON_MONO_16x16; public static final int ICON_MONO_32x32; // Public Instance Methods public abstract BeanInfo[] getAdditionalBeanInfo(); public abstract BeanDescriptor getBeanDescriptor(); public abstract int getDefaultEventIndex(); public abstract int getDefaultPropertyIndex(); http://localhost/java/javaref/javanut/ch23_02.htm (1 of 2) [20/12/2001 11:00:51]
[Chapter 23] 23.2 java.beans.BeanInfo (JDK 1.1)
public public public public
abstract abstract abstract abstract
EventSetDescriptor[] getEventSetDescriptors(); Image getIcon(int iconKind); MethodDescriptor[] getMethodDescriptors(); PropertyDescriptor[] getPropertyDescriptors();
}
Implemented By: SimpleBeanInfo
Returned By: BeanInfo.getAdditionalBeanInfo(), Introspector.getBeanInfo(), SimpleBeanInfo.getAdditionalBeanInfo()
java.beans.BeanDescriptor (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_02.htm (2 of 2) [20/12/2001 11:00:51]
java.beans.Beans (JDK 1.1)
[Chapter 23] 23.9 java.beans.Introspector (JDK 1.1)
Chapter 23 The java.beans Package
23.9 java.beans.Introspector (JDK 1.1) The Introspector is a class that is never instantiated. Its static getBeanInfo() methods provide a way to obtain information about a Java bean, and are typically only invoked by application builders or similar tools. getBeanInfo() first looks for a BeanInfo class for the specified Java bean class. For a class named x, it looks for a BeanInfo class named xBeanInfo, first in the current package, and then in each of the packages in the BeanInfo search path. If no BeanInfo class is found, or if the BeanInfo class found does not provide complete information about the bean properties, events, and methods, getBeanInfo() "introspects" on the bean class by using the java.lang.reflect package to fill in the missing information. When explicit information is provided by a BeanInfo class, getBeanInfo() treats it as definitive. When determining information through introspection, however, it examines each of the bean's superclasses in turn, looking for a BeanInfo class at that level or using introspection. When calling getBeanInfo(), you may optionally specify a second class argument that specifies a superclass for which, and above which, getBeanInfo() does not introspect. public class Introspector extends Object { // No Constructor // Class Methods public static String decapitalize(String name); public static BeanInfo getBeanInfo(Class beanClass) throws IntrospectionException; public static BeanInfo getBeanInfo(Class beanClass, Class stopClass) throws IntrospectionException; public static String[] getBeanInfoSearchPath(); public static void setBeanInfoSearchPath(String[] path); }
java.beans.IntrospectionException (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_09.htm [20/12/2001 11:00:51]
java.beans.MethodDescriptor (JDK 1.1)
[Chapter 14] System Properties
Chapter 14
14. System Properties Contents: Standard System Properties Working with System Properties Java programs cannot read environment variables the way that native programs can. The reason is that environment variables are platform dependent. Similar mechanisms exist, however, that allow applications to read the value of a named resource. These resource values allow customization of an application's behavior based on site-specific parameters, such as the type of host, or based on user preferences. These named resource values are specified for applications in the "system properties" list. Applications can read these "system properties" with the System.getProperty() method, or can read the entire list of properties with System.getProperties(). System.getProperty() returns the property value as a string. Applications can also read properties in parsed form using methods that are based on System.getProperty(), such as Font.getFont(), Color.getColor(), Integer.getInteger(), and Boolean.getBoolean().
14.1 Standard System Properties When the Java interpreter starts, it inserts a number of standard properties into the system properties list. These properties, and the meaning of their values, are listed in Table 14.1. The table also specifies whether untrusted applets are allowed (at least by default) to read the value of these properties. For reasons of security, untrusted code is only allowed to read the values of properties to which it has explicitly been granted access. (Untrusted applets are not allowed to set the value of system properties, nor are they allowed to call System.getProperties() to obtain the entire list of properties.) Table 14.1: Standard System Properties Name java.version java.vendor java.vendor.url
Value Version of the Java interpreter Vendor-specific identifier string Vendor's URL
http://localhost/java/javaref/javanut/ch14_01.htm (1 of 2) [20/12/2001 11:00:51]
Applet Access yes yes yes
[Chapter 14] System Properties
java.class.version java.class.path java.home java.compiler os.name os.arch os.version
The version of the Java API The classpath value The directory Java is installed in The JIT compiler to use, if any (Java 1.1) The name of the operating system The host hardware architecture Version of the host operating system
yes no no no yes yes yes
file.separator
Platform-dependent file separator (e.g., / or #)
yes
path.separator
Platform-dependent path separator (e.g., : or ;)
yes
line.separator
Platform-dependent line separator (e.g., #n or #r#n) The username of the current user The home directory of the current user
yes
user.name user.home user.dir user.language user.region user.timezone file.encoding
The current working directory The 2-letter language code of the default locale (Java 1.1) The 2-letter country code of the default locale (Java 1.1) The default time zone (Java 1.1) The character encoding for the default locale (Java 1.1) The package that contains converters between local encodings and file.encoding.pkg Unicode (Java 1.1)
Java Documentation Comment Syntax
http://localhost/java/javaref/javanut/ch14_01.htm (2 of 2) [20/12/2001 11:00:51]
no no no no no no no no
Working with System Properties
[Chapter 30] 30.20 java.util.ResourceBundle (JDK 1.1)
Chapter 30 The java.util Package
30.20 java.util.ResourceBundle (JDK 1.1) This abstract class allows subclasses to define sets of localized resources which can then be dynamically loaded as needed by internationalized programs. Such resources may include user-visible text and images that appear in an application, and even more complex things such as Menu objects. Use getBundle() to load a ResourceBundle subclass that is appropriate for the default or the specified locale. Use getObject(), getString(), and getStringArray() to look up a named resource in a bundle. To define a bundle, provide implementations of handleGetObject() and getKeys(). It is often easier, however, to subclass ListResourceBundle, or to provide a property file that is used by PropertyResourceBundle. The name of any localized ResourceBundle class you define should include the locale language code, and, optionally, the locale country code. public abstract class ResourceBundle extends Object { // Default Constructor: public ResourceBundle() // Protected Instance Variables protected ResourceBundle parent; // Class Methods public static final ResourceBundle getBundle(String baseName) throws MissingResourceException; public static final ResourceBundle getBundle(String baseName, Locale locale); // Public Instance Methods public abstract Enumeration getKeys(); public final Object getObject(String key) throws MissingResourceException; public final String getString(String key) throws MissingResourceException; public final String[] getStringArray(String key) throws MissingResourceException; // Protected Instance Methods protected abstract Object handleGetObject(String key) throws MissingResourceException; protected void setParent(ResourceBundle parent); }
Extended By: ListResourceBundle, PropertyResourceBundle
http://localhost/java/javaref/javanut/ch30_20.htm (1 of 2) [20/12/2001 11:00:52]
[Chapter 30] 30.20 java.util.ResourceBundle (JDK 1.1)
Passed To: ResourceBundle.setParent()
Returned By: ResourceBundle.getBundle()
Type Of: ResourceBundle.parent
java.util.Random (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_20.htm (2 of 2) [20/12/2001 11:00:52]
java.util.SimpleTimeZone (JDK 1.1)
[Chapter 30] 30.13 java.util.MissingResourceException (JDK 1.1)
Chapter 30 The java.util Package
30.13 java.util.MissingResourceException (JDK 1.1) This exception signals that no ResourceBundle could be located for the desired locale, or that a named resource could not be found within a given ResourceBundle. getClassName() returns the name of the ResourceBundle class in question, and getKey() returns the name of the resource that could not be located. public class MissingResourceException extends RuntimeException { // Public Constructor public MissingResourceException(String s, String className, String key); // Public Instance Methods public String getClassName(); public String getKey(); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->MissingResourceException
Thrown By: Locale.getISO3Country(), Locale.getISO3Language(), ResourceBundle.getBundle(), ResourceBundle.getObject(), ResourceBundle.getString(), ResourceBundle.getStringArray(), ResourceBundle.handleGetObject()
java.util.Locale (JDK 1.1)
java.util.NoSuchElementException (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_13.htm [20/12/2001 11:00:52]
[Chapter 28] 28.22 java.net.URL (JDK 1.0)
Chapter 28 The java.net Package
28.22 java.net.URL (JDK 1.0) This class represents a URL (a Uniform Resource Locator) and allows the data referred to by the URL to be downloaded. A URL may be specified as a single string or with separate protocol, host, port, and file specifications. Relative URLs may also be specified with a String and the URL object that it is relative to. getFile(), getHost(), getPort(), getProtocol(), and getRef() return the various portions of the URL specified by a URL object. sameFile() determines whether a URL object refers to the same file as this one. The data or object referred to by a URL may be downloaded from the Internet in three ways: through a URLConnection created with openConnection(), through an InputStream created by openStream(), or through getContent(), which returns the URL contents directly, if an appropriate ContentHandler can be found. public final class URL extends Object implements Serializable { // Public Constructors public URL(String protocol, String host, int port, String file) throws MalformedURLException; public URL(String protocol, String host, String file) throws MalformedURLException; public URL(String spec) throws MalformedURLException; public URL(URL context, String spec) throws MalformedURLException; // Class Methods public static synchronized void setURLStreamHandlerFactory(URLStreamHandlerFactory fac); // Public Instance Methods public boolean equals(Object obj); // Overrides Object public final Object getContent() throws IOException; public String getFile(); public String getHost(); public int getPort(); public String getProtocol(); public String getRef(); public int hashCode(); // Overrides Object public URLConnection openConnection() throws IOException; public final InputStream openStream() throws IOException; public boolean sameFile(URL other); public String toExternalForm(); public String toString(); // Overrides Object // Protected Instance Methods protected void set(String protocol, String host, int port, String file, String ref); }
http://localhost/java/javaref/javanut/ch28_22.htm (1 of 2) [20/12/2001 11:00:52]
[Chapter 28] 28.22 java.net.URL (JDK 1.0)
Passed To: Applet.getAudioClip(), Applet.getImage(), Applet.play(), AppletContext.getAudioClip(), AppletContext.getImage(), AppletContext.showDocument(), HttpURLConnection(), Toolkit.getImage(), URL(), URL.sameFile(), URLConnection(), URLStreamHandler.openConnection(), URLStreamHandler.parseURL(), URLStreamHandler.setURL(), URLStreamHandler.toExternalForm()
Returned By: Applet.getCodeBase(), Applet.getDocumentBase(), AppletStub.getCodeBase(), AppletStub.getDocumentBase(), Class.getResource(), ClassLoader.getResource(), ClassLoader.getSystemResource(), URLConnection.getURL()
Type Of: URLConnection.url
java.net.UnknownServiceException (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_22.htm (2 of 2) [20/12/2001 11:00:52]
java.net.URLConnection (JDK 1.0)
[Chapter 30] 30.11 java.util.ListResourceBundle (JDK 1.1)
Chapter 30 The java.util Package
30.11 java.util.ListResourceBundle (JDK 1.1) This abstract class provides a simple way to define a ResourceBundle. You may find it easier to subclass ListResourceBundle than to subclass ResourceBundle directly. ListResourceBundle provides implementations for the abstract handleGetObject() and getKeys() methods defined by ResourceBundle, and it adds its own abstract getContents() method that your subclasses must override. getContents() returns an Object[][]--an array of arrays of objects. This array can have any number of elements. Each element of this array must itself be an array with two elements: the first element of each subarray should be a String that specifies the name of a resource, and the corresponding second element should be the value of that resource--this value can be an Object of any desired type. See also ResourceBundle and PropertyResourceBundle. public abstract class ListResourceBundle extends ResourceBundle { // Default Constructor: public ListResourceBundle() // Public Instance Methods public Enumeration getKeys(); // Defines ResourceBundle public final Object handleGetObject(String key); // Defines ResourceBundle // Protected Instance Methods protected abstract Object[][] getContents(); }
Hierarchy: Object->ResourceBundle->ListResourceBundle
java.util.Hashtable (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_11.htm [20/12/2001 11:00:53]
java.util.Locale (JDK 1.1)
[Chapter 26] 26.5 java.lang.reflect.Member (JDK 1.1)
Chapter 26 The java.lang.reflect Package
26.5 java.lang.reflect.Member (JDK 1.1) This interface defines the methods shared by all members (fields, methods, and constructors) of a class. getName() returns the name of the member, getModifiers() returns its modifiers, and getDeclaringClass() returns the Class object that represents the class of which the member is a part. public abstract interface Member { // Constants public static final int DECLARED; public static final int PUBLIC; // Public Instance Methods public abstract Class getDeclaringClass(); public abstract int getModifiers(); public abstract String getName(); }
Implemented By: Constructor, Field, Method
java.lang.reflect.InvocationTargetException (JDK 1.1)
http://localhost/java/javaref/javanut/ch26_05.htm [20/12/2001 11:00:53]
java.lang.reflect.Method (JDK 1.1)
[Chapter 18] 18.60 java.awt.Toolkit (JDK 1.0)
Chapter 18 The java.awt Package
18.60 java.awt.Toolkit (JDK 1.0) This abstract class defines methods that, when implemented, create platform-dependent "peers" for each of the java.awt Component types. Java supports its platform-independent GUI interface by implementing a subclass of Toolkit for each platform. Portable programs should never use these methods to create peers directly--they should use the Component classes themselves. A Toolkit object cannot be instantiated directly. Component.getToolkit() returns the Toolkit being used for a particular component. The Toolkit class defines a few methods that you can use directly: the static method getDefaultToolkit() returns the default Toolkit that is in use. getScreenSize() returns the screen size in pixels, and getScreenResolution() returns the resolution in dots-per-inch. getFontList() returns the names of supported fonts. sync() flushes all pending graphics output, which can be useful for animation. In Java 1.1, getPrintJob(), getSystemClipboard(), and getSystemEventQueue() are also of interest. public abstract class Toolkit extends Object { // Default Constructor: public Toolkit() // Class Methods public static synchronized Toolkit getDefaultToolkit(); 1.1 protected static Container getNativeContainer(Component c); 1.1 public static String getProperty(String key, String defaultValue); // Public Instance Methods 1.1 public abstract void beep(); public abstract int checkImage(Image image, int width, int height, ImageObserver observer); public abstract Image createImage(ImageProducer producer); 1.1 public Image createImage(byte[] imagedata); 1.1 public abstract Image createImage(byte[] imagedata, int imageoffset, int imagelength); public abstract ColorModel getColorModel(); public abstract String[] getFontList(); public abstract FontMetrics getFontMetrics(Font font); public abstract Image getImage(String filename); public abstract Image getImage(URL url); 1.1 public int getMenuShortcutKeyMask(); 1.1 public abstract PrintJob getPrintJob(Frame frame, String jobtitle, Properties props); public abstract int getScreenResolution(); public abstract Dimension getScreenSize(); 1.1 public abstract Clipboard getSystemClipboard(); 1.1 public final EventQueue getSystemEventQueue(); public abstract boolean prepareImage(Image image, int width, int height, ImageObserver observer); public abstract void sync(); // Protected Instance Methods
http://localhost/java/javaref/javanut/ch18_60.htm (1 of 2) [20/12/2001 11:00:53]
[Chapter 18] 18.60 java.awt.Toolkit (JDK 1.0)
protected abstract ButtonPeer createButton(Button target); protected abstract CanvasPeer createCanvas(Canvas target); protected abstract CheckboxPeer createCheckbox(Checkbox target); protected abstract CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target); protected abstract ChoicePeer createChoice(Choice target); 1.1 protected LightweightPeer createComponent(Component target); protected abstract DialogPeer createDialog(Dialog target); protected abstract FileDialogPeer createFileDialog(FileDialog target); protected abstract FramePeer createFrame(Frame target); protected abstract LabelPeer createLabel(Label target); protected abstract ListPeer createList(List target); protected abstract MenuPeer createMenu(Menu target); protected abstract MenuBarPeer createMenuBar(MenuBar target); protected abstract MenuItemPeer createMenuItem(MenuItem target); protected abstract PanelPeer createPanel(Panel target); 1.1 protected abstract PopupMenuPeer createPopupMenu(PopupMenu target); 1.1 protected abstract ScrollPanePeer createScrollPane(ScrollPane target); protected abstract ScrollbarPeer createScrollbar(Scrollbar target); protected abstract TextAreaPeer createTextArea(TextArea target); protected abstract TextFieldPeer createTextField(TextField target); protected abstract WindowPeer createWindow(Window target); 1.1 protected abstract FontPeer getFontPeer(String name, int style); 1.1 protected abstract EventQueue getSystemEventQueueImpl(); 1.1 protected void loadSystemColors(int[] systemColors); }
Returned By: Component.getToolkit(), ComponentPeer.getToolkit(), Toolkit.getDefaultToolkit(), Window.getToolkit()
java.awt.TextField (JDK 1.0)
java.awt.Window (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_60.htm (2 of 2) [20/12/2001 11:00:53]
[Chapter 24] 24.29 java.io.InputStreamReader (JDK 1.1)
Chapter 24 The java.io Package
24.29 java.io.InputStreamReader (JDK 1.1) This class is a character input stream that uses a byte input stream as its data source: it reads bytes from a specified InputStream and translates them into Unicode characters according to a particular platform- and locale-dependent character encoding. This is a very important internationalization feature in Java 1.1. When you create an InputStreamReader, you specify an InputStream from which the InputStreamReader is to read bytes, and you also optionally specify the name of the character encoding used by those bytes. If you do not specify an encoding name, the InputStreamReader uses the default encoding for the default locale, which is usually the correct thing to do. The InputStreamReader supports the standard Reader methods. It also has a getEncoding() method that returns the name of the encoding being used to convert bytes to characters. public class InputStreamReader extends Reader { // Public Constructors public InputStreamReader(InputStream in); public InputStreamReader(InputStream in, String enc) throws UnsupportedEncodingException; // Public Instance Methods public void close() throws IOException; // Defines Reader public String getEncoding(); public int read() throws IOException; // Overrides Reader public int read(char[] cbuf, int off, int len) throws IOException; Defines Reader public boolean ready() throws IOException; // Overrides Reader }
Hierarchy: Object->Reader->InputStreamReader
Extended By: FileReader
java.io.InputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_29.htm [20/12/2001 11:00:54]
java.io.InterruptedIOException (JDK 1.0)
//
[Chapter 24] 24.47 java.io.OutputStreamWriter (JDK 1.1)
Chapter 24 The java.io Package
24.47 java.io.OutputStreamWriter (JDK 1.1) This class is a character output stream that uses a byte output stream as the destination for its data: when characters are written to an OutputStreamWriter, it translates them into bytes according to a particular locale- and/or platform-specific character encoding, and writes those bytes to the specified OutputStream. This is a very important internationalization feature in Java 1.1. When you create an OutputStreamWriter, you specify the OutputStream to which it writes bytes, and you optionally specify the name of the character encoding that should be used to convert characters to bytes. If you do not specify an encoding name, the OutputStreamWriter uses the default encoding of the default locale, which is usually the correct thing to do. OutputStreamWriter supports the usual Writer methods. It also has a getEncoding() method which returns the name of the encoding being used to convert characters to bytes. public class OutputStreamWriter extends Writer { // Public Constructors public OutputStreamWriter(OutputStream out, String enc) throws UnsupportedEncodingException; public OutputStreamWriter(OutputStream out); // Public Instance Methods public void close() throws IOException; // Defines Writer public void flush() throws IOException; // Defines Writer public String getEncoding(); public void write(int c) throws IOException; // Overrides Writer public void write(char[] cbuf, int off, int len) throws IOException; // Defines Writer public void write(String str, int off, int len) throws IOException; // Overrides Writer }
Hierarchy: Object->Writer->OutputStreamWriter
Extended By: FileWriter
java.io.OutputStream (JDK 1.0)
java.io.PipedInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_47.htm (1 of 2) [20/12/2001 11:00:54]
[Chapter 24] 24.47 java.io.OutputStreamWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_47.htm (2 of 2) [20/12/2001 11:00:54]
[Chapter 26] 26.6 java.lang.reflect.Method (JDK 1.1)
Chapter 26 The java.lang.reflect Package
26.6 java.lang.reflect.Method (JDK 1.1) This class represents a method. Instances of Method are obtained by calling the getMethod() and related methods of java.lang.Class. Method implements the Member interface, so you can use the methods of that interface to obtain the method name, modifiers, and declaring class. In addition, getReturnType(), getParameterTypes(), and getExceptionTypes() also return important information about the represented method. Perhaps most important, the invoke() method allows the method represented by the Method object to be invoked with a specified array of argument values. If any of the arguments are of primitive types, they must be converted to their corresponding wrapper object types in order to be passed to invoke(). If the represented method is an instance method (i.e., if it is not static), the instance on which it should be invoked must also be passed to invoke(). The return value of the represented method is returned by invoke(). If the return value is a primitive value, it is first converted to the corresponding wrapper type. If the invoked method causes an exception, the Throwable object it throws is wrapped within the InvocationTargetException that is thrown by invoke(). public final class Method extends Object implements Member { // No Constructor // Public Instance Methods public boolean equals(Object obj); // Overrides Object public Class getDeclaringClass(); // From Member public Class[] getExceptionTypes(); public native int getModifiers(); // From Member public String getName(); // From Member public Class[] getParameterTypes(); public Class getReturnType(); public int hashCode(); // Overrides Object public native Object invoke(Object obj, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException; public String toString(); // Overrides Object }
Passed To: EventSetDescriptor(), IndexedPropertyDescriptor(), MethodDescriptor(), PropertyDescriptor()
http://localhost/java/javaref/javanut/ch26_06.htm (1 of 2) [20/12/2001 11:00:54]
[Chapter 26] 26.6 java.lang.reflect.Method (JDK 1.1)
Returned By: Class.getDeclaredMethod(), Class.getDeclaredMethods(), Class.getMethod(), Class.getMethods(), EventSetDescriptor.getAddListenerMethod(), EventSetDescriptor.getListenerMethods(), EventSetDescriptor.getRemoveListenerMethod(), IndexedPropertyDescriptor.getIndexedReadMethod(), IndexedPropertyDescriptor.getIndexedWriteMethod(), MethodDescriptor.getMethod(), PropertyDescriptor.getReadMethod(), PropertyDescriptor.getWriteMethod()
java.lang.reflect.Member (JDK 1.1)
http://localhost/java/javaref/javanut/ch26_06.htm (2 of 2) [20/12/2001 11:00:54]
java.lang.reflect.Modifier (JDK 1.1)
[Chapter 18] 18.32 java.awt.Image (JDK 1.0)
Chapter 18 The java.awt Package
18.32 java.awt.Image (JDK 1.0) This abstract class represents a displayable image in a platform-independent way. An Image object may not be instantiated directly through a constructor; it must be obtained through a call like Applet.getImage() or Component.createImage(). getSource() method returns the ImageProducer object that produces the image data. getGraphics() returns a Graphics object that can be used for drawing into offscreen images (but not images that are downloaded or generated by an ImageProducer). public abstract class Image extends Object { // Default Constructor: public Image() // Constants 1.1 public static final int SCALE_AREA_AVERAGING; 1.1 public static final int SCALE_DEFAULT; 1.1 public static final int SCALE_FAST; 1.1 public static final int SCALE_REPLICATE; 1.1 public static final int SCALE_SMOOTH; public static final Object UndefinedProperty; // Public Instance Methods public abstract void flush(); public abstract Graphics getGraphics(); public abstract int getHeight(ImageObserver observer); public abstract Object getProperty(String name, ImageObserver observer); 1.1 public Image getScaledInstance(int width, int height, int hints); public abstract ImageProducer getSource(); public abstract int getWidth(ImageObserver observer); }
Passed To: Component.checkImage(), Component.imageUpdate(), Component.prepareImage(), ComponentPeer.checkImage(), ComponentPeer.prepareImage(), Frame.setIconImage(), FramePeer.setIconImage(), Graphics.drawImage(), ImageObserver.imageUpdate(), MediaTracker.addImage(), MediaTracker.removeImage(), PixelGrabber(), Toolkit.checkImage(), Toolkit.prepareImage()
Returned By: Applet.getImage(), AppletContext.getImage(), BeanInfo.getIcon(), Component.createImage(), ComponentPeer.createImage(), Frame.getIconImage(), Image.getScaledInstance(), SimpleBeanInfo.getIcon(), SimpleBeanInfo.loadImage(), Toolkit.createImage(), Toolkit.getImage()
http://localhost/java/javaref/javanut/ch18_32.htm (1 of 2) [20/12/2001 11:00:55]
[Chapter 18] 18.32 java.awt.Image (JDK 1.0)
java.awt.IllegalComponentStateException (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_32.htm (2 of 2) [20/12/2001 11:00:55]
java.awt.Insets (JDK 1.0)
[Chapter 18] 18.53 java.awt.ScrollPane (JDK 1.1)
Chapter 18 The java.awt Package
18.53 java.awt.ScrollPane (JDK 1.1) This Container class creates horizontal and vertical scrollbars surrounding a "viewport" and allows a single child component to be displayed and scrolled within this viewport. Typically the child of the ScrollPane is larger than the ScrollPane itself, so scrollbars allow the user to select the currently visible portion. When you call the ScrollPane() constructor, you may optionally specify a scrollbar display policy, which should be one of the three constants defined by this class. If you do not specify a policy, ScrollPane uses the SCROLLBARS_AS_NEEDED policy. A program can programmatically scroll the child within the viewport by calling setScrollPosition(). getHAdjustable() and getVAdjustable() return the horizontal and vertical Adjustable objects that control scrolling (typically these are not actually instances of Scrollbar). You can use these Adjustable objects to specify the unit and block increment values for the scrollbars. You can also directly set the Adjustable value, as an alternative to setScrollPosition(), but should not set other values of the Adjustable objects. Use setSize() to set the size of the ScrollPane container. You may want to take the size of the scrollbars into account when computing the overall container size--use getHScrollbarHeight() and getVScrollbarWidth() to obtain these values. ScrollPane overrides the printComponents() method of Container so that when a ScrollPane is printed, the entire child component is printed, rather than only the currently visible portion. public class ScrollPane extends Container { // Public Constructors public ScrollPane(); public ScrollPane(int scrollbarDisplayPolicy); // Constants public static final int SCROLLBARS_ALWAYS; public static final int SCROLLBARS_AS_NEEDED; public static final int SCROLLBARS_NEVER; // Public Instance Methods public void addNotify(); // Overrides Container public void doLayout(); // Overrides Container public Adjustable getHAdjustable(); public int getHScrollbarHeight(); public Point getScrollPosition(); public int getScrollbarDisplayPolicy(); public Adjustable getVAdjustable(); public int getVScrollbarWidth(); public Dimension getViewportSize(); # public void layout(); // Overrides Container public String paramString(); // Overrides Container public void printComponents(Graphics g); // Overrides Container http://localhost/java/javaref/javanut/ch18_53.htm (1 of 2) [20/12/2001 11:00:55]
[Chapter 18] 18.53 java.awt.ScrollPane (JDK 1.1)
public final void setLayout(LayoutManager mgr); // Overrides Container public void setScrollPosition(int x, int y); public void setScrollPosition(Point p); // Protected Instance Methods protected final void addImpl(Component comp, Object constraints, int index); // Overrides Container }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Container->ScrollPane
Passed To: Toolkit.createScrollPane()
java.awt.Rectangle (JDK 1.0)
java.awt.Scrollbar (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_53.htm (2 of 2) [20/12/2001 11:00:55]
[Chapter 23] 23.20 java.beans.SimpleBeanInfo (JDK 1.1)
Chapter 23 The java.beans Package
23.20 java.beans.SimpleBeanInfo (JDK 1.1) The SimpleBeanInfo class is a trivial implementation of the BeanInfo interface. The methods of this class all return null or -1, indicating that no bean information is available. To use this class, you need only to override the method or methods that return the particular type of bean information you want to provide. In addition, SimpleBeanInfo provides a convenience method, loadImage(), that takes a resource name as an argument and returns an Image object. This method is useful when defining the getIcon() method. public class SimpleBeanInfo extends Object implements BeanInfo { // Default Constructor: public SimpleBeanInfo() // Public Instance Methods public BeanInfo[] getAdditionalBeanInfo(); // From BeanInfo public BeanDescriptor getBeanDescriptor(); // From BeanInfo public int getDefaultEventIndex(); // From BeanInfo public int getDefaultPropertyIndex(); // From BeanInfo public EventSetDescriptor[] getEventSetDescriptors(); // From BeanInfo public Image getIcon(int iconKind); // From BeanInfo public MethodDescriptor[] getMethodDescriptors(); // From BeanInfo public PropertyDescriptor[] getPropertyDescriptors(); // From BeanInfo public Image loadImage(String resourceName); }
java.beans.PropertyVetoException (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_20.htm [20/12/2001 11:00:55]
java.beans.VetoableChangeListener (JDK 1.1)
[Chapter 29] 29.16 java.text.ParsePosition (JDK 1.1)
Chapter 29 The java.text Package
29.16 java.text.ParsePosition (JDK 1.1) ParsePosition objects are passed to the parse() and parseObject() methods of Format and its subclasses. The ParsePosition class represents the position in a string at which parsing should begin or at which parsing stopped. Before calling a parse() method, you can specify the starting position of parsing by passing the desired index to the ParsePosition() constructor, or by calling the setIndex() of an existing ParsePosition object. When parse() returns, you can determine where parsing ended by calling getIndex(). When parsing multiple objects or values from a string, a single ParsePosition object can be used sequentially. public class ParsePosition extends Object { // Public Constructor public ParsePosition(int index); // Public Instance Methods public int getIndex(); public void setIndex(int index); }
Passed To: ChoiceFormat.parse(), DateFormat.parse(), DateFormat.parseObject(), DecimalFormat.parse(), Format.parseObject(), MessageFormat.parse(), MessageFormat.parseObject(), NumberFormat.parse(), NumberFormat.parseObject(), SimpleDateFormat.parse()
java.text.ParseException (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_16.htm [20/12/2001 11:00:55]
java.text.RuleBasedCollator (JDK 1.1)
[Chapter 28] 28.16 java.net.Socket (JDK 1.0)
Chapter 28 The java.net Package
28.16 java.net.Socket (JDK 1.0) This class implements a socket for interprocess communication over the network. The constructor methods create the socket and connect it to the specified host and port. You may also optionally specify whether communication through the socket should be based on an underlying reliable connection-based stream protocol, or on an underlying unreliable (but faster) datagram protocol. A stream protocol is the default. Once the socket is created, getInputStream() and getOutputStream() return InputStream and OutputStream objects that you can use just as you would for file input and output. getInetAddress() and getPort() return the address and port that the socket is connected to. getLocalPort() returns the local port that the socket is using. public class Socket extends Object { // Public Constructors public Socket(String host, int port) throws UnknownHostException, IOException; public Socket(InetAddress address, int port) throws IOException; 1.1public Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException; 1.1public Socket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException; # public Socket(String host, int port, boolean stream) throws IOException; # public Socket(InetAddress host, int port, boolean stream) throws IOException; // Protected Constructors 1.1protected Socket(); 1.1protected Socket(SocketImpl impl) throws SocketException; // Class Methods public static synchronized void setSocketImplFactory(SocketImplFactory fac) throws IOException; // Public Instance Methods public synchronized void close() throws IOException; public InetAddress getInetAddress(); public InputStream getInputStream() throws IOException; 1.1public InetAddress getLocalAddress(); public int getLocalPort(); public OutputStream getOutputStream() throws IOException; public int getPort(); 1.1public int getSoLinger() throws SocketException; 1.1public synchronized int getSoTimeout() throws SocketException; 1.1public boolean getTcpNoDelay() throws SocketException; 1.1public void setSoLinger(boolean on, int val) throws SocketException; 1.1public synchronized void setSoTimeout(int timeout) throws SocketException; 1.1public void setTcpNoDelay(boolean on) throws SocketException;
http://localhost/java/javaref/javanut/ch28_16.htm (1 of 2) [20/12/2001 11:00:56]
[Chapter 28] 28.16 java.net.Socket (JDK 1.0)
public String toString();
// Overrides Object
}
Passed To: ServerSocket.implAccept()
Returned By: ServerSocket.accept()
java.net.ServerSocket (JDK 1.0)
java.net.SocketException (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_16.htm (2 of 2) [20/12/2001 11:00:56]
[Chapter 23] 23.3 java.beans.Beans (JDK 1.1)
Chapter 23 The java.beans Package
23.3 java.beans.Beans (JDK 1.1) The Beans class is never meant to be instantiated; its static methods provide miscellaneous JavaBeans features. The instantiate() method creates an instance of a bean. The specified bean name represents either a serialized bean file or a bean class file; it is interpreted relative to the specified ClassLoader object. The setDesignTime() and isDesignTime() methods are used to set and query a flag that indicates whether beans are being used in an application builder environment. Similarly, setGuiAvailable() and isGuiAvailable() set and query a flag that indicates whether the Java Virtual Machine is running in an environment in which a GUI is available. (Note that untrusted applet code cannot call setDesignTime() or setGuiAvailable().) The isInstanceOf() method is a replacement for the Java instanceof operator for use with beans. Currently, it behaves just like instanceof, but in the future it may work with beans that consist of a set of Java objects, each of which provides a different "view" of a bean. Similarly, the getInstanceOf() method is a replacement for the Java cast operator. It converts a bean to a superclass or interface type. Currently, it behaves just like a cast, but you should use it for future compatibility with multiclass beans. public class Beans extends Object { // Default Constructor: public Beans() // Class Methods public static Object getInstanceOf(Object bean, Class targetType); public static Object instantiate(ClassLoader cls, String beanName) public static Object instantiate'u'throws IOException, ClassNotFoundException; public static boolean isDesignTime(); public static boolean isGuiAvailable(); public static boolean isInstanceOf(Object bean, Class targetType); public static void setDesignTime(boolean isDesignTime) throws SecurityException; public static void setGuiAvailable(boolean isGuiAvailable) throws SecurityException; }
java.beans.BeanInfo (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_03.htm [20/12/2001 11:00:56]
java.beans.Customizer (JDK 1.1)
[Chapter 24] 24.34 java.io.LineNumberInputStream (JDK 1.0; Deprecated.)
Chapter 24 The java.io Package
24.34 java.io.LineNumberInputStream (JDK 1.0; Deprecated.) This class is a FilterInputStream that keeps track of the number of lines of data that have been read. getLineNumber() returns the current line number. setLineNumber() sets the line number of the current line. Subsequent lines are numbered starting from that number. This class is deprecated in Java 1.1 because it does not properly convert bytes to characters. Use LineNumberReader instead. public class LineNumberInputStream extends FilterInputStream { // Public Constructor public LineNumberInputStream(InputStream in); // Public Instance Methods public int available() throws IOException; // Overrides FilterInputStream public int getLineNumber(); public void mark(int readlimit); // Overrides FilterInputStream public int read() throws IOException; // Overrides FilterInputStream public int read(byte[] b, int off, int len) throws IOException; // Overrides FilterInputStream public void reset() throws IOException; // Overrides FilterInputStream public void setLineNumber(int lineNumber); public long skip(long n) throws IOException; // Overrides FilterInputStream }
Hierarchy: Object->InputStream->FilterInputStream->LineNumberInputStream
java.io.IOException (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_34.htm [20/12/2001 11:00:56]
java.io.LineNumberReader (JDK 1.1)
[Chapter 24] 24.35 java.io.LineNumberReader (JDK 1.1)
Chapter 24 The java.io Package
24.35 java.io.LineNumberReader (JDK 1.1) This class is a character input stream that keeps track of the number of lines of text that have been read from it. It supports the usual Reader methods, and also the readLine() method introduced by its superclass. In addition to these methods, you can call getLineNumber() to query the number of lines set so far. You can also call setLineNumber() to set the line number for the current line. Subsequent lines are numbered sequentially from this specified starting point. This class is a character-stream analog to LineNumberInputStream, which has been deprecated in Java 1.1. public class LineNumberReader extends BufferedReader { // Public Constructors public LineNumberReader(Reader in); public LineNumberReader(Reader in, int sz); // Public Instance Methods public int getLineNumber(); public void mark(int readAheadLimit) throws IOException; // Overrides BufferedReader public int read() throws IOException; // Overrides BufferedReader public int read(char[] cbuf, int off, int len) throws IOException; // Overrides BufferedReader public String readLine() throws IOException; // Overrides BufferedReader public void reset() throws IOException; // Overrides BufferedReader public void setLineNumber(int lineNumber); public long skip(long n) throws IOException; // Overrides BufferedReader }
Hierarchy: Object->Reader->BufferedReader->LineNumberReader
java.io.LineNumberInputStream (JDK 1.0; Deprecated.)
http://localhost/java/javaref/javanut/ch24_35.htm [20/12/2001 11:00:56]
java.io.NotActiveException (JDK 1.1)
[Chapter 18] 18.45 java.awt.MenuShortcut (JDK 1.1)
Chapter 18 The java.awt Package
18.45 java.awt.MenuShortcut (JDK 1.1) This class represents a keystroke used to select a MenuItem without actually pulling down the menu. A MenuShortcut object can be specified for a MenuItem when the MenuItem is created or by calling the item's setShortcut() method. The keystroke sequence for the menu shortcut automatically appears in the label for the menu item, so you need not add this information yourself. When you create a MenuShortcut, you specify the key code of the shortcut--this is one of the VK_ constants defined by java.awt.event.KeyEvent, and is not always the same as a corresponding character code. You may also optionally specify a boolean value that, if true, indicates that the MenuShortcut requires the Shift key to be held down. Note that menu shortcuts are triggered in a platform-dependent way. When you create a shortcut, you specify only the keycode and an optional Shift modifier. The shortcut is not triggered, however, unless an additional modifier key is held down. On Windows platforms, for example, the Ctrl key is used for menu shortcuts. You can query the platform-specific menu shortcut key with Toolkit.getMenuShortcutKeyMask(). public class MenuShortcut extends Object implements Serializable { // Public Constructors public MenuShortcut(int key); public MenuShortcut(int key, boolean useShiftModifier); // Public Instance Methods public boolean equals(MenuShortcut s); public int getKey(); public String toString(); // Overrides Object public boolean usesShiftModifier(); // Protected Instance Methods protected String paramString(); }
http://localhost/java/javaref/javanut/ch18_45.htm (1 of 2) [20/12/2001 11:00:56]
[Chapter 18] 18.45 java.awt.MenuShortcut (JDK 1.1)
Passed To: MenuBar.deleteShortcut(), MenuBar.getShortcutMenuItem(), MenuItem(), MenuItem.setShortcut(), MenuShortcut.equals()
Returned By: MenuItem.getShortcut()
java.awt.MenuItem (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_45.htm (2 of 2) [20/12/2001 11:00:56]
java.awt.Panel (JDK 1.0)
[Chapter 24] 24.68 java.io.WriteAbortedException (JDK 1.1)
Chapter 24 The java.io Package
24.68 java.io.WriteAbortedException (JDK 1.1) This exception is thrown when reading a stream of data that is incomplete because an exception was thrown while it was being written. The detail field may contain the exception that terminated the output stream. The getMessage() method has been overridden to include the message of this detail exception, if any. public class WriteAbortedException extends ObjectStreamException { // Public Constructor public WriteAbortedException(String s, Exception ex); // Public Instance Variables public Exception detail; // Public Instance Methods public String getMessage(); // Overrides Throwable }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ObjectStreamException->WriteAbortedException
java.io.UTFDataFormatException (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_68.htm [20/12/2001 11:00:57]
java.io.Writer (JDK 1.1)
[Chapter 26] 26.7 java.lang.reflect.Modifier (JDK 1.1)
Chapter 26 The java.lang.reflect Package
26.7 java.lang.reflect.Modifier (JDK 1.1) This class defines a number of constants and static methods that are used to interpret the integer values returned by the getModifiers() methods of the Field, Method, and Constructor classes. The isPublic(), isAbstract(), and related methods return true if the modifiers value includes the specified modifier, otherwise they return false. The constants defined by this class specify the various bit flags used in the modifiers value. You can use these constants to test for modifiers if you want to perform your own boolean algebra. public class Modifier extends Object { // Default Constructor: public Modifier() // Constants public static final int ABSTRACT; public static final int FINAL; public static final int INTERFACE; public static final int NATIVE; public static final int PRIVATE; public static final int PROTECTED; public static final int PUBLIC; public static final int STATIC; public static final int SYNCHRONIZED; public static final int TRANSIENT; public static final int VOLATILE; // Class Methods public static boolean isAbstract(int mod); public static boolean isFinal(int mod); public static boolean isInterface(int mod); public static boolean isNative(int mod); public static boolean isPrivate(int mod); public static boolean isProtected(int mod); public static boolean isPublic(int mod); public static boolean isStatic(int mod); public static boolean isSynchronized(int mod); public static boolean isTransient(int mod); http://localhost/java/javaref/javanut/ch26_07.htm (1 of 2) [20/12/2001 11:00:57]
[Chapter 26] 26.7 java.lang.reflect.Modifier (JDK 1.1)
public static boolean isVolatile(int mod); public static String toString(int mod); }
java.lang.reflect.Method (JDK 1.1)
http://localhost/java/javaref/javanut/ch26_07.htm (2 of 2) [20/12/2001 11:00:57]
The java.math Package
[Chapter 18] 18.50 java.awt.PrintGraphics (JDK 1.1)
Chapter 18 The java.awt Package
18.50 java.awt.PrintGraphics (JDK 1.1) The Graphics object returned by the getGraphics() method of PrintJob always implements this PrintGraphics interface. You can use this fact to distinguish a Graphics object that draws to the screen from one that generates hardcopy. This is a useful thing to do in a paint() method when you want to generate hardcopy that differs somewhat from what is displayed on-screen. The getPrintJob() method defined by this interface can also be used, of course, to return the PrintJob with which the PrintGraphics object is associated. public abstract interface PrintGraphics { // Public Instance Methods public abstract PrintJob getPrintJob(); }
java.awt.PopupMenu (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_50.htm [20/12/2001 11:00:57]
java.awt.PrintJob (JDK 1.1)
[Chapter 30] 30.17 java.util.Properties (JDK 1.0)
Chapter 30 The java.util Package
30.17 java.util.Properties (JDK 1.0) This class is an extension of Hashtable that allows key/value pairs to be read from and written to a stream. The Properties class is used to implement the system properties list, which supports user customization by allowing programs to look up the value of named resources. When you create a Properties object, you may specify another Properties object that contains default values. Keys (property names) and values are associated in a Properties object with the Hashtable method put(). Values are looked up with getProperty()--if this method does not find the key in the current Properties object, it looks in the default Properties object that was passed to the constructor method. A default value may also be specified in case the key is not found at all. propertyNames() returns an enumeration of all property names (keys) stored in the Properties object and (recursively) also all property names stored in the default Properties object associated with it. list() prints the properties stored in a Properties object. It is useful for debugging. save() writes a Properties object to a stream. load() reads key/value pairs from a stream and stores them in a Properties object. public class Properties extends Hashtable { // Public Constructors public Properties(); public Properties(Properties defaults); // Protected Instance Variables protected Properties defaults; // Public Instance Methods public String getProperty(String key); public String getProperty(String key, String defaultValue); public void list(PrintStream out); 1.1public void list(PrintWriter out); public synchronized void load(InputStream in) throws IOException; public Enumeration propertyNames(); public synchronized void save(OutputStream out, String header); }
Hierarchy: Object->Dictionary->Hashtable(Cloneable, Serializable)->Properties
http://localhost/java/javaref/javanut/ch30_17.htm (1 of 2) [20/12/2001 11:00:57]
[Chapter 30] 30.17 java.util.Properties (JDK 1.0)
Passed To: Properties(), System.setProperties(), Toolkit.getPrintJob()
Returned By: System.getProperties()
Type Of: Properties.defaults
java.util.Observer (JDK 1.0)
java.util.PropertyResourceBundle (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_17.htm (2 of 2) [20/12/2001 11:00:57]
[Chapter 21] 21.14 java.awt.image.ReplicateScaleFilter (JDK 1.1)
Chapter 21 The java.awt.image Package
21.14 java.awt.image.ReplicateScaleFilter (JDK 1.1) This class implements an ImageFilter that scales an image to a specified pixel size. It uses a very simple scaling algorithm in which rows and columns of image pixels are duplicated or omitted as necessary to achieve the desired size. See AreaAveragingScaleFilter for a scaling filter that results in smoother images. The methods of this class are ImageConsumer methods used for communication between the image filter and the FilteredImageSource that uses it. Applications do not usually call these methods directly. The easiest way to use this filter is to call Image.getScaledInstance(), specifying an appropriate hint constant. public class ReplicateScaleFilter extends ImageFilter { // Public Constructor public ReplicateScaleFilter(int width, int height); // Protected Instance Variables protected int destHeight; protected int destWidth; protected Object outpixbuf; protected int srcHeight; protected int srcWidth; protected int[] srccols; protected int[] srcrows; // Public Instance Methods public void setDimensions(int w, int h); // Overrides ImageFilter public void setPixels(int x, int y, int w, int h, ColorModel model, public void setPixels'u'byte[] pixels, int off, int scansize); // Overrides ImageFilter public void setPixels(int x, int y, int w, int h, ColorModel model, public void setPixels'u'int[] pixels, int off, int scansize); // Overrides ImageFilter public void setProperties(Hashtable props); // Overrides ImageFilter }
Hierarchy: Object->ImageFilter(ImageConsumer, Cloneable)->ReplicateScaleFilter
Extended By: AreaAveragingScaleFilter
http://localhost/java/javaref/javanut/ch21_14.htm (1 of 2) [20/12/2001 11:00:57]
[Chapter 21] 21.14 java.awt.image.ReplicateScaleFilter (JDK 1.1)
java.awt.image.RGBImageFilter (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_14.htm (2 of 2) [20/12/2001 11:00:57]
The java.awt.peer Package
[Chapter 18] 18.58 java.awt.TextComponent (JDK 1.0)
Chapter 18 The java.awt Package
18.58 java.awt.TextComponent (JDK 1.0) This class is the superclass of the TextArea and TextField components. It cannot be instantiated itself, but provides methods that are common to these two component types. setEditable() specifies whether the text in the text component is editable or not. getText() returns the text in the component, and setText() specifies text to be displayed. getSelectedText() returns the currently selected text in the text component, and getSelectionStart() and getSelectionEnd() return the extents of the selected region of text. select() and selectAll() select some or all of the text displayed in the text component. See also TextField and TextArea. public class TextComponent extends Component { // No Constructor // Protected Instance Variables 1.1 protected transient TextListener textListener; // Public Instance Methods 1.1 public void addTextListener(TextListener l); 1.1 public int getCaretPosition(); public synchronized String getSelectedText(); public synchronized int getSelectionEnd(); public synchronized int getSelectionStart(); public synchronized String getText(); public boolean isEditable(); public void removeNotify(); // Overrides Component 1.1 public void removeTextListener(TextListener l); public synchronized void select(int selectionStart, int selectionEnd); public synchronized void selectAll(); 1.1 public void setCaretPosition(int position); public synchronized void setEditable(boolean b); 1.1 public synchronized void setSelectionEnd(int selectionEnd); 1.1 public synchronized void setSelectionStart(int selectionStart); public synchronized void setText(String t); // Protected Instance Methods protected String paramString(); // Overrides Component 1.1 protected void processEvent(AWTEvent e); // Overrides Component 1.1 protected void processTextEvent(TextEvent e); }
http://localhost/java/javaref/javanut/ch18_58.htm (1 of 2) [20/12/2001 11:00:58]
[Chapter 18] 18.58 java.awt.TextComponent (JDK 1.0)
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->TextComponent
Extended By: TextArea, TextField
java.awt.TextArea (JDK 1.0)
java.awt.TextField (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_58.htm (2 of 2) [20/12/2001 11:00:58]
[Chapter 19] 19.5 java.awt.datatransfer.Transferable (JDK 1.1)
Chapter 19 The java.awt.datatransfer Package
19.5 java.awt.datatransfer.Transferable (JDK 1.1) This interface defines the methods that a class must define if it is to act as the source object in a data transfer operation. getTransferDataFlavors() should return an array of DataFlavor objects that specify the data types or formats in which the object can provide its data. The DataFlavor objects should be ordered from best format (most richly descriptive) to worst format. isDataFlavorSupported() must return a boolean value indicating whether it can transfer data using a specified DataFlavor. Finally, getTransferData() must return an object that represents the data formatted as required by the specified DataFlavor. StringSelection is a pre-defined class that implements the Transferable interface for the transfer of string data. public abstract interface Transferable { // Public Instance Methods public abstract Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException; public abstract DataFlavor[] getTransferDataFlavors(); public abstract boolean isDataFlavorSupported(DataFlavor flavor); }
Implemented By: StringSelection
Passed To: Clipboard.setContents(), ClipboardOwner.lostOwnership(), StringSelection.lostOwnership()
Returned By: Clipboard.getContents()
http://localhost/java/javaref/javanut/ch19_05.htm (1 of 2) [20/12/2001 11:00:58]
[Chapter 19] 19.5 java.awt.datatransfer.Transferable (JDK 1.1)
Type Of: Clipboard.contents
java.awt.datatransfer.StringSelection (JDK 1.1)
java.awt.datatransfer.UnsupportedFlavorException (JDK 1.1)
http://localhost/java/javaref/javanut/ch19_05.htm (2 of 2) [20/12/2001 11:00:58]
[Chapter 21] 21.12 java.awt.image.PixelGrabber (JDK 1.0)
Chapter 21 The java.awt.image Package
21.12 java.awt.image.PixelGrabber (JDK 1.0) This class is an ImageConsumer that extracts a specified rectangular array of pixels (in the default RGB color model) from a specified Image or ImageProducer and stores them into a specified array (using the specified offset into the array and specified scanline size). Use this class when you want to inspect or manipulate the data of an image or some rectangular portion of an image. The method grabPixels() makes the PixelGrabber start grabbing pixels. status() returns the status of the pixel-grabbing process. The return value uses the same flag value constants as the ImageObserver class does. The remaining methods are the standard ImageConsumer methods and should not be called directly. public class PixelGrabber extends Object implements ImageConsumer { // Public Constructors public PixelGrabber(Image img, int x, int y, int w, int h, int[] pix, int off, int scansize); public PixelGrabber(ImageProducer ip, int x, int y, int w, int h, int[] pix, int off, int scansize); 1.1 public PixelGrabber(Image img, int x, int y, int w, int h, boolean forceRGB); // Public Instance Methods 1.1 public synchronized void abortGrabbing(); 1.1 public synchronized ColorModel getColorModel(); 1.1 public synchronized int getHeight(); 1.1 public synchronized Object getPixels(); 1.1 public synchronized int getStatus(); 1.1 public synchronized int getWidth(); public boolean grabPixels() throws InterruptedException; public synchronized boolean grabPixels(long ms) throws InterruptedException; public synchronized void imageComplete(int status); // From ImageConsumer public void setColorModel(ColorModel model); // From ImageConsumer public void setDimensions(int width, int height); // From ImageConsumer public void setHints(int hints); // From ImageConsumer public void setPixels(int srcX, int srcY, int srcW, int srcH, ColorModel model, public void setPixels'u'byte[] pixels, int srcOff, int srcScan); // From ImageConsumer public void setPixels(int srcX, int srcY, int srcW, int srcH, ColorModel model, public void setPixels'u'int[] pixels, int srcOff, int srcScan); // From ImageConsumer public void setProperties(Hashtable props); // From ImageConsumer 1.1 public synchronized void startGrabbing();
http://localhost/java/javaref/javanut/ch21_12.htm (1 of 2) [20/12/2001 11:00:58]
[Chapter 21] 21.12 java.awt.image.PixelGrabber (JDK 1.0)
public synchronized int status(); }
java.awt.image.MemoryImageSource (JDK 1.0)
java.awt.image.RGBImageFilter (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_12.htm (2 of 2) [20/12/2001 11:00:58]
[Chapter 18] 18.28 java.awt.GridBagConstraints (JDK 1.0)
Chapter 18 The java.awt Package
18.28 java.awt.GridBagConstraints (JDK 1.0) This class encapsulates the instance variables that tell a GridBagLayout how to position a given Component within its Container. gridx, gridy These fields specify the grid position of the component. The RELATIVE constant specifies a position to the right or below the previous component. gridwidth, gridheight These fields specify the height and width of the component in grid cells. The constant REMAINDER specifies that the component is the last one and should get all remaining cells. fill This field specifies which dimensions of a component should grow when the space available for it is larger than its default size. Legal values are the constants NONE, BOTH, HORIZONTAL, and VERTICAL. ipadx, ipady These fields specify internal padding to add on each side of the component in each dimension. They increase the size of the component beyond its default minimum size. insets This Insets object specifies margins to appear on all sides of the component. anchor This field specifies how the component should be displayed within its grid cells when it is smaller than those cells. The CENTER constant and the compass-point constants are legal values. weightx, weighty These fields specify how extra space in the container should be distributed among its components in the X and Y dimensions. Larger weights specify that a component should receive a proportionally larger amount of extra space. A zero weight specifies that the component should not receive any extra space. These weights specify the resizing behavior of the component and its container. See also GridBagLayout. public class GridBagConstraints extends Object implements Cloneable, Serializable { // Public Constructor public GridBagConstraints(); // Constants public static final int BOTH; public static final int CENTER; public static final int EAST; public static final int HORIZONTAL; http://localhost/java/javaref/javanut/ch18_28.htm (1 of 2) [20/12/2001 11:00:58]
[Chapter 18] 18.28 java.awt.GridBagConstraints (JDK 1.0)
public static final int public static final int public static final int public static final int public static final int public static final int public static final int public static final int public static final int public static final int public static final int // Public Instance Variables public int anchor; public int fill; public int gridheight; public int gridwidth; public int gridx; public int gridy; public Insets insets; public int ipadx; public int ipady; public double weightx; public double weighty; // Public Instance Methods public Object clone();
NONE; NORTH; NORTHEAST; NORTHWEST; RELATIVE; REMAINDER; SOUTH; SOUTHEAST; SOUTHWEST; VERTICAL; WEST;
// Overrides Object
}
Passed To: GridBagLayout.AdjustForGravity(), GridBagLayout.setConstraints()
Returned By: GridBagLayout.getConstraints(), GridBagLayout.lookupConstraints()
Type Of: GridBagLayout.defaultConstraints
java.awt.Graphics (JDK 1.0)
java.awt.GridBagLayout (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_28.htm (2 of 2) [20/12/2001 11:00:58]
[Chapter 18] 18.30 java.awt.GridLayout (JDK 1.0)
Chapter 18 The java.awt Package
18.30 java.awt.GridLayout (JDK 1.0) This class implements the LayoutManager interface to lay out Component objects in a Container. It divides the Container into a specified number of rows and columns and arranges the components in those rows and columns, left-to-right and top-to-bottom. If either the number of rows or the number of columns is set to zero, its value is computed from the other dimension and the total number of components. Do not confuse this class with the more flexible and complicated GridBagLayout. Note that applications should never call the LayoutManager methods of this class directly; the Container for which the GridLayout is registered does this. public class GridLayout extends Object implements LayoutManager, Serializable { // Public Constructors 1.1 public GridLayout(); public GridLayout(int rows, int cols); public GridLayout(int rows, int cols, int hgap, int vgap); // Public Instance Methods public void addLayoutComponent(String name, Component comp); // From LayoutManager 1.1 public int getColumns(); 1.1 public int getHgap(); 1.1 public int getRows(); 1.1 public int getVgap(); public void layoutContainer(Container parent); // From LayoutManager public Dimension minimumLayoutSize(Container parent); // From LayoutManager public Dimension preferredLayoutSize(Container parent); // From LayoutManager public void removeLayoutComponent(Component comp); // From LayoutManager 1.1 public void setColumns(int cols); 1.1 public void setHgap(int hgap); 1.1 public void setRows(int rows); 1.1 public void setVgap(int vgap); public String toString(); // Overrides Object }
java.awt.GridBagLayout (JDK 1.0)
java.awt.IllegalComponentStateException (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_30.htm [20/12/2001 11:00:59]
[Chapter 30] 30.15 java.util.Observable (JDK 1.0)
Chapter 30 The java.util Package
30.15 java.util.Observable (JDK 1.0) This class is the superclass of all "observable" objects to be used in an object-oriented model/view paradigm. The class methods allow you to add and delete Observer objects to and from an Observable's list, and to notify all of the Observer objects on the list. Observer objects are "notified" by invoking their update() method. Observable also maintains an internal "changed" flag, which may be set and cleared by the Observable, and which may be queried with hasChanged() by any interested observer. public class Observable extends Object { // Public Constructor 1.1public Observable(); // Public Instance Methods public synchronized void addObserver(Observer o); public synchronized int countObservers(); public synchronized void deleteObserver(Observer o); public synchronized void deleteObservers(); public synchronized boolean hasChanged(); public void notifyObservers(); public void notifyObservers(Object arg); // Protected Instance Methods protected synchronized void clearChanged(); protected synchronized void setChanged(); }
Passed To: Observer.update()
java.util.NoSuchElementException (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_15.htm [20/12/2001 11:00:59]
java.util.Observer (JDK 1.0)
[Chapter 25] 25.24 java.lang.IllegalArgumentException (JDK 1.0)
Chapter 25 The java.lang Package
25.24 java.lang.IllegalArgumentException (JDK 1.0) Signals an illegal argument to a method. See subclasses IllegalThreadStateException and NumberFormatException. public class IllegalArgumentException extends RuntimeException { // Public Constructors public IllegalArgumentException(); public IllegalArgumentException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->IllegalArgumentException
Extended By: IllegalThreadStateException, NumberFormatException
Thrown By: Array.get(), Array.getBoolean(), Array.getByte(), Array.getChar(), Array.getDouble(), Array.getFloat(), Array.getInt(), Array.getLength(), Array.getLong(), Array.getShort(), Array.newInstance(), Array.set(), Array.setBoolean(), Array.setByte(), Array.setChar(), Array.setDouble(), Array.setFloat(), Array.setInt(), Array.setLong(), Array.setShort(), BigDecimal.divide(), BigDecimal.setScale(), BigInteger(), Constructor.newInstance(), Field.get(), Field.getBoolean(), Field.getByte(), Field.getChar(), Field.getDouble(), Field.getFloat(), Field.getInt(), Field.getLong(), Field.getShort(), Field.set(), Field.setBoolean(), Field.setByte(), Field.setChar(), Field.setDouble(), Field.setFloat(), Field.setInt(), Field.setLong(), Field.setShort(), Method.invoke(), PropertyEditor.setAsText(), PropertyEditorSupport.setAsText()
java.lang.IllegalAccessException (JDK 1.0) http://localhost/java/javaref/javanut/ch25_24.htm (1 of 2) [20/12/2001 11:00:59]
java.lang.IllegalMonitorStateException (JDK 1.0)
[Chapter 25] 25.24 java.lang.IllegalArgumentException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_24.htm (2 of 2) [20/12/2001 11:00:59]
[Chapter 18] 18.31 java.awt.IllegalComponentStateException (JDK 1.1)
Chapter 18 The java.awt Package
18.31 java.awt.IllegalComponentStateException (JDK 1.1) This exception signals that an AWT component is not in the appropriate state (for example, it hasn't been added to a container yet or is currently hidden) for some requested operation. public class IllegalComponentStateException extends IllegalStateException { // Public Constructors public IllegalComponentStateException(); public IllegalComponentStateException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException-> IllegalStateException->IllegalComponentStateException
java.awt.GridLayout (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_31.htm [20/12/2001 11:00:59]
java.awt.Image (JDK 1.0)
[Chapter 25] 25.25 java.lang.IllegalMonitorStateException (JDK 1.0)
Chapter 25 The java.lang Package
25.25 java.lang.IllegalMonitorStateException (JDK 1.0) Signals an illegal monitor state. It is thrown by the Object notify() and wait() methods used for thread synchronization. public class IllegalMonitorStateException extends RuntimeException { // Public Constructors public IllegalMonitorStateException(); public IllegalMonitorStateException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->IllegalMonitorStateException
java.lang.IllegalArgumentException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_25.htm [20/12/2001 11:01:00]
java.lang.IllegalStateException (JDK 1.1)
[Chapter 25] 25.26 java.lang.IllegalStateException (JDK 1.1)
Chapter 25 The java.lang Package
25.26 java.lang.IllegalStateException (JDK 1.1) An exception of this type signals that a method has been invoked on an object that is not in an appropriate state to be able to perform the requested operation. public class IllegalStateException extends RuntimeException { // Public Constructors public IllegalStateException(); public IllegalStateException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->IllegalStateException
Extended By: IllegalComponentStateException
java.lang.IllegalMonitorStateException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_26.htm [20/12/2001 11:01:00]
java.lang.IllegalThreadStateException (JDK 1.0)
[Chapter 25] 25.27 java.lang.IllegalThreadStateException (JDK 1.0)
Chapter 25 The java.lang Package
25.27 java.lang.IllegalThreadStateException (JDK 1.0) Signals that a thread is not in the appropriate state for an attempted operation to succeed. public class IllegalThreadStateException extends IllegalArgumentException { // Public Constructors public IllegalThreadStateException(); public IllegalThreadStateException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException-> IllegalArgumentException->IllegalThreadStateException
java.lang.IllegalStateException (JDK 1.1)
http://localhost/java/javaref/javanut/ch25_27.htm [20/12/2001 11:01:00]
java.lang.IncompatibleClassChangeError (JDK 1.0)
[Chapter 21] 21.6 java.awt.image.ImageConsumer (JDK 1.0)
Chapter 21 The java.awt.image Package
21.6 java.awt.image.ImageConsumer (JDK 1.0) This interface defines the methods necessary for a class that consumes image data to communicate with a class that produces image data. The methods defined by this interface should never be called by a program directly; instead, they are invoked by an ImageProducer to pass the image data and other information about the image to the ImageConsumer. The constants defined by this interface are values passed to the setHints() and imageComplete() methods. Unless you want to do low-level manipulation of image data, you never need to use or implement an ImageConsumer. public abstract interface ImageConsumer { // Constants public static final int COMPLETESCANLINES; public static final int IMAGEABORTED; public static final int IMAGEERROR; public static final int RANDOMPIXELORDER; public static final int SINGLEFRAME; public static final int SINGLEFRAMEDONE; public static final int SINGLEPASS; public static final int STATICIMAGEDONE; public static final int TOPDOWNLEFTRIGHT; // Public Instance Methods public abstract void imageComplete(int status); public abstract void setColorModel(ColorModel model); public abstract void setDimensions(int width, int height); public abstract void setHints(int hintflags); public abstract void setPixels(int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize); public abstract void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize); public abstract void setProperties(Hashtable props); }
Implemented By: ImageFilter, PixelGrabber
Passed To: FilteredImageSource.addConsumer(), FilteredImageSource.isConsumer(), FilteredImageSource.removeConsumer(),
http://localhost/java/javaref/javanut/ch21_06.htm (1 of 2) [20/12/2001 11:01:00]
[Chapter 21] 21.6 java.awt.image.ImageConsumer (JDK 1.0)
FilteredImageSource.requestTopDownLeftRightResend(), FilteredImageSource.startProduction(), ImageFilter.getFilterInstance(), ImageProducer.addConsumer(), ImageProducer.isConsumer(), ImageProducer.removeConsumer(), ImageProducer.requestTopDownLeftRightResend(), ImageProducer.startProduction(), MemoryImageSource.addConsumer(), MemoryImageSource.isConsumer(), MemoryImageSource.removeConsumer(), MemoryImageSource.requestTopDownLeftRightResend(), MemoryImageSource.startProduction()
Type Of: ImageFilter.consumer
java.awt.image.FilteredImageSource (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_06.htm (2 of 2) [20/12/2001 11:01:00]
java.awt.image.ImageFilter (JDK 1.0)
[Chapter 21] 21.7 java.awt.image.ImageFilter (JDK 1.0)
Chapter 21 The java.awt.image Package
21.7 java.awt.image.ImageFilter (JDK 1.0) This class is used in conjunction with a FilteredImageSource. It accepts image data through the ImageConsumer interface and passes it on to an ImageConsumer specified by the controlling FilteredImageSource. ImageFilter is the superclass of all image filters, and performs no filtering itself. You must subclass it to perform the desired filtering. See CropImageFilter and RGBImageFilter. The ImageFilter methods are the ImageConsumer methods invoked by an ImageProducer. You should not call them directly. See FilteredImageSource for an example of using an ImageFilter. public class ImageFilter extends Object implements ImageConsumer, Cloneable { // Default Constructor: public ImageFilter() // Protected Instance Variables protected ImageConsumer consumer; // Public Instance Methods public Object clone(); // Overrides Object public ImageFilter getFilterInstance(ImageConsumer ic); public void imageComplete(int status); // From ImageConsumer public void resendTopDownLeftRight(ImageProducer ip); public void setColorModel(ColorModel model); // From ImageConsumer public void setDimensions(int width, int height); // From ImageConsumer public void setHints(int hints); // From ImageConsumer public void setPixels(int x, int y, int w, int h, ColorModel model, public void setPixels'u'byte[] pixels, int off, int scansize); // From ImageConsumer public void setPixels(int x, int y, int w, int h, ColorModel model, public void setPixels'u'int[] pixels, int off, int scansize); // From ImageConsumer public void setProperties(Hashtable props); // From ImageConsumer }
Extended By: CropImageFilter, ReplicateScaleFilter, RGBImageFilter
Passed To: FilteredImageSource()
http://localhost/java/javaref/javanut/ch21_07.htm (1 of 2) [20/12/2001 11:01:00]
[Chapter 21] 21.7 java.awt.image.ImageFilter (JDK 1.0)
Returned By: ImageFilter.getFilterInstance()
java.awt.image.ImageConsumer (JDK 1.0)
java.awt.image.ImageObserver (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_07.htm (2 of 2) [20/12/2001 11:01:00]
[Chapter 21] 21.8 java.awt.image.ImageObserver (JDK 1.0)
Chapter 21 The java.awt.image Package
21.8 java.awt.image.ImageObserver (JDK 1.0) This interface defines a method and associated constants used by classes that want to receive information asynchronously about the status of an image. Many methods that query information about an image take an ImageObserver as an argument. If the specified information is not available when requested, it is passed to the ImageObserver when it becomes available. Component implements this interface, and components are the most commonly used image observers. public abstract interface ImageObserver { // Constants public static final int ABORT; public static final int ALLBITS; public static final int ERROR; public static final int FRAMEBITS; public static final int HEIGHT; public static final int PROPERTIES; public static final int SOMEBITS; public static final int WIDTH; // Public Instance Methods public abstract boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height); }
Implemented By: Component
Passed To: Component.checkImage(), Component.prepareImage(), ComponentPeer.checkImage(), ComponentPeer.prepareImage(), Graphics.drawImage(), Image.getHeight(), Image.getProperty(), Image.getWidth(), Toolkit.checkImage(), Toolkit.prepareImage()
java.awt.image.ImageFilter (JDK 1.0)
java.awt.image.ImageProducer (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_08.htm [20/12/2001 11:01:01]
[Chapter 21] 21.11 java.awt.image.MemoryImageSource (JDK 1.0)
Chapter 21 The java.awt.image Package
21.11 java.awt.image.MemoryImageSource (JDK 1.0) This class is an ImageProducer that produces an image from data stored in memory. The various constructors specify image data, color model, array offset, scan line length, and properties in slightly different ways. The instance methods implement the standard ImageProducer interface that allows an ImageConsumer object to register interest in the image. public class MemoryImageSource extends Object implements ImageProducer { // Public Constructors public MemoryImageSource(int w, int h, ColorModel cm, byte[] pix, int off, int scan); public MemoryImageSource(int w, int h, ColorModel cm, byte[] pix, int off, int scan, Hashtable props); public MemoryImageSource(int w, int h, ColorModel cm, int[] pix, int off, int scan); public MemoryImageSource(int w, int h, ColorModel cm, int[] pix, int off, int scan, Hashtable props); public MemoryImageSource(int w, int h, int[] pix, int off, int scan); public MemoryImageSource(int w, int h, int[] pix, int off, int scan, Hashtable props); // Public Instance Methods public synchronized void addConsumer(ImageConsumer ic); // From ImageProducer public synchronized boolean isConsumer(ImageConsumer ic); // From ImageProducer 1.1 public void newPixels(); 1.1 public synchronized void newPixels(int x, int y, int w, int h); 1.1 public synchronized void newPixels(int x, int y, int w, int h, boolean framenotify); 1.1 public synchronized void newPixels(byte[] newpix, ColorModel newmodel, int offset, int scansize); 1.1 public synchronized void newPixels(int[] newpix, ColorModel newmodel, int offset, int scansize); public synchronized void removeConsumer(ImageConsumer ic); // From ImageProducer public void requestTopDownLeftRightResend(ImageConsumer ic); // From ImageProducer 1.1 public synchronized void setAnimated(boolean animated); 1.1 public synchronized void setFullBufferUpdates(boolean fullbuffers); public void startProduction(ImageConsumer ic); // From ImageProducer }
http://localhost/java/javaref/javanut/ch21_11.htm (1 of 2) [20/12/2001 11:01:01]
[Chapter 21] 21.11 java.awt.image.MemoryImageSource (JDK 1.0)
java.awt.image.IndexColorModel (JDK 1.0)
java.awt.image.PixelGrabber (JDK 1.0)
http://localhost/java/javaref/javanut/ch21_11.htm (2 of 2) [20/12/2001 11:01:01]
[Chapter 23] 23.7 java.beans.IndexedPropertyDescriptor (JDK 1.1)
Chapter 23 The java.beans Package
23.7 java.beans.IndexedPropertyDescriptor (JDK 1.1) An IndexedPropertyDescriptor object is a type of PropertyDescriptor that describes a Java bean property that is (or behaves like) an array. The BeanInfo class for a Java bean optionally creates and initializes IndexedPropertyDescriptor objects to describe the indexed properties that the bean supports. Typically, only application builders and similar tools use the descriptor objects to obtain indexed property description information. You create an IndexedPropertyDescriptor by specifying the name of the indexed property and the Class object for the bean. If you have not followed the standard "design patterns" for accessor method naming, you may also specify the accessor methods for the property, either as method names or as java.lang.reflect.Method objects. Once you have created an IndexedPropertyDescriptor object, you can use the methods of PropertyDescriptor and FeatureDescriptor to provide additional information about the indexed property. public class IndexedPropertyDescriptor extends PropertyDescriptor { // Public Constructors public IndexedPropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException; public IndexedPropertyDescriptor(String propertyName, Class beanClass, String getterName, public IndexedPropertyDescriptor'u'String setterName, String indexedGetterName, public IndexedPropertyDescriptor'u'String indexedSetterName) throws IntrospectionException; public IndexedPropertyDescriptor(String propertyName, Method getter, Method setter, Method indexedGetter, public IndexedPropertyDescriptor'u'Method indexedSetter) throws IntrospectionException; // Public Instance Methods public Class getIndexedPropertyType(); public Method getIndexedReadMethod(); public Method getIndexedWriteMethod(); }
Hierarchy: Object->FeatureDescriptor->PropertyDescriptor->IndexedPropertyDescriptor
java.beans.FeatureDescriptor (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_07.htm [20/12/2001 11:01:01]
java.beans.IntrospectionException (JDK 1.1)
[Chapter 25] 25.29 java.lang.IndexOutOfBoundsException (JDK 1.0)
Chapter 25 The java.lang Package
25.29 java.lang.IndexOutOfBoundsException (JDK 1.0) Signals that an index is out of bounds. See the subclasses ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException. public class IndexOutOfBoundsException extends RuntimeException { // Public Constructors public IndexOutOfBoundsException(); public IndexOutOfBoundsException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->IndexOutOfBoundsException
Extended By: ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException
java.lang.IncompatibleClassChangeError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_29.htm [20/12/2001 11:01:02]
java.lang.InstantiationError (JDK 1.0)
[Chapter 31] 31.11 java.util.zip.Inflater (JDK 1.1)
Chapter 31 The java.util.zip Package
31.11 java.util.zip.Inflater (JDK 1.1) This class implements the general ZLIB data decompression algorithm used by gzip, PKZip, and other data compression applications. It decompresses or "inflates" data compressed through the Deflater class. The important methods of this class are setInput(), which specifies input data to be decompressed, and inflate(), which decompresses the input data into an output buffer. A number of other methods exist so that this class can be used for stream-based decompression, as it is in the higher-level classes such as GZIPInputStream and ZipInputStream. These stream-based classes are sufficient in most cases. Most applications do not need to use Inflater directly. public class Inflater extends Object { // Public Constructors public Inflater(boolean nowrap); public Inflater(); // Public Instance Methods public synchronized native void end(); public synchronized boolean finished(); public synchronized native int getAdler(); public synchronized int getRemaining(); public synchronized native int getTotalIn(); public synchronized native int getTotalOut(); public synchronized native int inflate(byte[] b, int off, int len) throws DataFormatException; public int inflate(byte[] b) throws DataFormatException; public synchronized boolean needsDictionary(); public synchronized boolean needsInput(); public synchronized native void reset(); public synchronized native void setDictionary(byte[] b, int off, int len); public void setDictionary(byte[] b); public synchronized void setInput(byte[] b, int off, int len); public void setInput(byte[] b); // Protected Instance Methods protected void finalize(); // Overrides Object }
Passed To: InflaterInputStream()
http://localhost/java/javaref/javanut/ch31_11.htm (1 of 2) [20/12/2001 11:01:04]
[Chapter 31] 31.11 java.util.zip.Inflater (JDK 1.1)
Type Of: InflaterInputStream.inf
java.util.zip.GZIPOutputStream (JDK 1.1)
java.util.zip.InflaterInputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_11.htm (2 of 2) [20/12/2001 11:01:04]
[Chapter 31] 31.12 java.util.zip.InflaterInputStream (JDK 1.1)
Chapter 31 The java.util.zip Package
31.12 java.util.zip.InflaterInputStream (JDK 1.1) This class is a subclass of java.io.FilterInputStream; it reads a specified stream of compressed input data (typically one that was written with DeflaterOutputStream or a subclass) and "filters" that data by uncompressing ("inflating") it. To create an InflaterInputStream, you must specify the input stream it is to read from, and also an Inflater object that is to perform the uncompresssion. Once an InflaterInputStream is created, the read() and skip() methods are the same as those of other input streams. Note that the InflaterInputStream uncompresses raw data. Applications often prefer one of its subclasses, GZIPInputStream or ZipInputStream, which work with compressed data written in the standard gzip and PKZip file formats. public class InflaterInputStream extends FilterInputStream { // Public Constructors public InflaterInputStream(InputStream in, Inflater inf, int size); public InflaterInputStream(InputStream in, Inflater inf); public InflaterInputStream(InputStream in); // Protected Instance Variables protected byte[] buf; protected Inflater inf; protected int len; // Public Instance Methods public int read() throws IOException; // Overrides FilterInputStream public int read(byte[] b, int off, int len) throws IOException; // Overrides FilterInputStream public long skip(long n) throws IOException; // Overrides FilterInputStream // Protected Instance Methods protected void fill() throws IOException; }
Hierarchy: Object->InputStream->FilterInputStream->InflaterInputStream
Extended By: GZIPInputStream, ZipInputStream
http://localhost/java/javaref/javanut/ch31_12.htm (1 of 2) [20/12/2001 11:01:04]
[Chapter 31] 31.12 java.util.zip.InflaterInputStream (JDK 1.1)
java.util.zip.Inflater (JDK 1.1)
java.util.zip.ZipEntry (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_12.htm (2 of 2) [20/12/2001 11:01:04]
[Chapter 24] 24.54 java.io.PushbackInputStream (JDK 1.0)
Chapter 24 The java.io Package
24.54 java.io.PushbackInputStream (JDK 1.0) This class is a FilterInputStream that implements a one-byte pushback buffer or, in Java 1.1, a pushback buffer of a specified length. The unread() methods "push" bytes back into the stream--these bytes are the first ones read by the next call to a read() method. This class is sometimes useful when writing parsers. See also PushbackReader. public class PushbackInputStream extends FilterInputStream { // Public Constructors 1.1 public PushbackInputStream(InputStream in, int size); public PushbackInputStream(InputStream in); // Protected Instance Variables 1.1 protected byte[] buf; 1.1 protected int pos; // Public Instance Methods public int available() throws IOException; // Overrides FilterInputStream public boolean markSupported(); // Overrides FilterInputStream public int read() throws IOException; // Overrides FilterInputStream public int read(byte[] b, int off, int len) throws IOException; // Overrides FilterInputStream public void unread(int b) throws IOException; 1.1 public void unread(byte[] b, int off, int len) throws IOException; 1.1 public void unread(byte[] b) throws IOException; }
Hierarchy: Object->InputStream->FilterInputStream->PushbackInputStream
java.io.PrintWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_54.htm [20/12/2001 11:01:04]
java.io.PushbackReader (JDK 1.1)
[Chapter 24] 24.58 java.io.SequenceInputStream (JDK 1.0)
Chapter 24 The java.io Package
24.58 java.io.SequenceInputStream (JDK 1.0) This class provides a way of seamlessly concatenating the data from two or more input streams. It provides an InputStream interface to a sequence of InputStream objects. Data are read from the streams in the order in which the streams are specified. When the end of one stream is reached, data are automatically read from the next stream. This class might be useful, for example, when implementing an "include file" facility for a parser of some sort. public class SequenceInputStream extends InputStream { // Public Constructors public SequenceInputStream(Enumeration e); public SequenceInputStream(InputStream s1, InputStream s2); // Public Instance Methods 1.1 public int available() throws IOException; // Overrides InputStream public void close() throws IOException; // Overrides InputStream public int read() throws IOException; // Defines InputStream public int read(byte[] buf, int pos, int len) throws IOException; // Overrides InputStream }
Hierarchy: Object->InputStream->SequenceInputStream
java.io.Reader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_58.htm [20/12/2001 11:01:04]
java.io.Serializable (JDK 1.1)
[Chapter 24] 24.60 java.io.StreamCorruptedException (JDK 1.1)
Chapter 24 The java.io Package
24.60 java.io.StreamCorruptedException (JDK 1.1) This exception signals that the data stream being read by an ObjectInputStream has been corrupted and does not contain valid serialized object data. public class StreamCorruptedException extends ObjectStreamException { // Public Constructors public StreamCorruptedException(String reason); public StreamCorruptedException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ObjectStreamException->StreamCorruptedException
Thrown By: ObjectInputStream(), ObjectInputStream.readStreamHeader()
java.io.Serializable (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_60.htm [20/12/2001 11:01:05]
java.io.StreamTokenizer (JDK 1.0)
[Chapter 24] 24.62 java.io.StringBufferInputStream (JDK 1.0; Deprecated.)
Chapter 24 The java.io Package
24.62 java.io.StringBufferInputStream (JDK 1.0; Deprecated.) This class is a subclass of InputStream in which input bytes come from the characters of a specified String object. This class does not correctly convert the characters of a StringBuffer into bytes, and is deprecated in Java 1.1. Use StringReader instead to correctly convert characters into bytes, or use ByteArrayInputStream to read bytes from an array of bytes. public class StringBufferInputStream extends InputStream { // Public Constructor public StringBufferInputStream(String s); // Protected Instance Variables protected String buffer; protected int count; protected int pos; // Public Instance Methods public synchronized int available(); // Overrides InputStream public synchronized int read(); // Defines InputStream public synchronized int read(byte[] b, int off, int len); // Overrides InputStream public synchronized void reset(); // Overrides InputStream public synchronized long skip(long n); // Overrides InputStream }
Hierarchy: Object->InputStream->StringBufferInputStream
java.io.StreamTokenizer (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_62.htm [20/12/2001 11:01:05]
java.io.StringReader (JDK 1.1)
[Chapter 18] 18.33 java.awt.Insets (JDK 1.0)
Chapter 18 The java.awt Package
18.33 java.awt.Insets (JDK 1.0) This class holds four values that represent the top, left, bottom, and right margins, in pixels, of a Container or other Component. Objects of this type may be specified in a GridBagConstraints layout object, and are returned by Container.insets(), which queries the margins of a container. public class Insets extends Object implements Cloneable, Serializable { // Public Constructor public Insets(int top, int left, int bottom, int right); // Public Instance Variables public int bottom; public int left; public int right; public int top; // Public Instance Methods public Object clone(); // Overrides Object 1.1 public boolean equals(Object obj); // Overrides Object public String toString(); // Overrides Object }
Returned By: Container.getInsets(), Container.insets(), ContainerPeer.getInsets(), ContainerPeer.insets()
Type Of: GridBagConstraints.insets
java.awt.Image (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_33.htm [20/12/2001 11:01:05]
java.awt.ItemSelectable (JDK 1.1)
[Chapter 10] 10.2 A Simple Bean
Chapter 10 Java Beans
10.2 A Simple Bean As noted above, the AWT components in Java 1.1 can all function as beans. When you write a custom GUI component, it is not difficult to make it function as a bean as well. Example 10.1 shows the definition of a custom component, MultiLineLabel, that is also a bean. This component is like the standard Label component, but it can display labels that contain more than one line of text. Much of the code in this example is taken up with the mechanics of breaking the label into separate lines and measuring the size of each of those lines. From the standpoint of custom AWT components, however, the most important code is in several required methods that make any component work correctly. First, there is the paint() method, of course. All components (including applets) use this method to display themselves on the screen. Second, the getPreferredSize() and getMinimumSize() methods return the preferred and minimum sizes for the component. These methods must be implemented so that layout managers can correctly lay the component out. (Note, though, that for compatibility with Java 1.0, this example defines the deprecated preferredSize() and minimumSize() methods instead.) MultiLineLabel extends Canvas, which is a blank component intended primarily for subclassing. When a component is a subclass of Canvas, it is typically given its own native window in the underlying window system. In Java 1.1, however, it is possible to define "lightweight" custom components by extending Component instead of Canvas. A lightweight component does not have its own native window in the underlying window system. What makes this component a bean is that all of its properties have get and set accessor methods. Because MultiLineLabel does not respond to user input in any way, it does not define any events, so there are no event listener registration methods required. Although it is not a formal requirement for a bean, most beanboxes attempt to instantiate a bean by invoking its no-argument constructor. Thus, a bean should define a constructor that expects no arguments. Example 10.1: A Custom AWT Component and JavaBean package oreilly.beans.yesno; import java.awt.*; import java.util.*; /** * A custom component that displays multiple lines of text with specified * margins and alignment. In Java 1.1, we could extend Component instead * of Canvas, making this a more efficient "Lightweight component." */ public class MultiLineLabel extends Canvas { // User-specified attributes protected String label; // The label, not broken into lines http://localhost/java/javaref/javanut/ch10_02.htm (1 of 5) [20/12/2001 11:01:06]
[Chapter 10] 10.2 A Simple Bean
protected int margin_width; // Left and right margins protected int margin_height; // Top and bottom margins protected int alignment; // The alignment of the text public static final int LEFT = 0, CENTER = 1, RIGHT = 2; // alignment values // Computed state values protected int num_lines; // The number of lines protected String[] lines; // The label, broken into lines protected int[] line_widths; // How wide each line is protected int max_width; // The width of the widest line protected int line_height; // Total height of the font protected int line_ascent; // Font height above baseline protected boolean measured = false; // Have the lines been measured? // Here are five versions of the constructor. public MultiLineLabel(String label, int margin_width, int margin_height, int alignment) { this.label = label; // Remember all the properties. this.margin_width = margin_width; this.margin_height = margin_height; this.alignment = alignment; newLabel(); // Break the label up into lines. } public MultiLineLabel(String label, int margin_width, int margin_height) { this(label, margin_width, margin_height, LEFT); } public MultiLineLabel(String label, int alignment) { this(label, 10, 10, alignment); } public MultiLineLabel(String label) { this(label, 10, 10, LEFT); } public MultiLineLabel() { this(""); } // Methods to set and query the various attributes of the component. // Note that some query methods are inherited from the superclass. public void setLabel(String label) { this.label = label; newLabel(); // Break the label into lines. measured = false; // Note that we need to measure lines. repaint(); // Request a redraw. } public void setFont(Font f) { super.setFont(f); // Tell our superclass about the new font. measured = false; // Note that we need to remeasure lines. repaint(); // Request a redraw. } public void setForeground(Color c) { super.setForeground(c); // Tell our superclass about the new color. repaint(); // Request a redraw (size is unchanged). } public void setAlignment(int a) { alignment = a; repaint(); } public void setMarginWidth(int mw) { margin_width = mw; repaint(); } public void setMarginHeight(int mh) { margin_height = mh; repaint(); } public String getLabel() { return label; }
http://localhost/java/javaref/javanut/ch10_02.htm (2 of 5) [20/12/2001 11:01:06]
[Chapter 10] 10.2 A Simple Bean
public int getAlignment() { return alignment; } public int getMarginWidth() { return margin_width; } public int getMarginHeight() { return margin_height; } /** * This method is called by a layout manager when it wants to * know how big we'd like to be. In Java 1.1, getPreferredSize() is * the preferred version of this method. We use this deprecated version * so that this component can interoperate with 1.0 components. */ public Dimension preferredSize() { if (!measured) measure(); return new Dimension(max_width + 2*margin_width, num_lines * line_height + 2*margin_height); } /** * This method is called when the layout manager wants to know * the bare minimum amount of space we need to get by. * For Java 1.1, we'd use getMinimumSize(). */ public Dimension minimumSize() { return preferredSize(); } /** * This method draws the label (same method that applets use). * Note that it handles the margins and the alignment, but that * it doesn't have to worry about the color or font--the superclass * takes care of setting those in the Graphics object we're passed. */ public void paint(Graphics g) { int x, y; Dimension size = this.size(); // Use getSize() in Java 1.1. if (!measured) measure(); y = line_ascent + (size.height - num_lines * line_height)/2; for(int i = 0; i < num_lines; i++, y += line_height) { switch(alignment) { default: case LEFT: x = margin_width; break; case CENTER: x = (size.width - line_widths[i])/2; break; case RIGHT: x = size.width - margin_width - line_widths[i]; break; } g.drawString(lines[i], x, y); } } /** This internal method breaks a specified label up into an array of lines. * It uses the StringTokenizer utility class. */ protected synchronized void newLabel() { StringTokenizer t = new StringTokenizer(label, "\n"); num_lines = t.countTokens(); lines = new String[num_lines]; line_widths = new int[num_lines]; for(int i = 0; i < num_lines; i++) lines[i] = t.nextToken(); }
http://localhost/java/javaref/javanut/ch10_02.htm (3 of 5) [20/12/2001 11:01:06]
[Chapter 10] 10.2 A Simple Bean
/** This internal method figures out how big the font is, and how wide each * line of the label is, and how wide the widest line is. */ protected synchronized void measure() { FontMetrics fm = this.getToolkit().getFontMetrics(this.getFont()); line_height = fm.getHeight(); line_ascent = fm.getAscent(); max_width = 0; for(int i = 0; i < num_lines; i++) { line_widths[i] = fm.stringWidth(lines[i]); if (line_widths[i] > max_width) max_width = line_widths[i]; } measured = true; } }
Packaging a Bean To prepare a bean for use in a beanbox, you must package it up in a JAR file, along with any other classes or resource files it requires. (JAR files are "Java archives"; they were introduced in Chapter 6, Applets.) Because a single bean can have many auxiliary files, and because a JAR file can contain multiple beans, the manifest of the JAR file must define which of the JAR file entries are beans. You create a JAR file with c option to the jar command. When you use the m option in conjunction with c, it tells jar to read a partial manifest file that you specify. jar uses the information in your partially-specified manifest file when creating the complete manifest for the JAR file. To identify a class file as a bean, you simply add the following line to the file's manifest entry: Java-Bean: True So, to package up the MultiLineLabel class in a JAR file, you must first create a manifest "stub" file. Create a file, perhaps named manifest.stub, with the following contents: Name: oreilly/beans/MultiLineLabel.class Java-Bean: True Note that the forward slashes in the manifest file should not be changed to backward slashes on Windows systems. The format of the JAR manifest file requires forward slashes to separate directories regardless of the platform. Having created this partial manifest file, we can now go ahead and create the JAR file: % jar cfm MultiLineLabel.jar manifest.stub oreilly/beans/MultiLineLabel.class (On a Windows system, you do need to replace the forward slashes with backslashes in this command line.) If this bean required any auxiliary files, we would specify them on the end of the jar command line, along with the class file for the bean.
Installing a Bean The procedure for installing a bean depends entirely upon the beanbox tool that you are using. For the beanbox tool shipped with the BDK, all you need to do is to copy the bean's JAR file into the jars/ directory within the BDK directory. Once you have done this, the bean will appear on the palette of beans every time you start up the application. Alternatively, you can also load a bean's JAR file at runtime by selecting the Load JAR option from the File menu of beanbox.
http://localhost/java/javaref/javanut/ch10_02.htm (4 of 5) [20/12/2001 11:01:06]
[Chapter 10] 10.2 A Simple Bean
Bean Basics
http://localhost/java/javaref/javanut/ch10_02.htm (5 of 5) [20/12/2001 11:01:06]
A More Complex Bean
[Chapter 25] 25.33 java.lang.InternalError (JDK 1.0)
Chapter 25 The java.lang Package
25.33 java.lang.InternalError (JDK 1.0) Signals an internal error in the Java interpreter. public class InternalError extends VirtualMachineError { // Public Constructors public InternalError(); public InternalError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->VirtualMachineError->InternalError
java.lang.Integer (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_33.htm [20/12/2001 11:01:06]
java.lang.InterruptedException (JDK 1.0)
[Chapter 25] 25.61 java.lang.Thread (JDK 1.0)
Chapter 25 The java.lang Package
25.61 java.lang.Thread (JDK 1.0) This class encapsulates all the information about a single thread of control running on the Java interpreter. To create a thread, you must pass a Runnable object (i.e., an object that implements the Runnable interface by defining a run() method) to the Thread constructor, or you must subclass Thread so that it defines its own run() method. The run() method of the Thread or of the specified Runnable object is the "body" of the thread. It begins executing when the start() method of the Thread object is called. The thread runs until the run() method returns or until the stop() method of its Thread object is called. The static methods of this class operate on the currently running thread. The instance methods may be called from one thread to operate on a different thread. start() starts a thread running. stop() stops it by throwing a ThreadDeath error. suspend() temporarily halts a thread. resume() allows it to resume. sleep() makes the current thread stop for a specified amount of time. yield() makes the current thread give up control to any other threads of equal priority that are waiting to run. join() waits for a thread to die. interrupt() wakes up a waiting or sleeping thread (with an InterruptedException) or sets an "interrupted" flag on a non-sleeping thread. A thread can test its own "interrupted" flag with interrupted() or can test the flag of another thread with isInterrupted(). The Object wait() method makes the current thread block until the object's notify() method is called by another thread. public class Thread extends Object implements Runnable { // Public Constructors public Thread(); public Thread(Runnable target); public Thread(ThreadGroup group, Runnable target); public Thread(String name); public Thread(ThreadGroup group, String name); public Thread(Runnable target, String name); public Thread(ThreadGroup group, Runnable target, String name); // Constants public static final int MAX_PRIORITY; public static final int MIN_PRIORITY; public static final int NORM_PRIORITY; // Class Methods public static int activeCount(); public static native Thread currentThread(); public static void dumpStack(); public static int enumerate(Thread[] tarray); public static boolean interrupted(); public static native void sleep(long millis) throws InterruptedException; public static void sleep(long millis, int nanos) throws InterruptedException; public static native void yield(); // Public Instance Methods public void checkAccess();
http://localhost/java/javaref/javanut/ch25_61.htm (1 of 2) [20/12/2001 11:01:06]
[Chapter 25] 25.61 java.lang.Thread (JDK 1.0)
public native int countStackFrames(); public void destroy(); public final String getName(); public final int getPriority(); public final ThreadGroup getThreadGroup(); public void interrupt(); public final native boolean isAlive(); public final boolean isDaemon(); public boolean isInterrupted(); public final synchronized void join(long millis) throws InterruptedException; public final synchronized void join(long millis, int nanos) throws InterruptedException; public final void join() throws InterruptedException; public final void resume(); public void run(); // From Runnable public final void setDaemon(boolean on); public final void setName(String name); public final void setPriority(int newPriority); public synchronized native void start(); public final void stop(); public final synchronized void stop(Throwable o); public final void suspend(); public String toString(); // Overrides Object }
Passed To: SecurityManager.checkAccess(), Thread.enumerate(), ThreadGroup.enumerate(), ThreadGroup.uncaughtException()
Returned By: Thread.currentThread()
java.lang.System (JDK 1.0)
java.lang.ThreadDeath (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_61.htm (2 of 2) [20/12/2001 11:01:06]
[Chapter 25] 25.34 java.lang.InterruptedException (JDK 1.0)
Chapter 25 The java.lang Package
25.34 java.lang.InterruptedException (JDK 1.0) Signals that the thread has been interrupted. public class InterruptedException extends Exception { // Public Constructors public InterruptedException(); public InterruptedException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->InterruptedException
Thrown By: EventQueue.getNextEvent(), MediaTracker.waitForAll(), MediaTracker.waitForID(), Object.wait(), PixelGrabber.grabPixels(), Process.waitFor(), Thread.join(), Thread.sleep()
java.lang.InternalError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_34.htm [20/12/2001 11:01:07]
java.lang.LinkageError (JDK 1.0)
[Chapter 24] 24.30 java.io.InterruptedIOException (JDK 1.0)
Chapter 24 The java.io Package
24.30 java.io.InterruptedIOException (JDK 1.0) An IOException that signals that an input or output operation was interrupted. The bytesTransferred variable contains the number of bytes read or written before the operation was interrupted. public class InterruptedIOException extends IOException { // Public Constructors public InterruptedIOException(); public InterruptedIOException(String s); // Public Instance Variables public int bytesTransferred; }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->InterruptedIOException
java.io.InputStreamReader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_30.htm [20/12/2001 11:01:07]
java.io.InvalidClassException (JDK 1.1)
[Chapter 4] 4.8 Reflection
Chapter 4 What's New in Java 1.1
4.8 Reflection Reflection in Java 1.1 refers to the ability of Java classes to reflect upon themselves, or to "look inside themselves." The java.lang.Class class has been greatly enhanced in Java 1.1. It now includes methods that return the fields, methods, and constructors defined by a class. These items are returned as objects of type Field, Method, and Constructor, respectively. These new classes are part of the new java.lang.reflect package, and they each provide methods to obtain complete information about the field, method, or constructor they represent. For example, the Method object has methods to query the name, the parameter types, and the return type of the method it represents. Chapter 12, Reflection provides some examples of using the Reflection API. Besides allowing a program to inspect the members of a class, the java.lang.reflect package also allows a program to manipulate these fields and methods. The Field class defines methods that get and set the value of the represented field for any given object of the appropriate type. Similarly, the Method object defines an invoke() method that allows the represented method to be invoked, and the Constructor class defines a newInstance() method that creates a new object and invokes the represented constructor on it. java.lang.reflect also defines an Array class. It does not represent a specific array, but defines static methods that read and write array elements and dynamically create new arrays. With the addition of reflection, the Class class has been expanded to represent not just Java classes, but any Java type, including primitive types and array types. There is a special Class object that represents each of the eight Java primitive types, and another special Class object that represents the void type. These special Class objects are available as constants in the wrapper objects for the primitive types. Integer.TYPE is a Class object that represents the int type, for example, and Void.TYPE is a Class object that represents the void type. Finally, new Java language syntax makes it easier to obtain a Class object that represents a Java class. If you follow the name of a class, interface, or other type with .class, Java evaluates that expression and returns the corresponding Class object. So, for example, the following two expressions are equivalent: String.class Class.forName("java.lang.String")
http://localhost/java/javaref/javanut/ch04_08.htm (1 of 2) [20/12/2001 11:01:07]
[Chapter 4] 4.8 Reflection
Note that this syntax also works with primitive type names: you can write short.class, for example, which returns the same value as Short.TYPE.
Object Serialization
http://localhost/java/javaref/javanut/ch04_08.htm (2 of 2) [20/12/2001 11:01:07]
Java Beans
[Chapter 23] 23.8 java.beans.IntrospectionException (JDK 1.1)
Chapter 23 The java.beans Package
23.8 java.beans.IntrospectionException (JDK 1.1) Signals that introspection on a Java bean could not be completed. Typically this indicates a bug in the way the bean or its associated BeanInfo class is defined. public class IntrospectionException extends Exception { // Public Constructor public IntrospectionException(String mess); }
Hierarchy: Object->Throwable(Serializable)->Exception->IntrospectionException
Thrown By: EventSetDescriptor(), IndexedPropertyDescriptor(), Introspector.getBeanInfo(), PropertyDescriptor()
java.beans.IndexedPropertyDescriptor (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_08.htm [20/12/2001 11:01:08]
java.beans.Introspector (JDK 1.1)
[Chapter 24] 24.32 java.io.InvalidObjectException (JDK 1.1)
Chapter 24 The java.io Package
24.32 java.io.InvalidObjectException (JDK 1.1) This exception should be thrown by the validateObject() method of an object that implements the ObjectInputValidation interface when a deserialized object fails an input validation test for any reason. public class InvalidObjectException extends ObjectStreamException { // Public Constructor public InvalidObjectException(String reason); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ObjectStreamException->InvalidObjectException
Thrown By: ObjectInputStream.registerValidation(), ObjectInputValidation.validateObject()
java.io.InvalidClassException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_32.htm [20/12/2001 11:01:08]
java.io.IOException (JDK 1.0)
[Chapter 26] 26.4 java.lang.reflect.InvocationTargetException (JDK 1.1)
Chapter 26 The java.lang.reflect Package
26.4 java.lang.reflect.InvocationTargetException (JDK 1.1) An object of this class is thrown by Method.invoke() and Constructor.newInstance() when an exception is thrown by the method or constructor invoked through those methods. The InvocationTargetException class serves as a wrapper around the object that was thrown; that object can be retrieved with the getTargetException() method. public class InvocationTargetException extends Exception { // Public Constructors public InvocationTargetException(Throwable target); public InvocationTargetException(Throwable target, String s); // Protected Constructor protected InvocationTargetException(); // Public Instance Methods public Throwable getTargetException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->InvocationTargetException
Thrown By: Constructor.newInstance(), Method.invoke()
java.lang.reflect.Field (JDK 1.1)
http://localhost/java/javaref/javanut/ch26_04.htm [20/12/2001 11:01:08]
java.lang.reflect.Member (JDK 1.1)
[Chapter 24] 24.33 java.io.IOException (JDK 1.0)
Chapter 24 The java.io Package
24.33 java.io.IOException (JDK 1.0) Signals that an exceptional condition has occurred during input or output. This class has several more specific subclasses. See EOFException, FileNotFoundException, InterruptedIOException, and UTFDataFormatException. public class IOException extends Exception { // Public Constructors public IOException(); public IOException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException
Extended By: CharConversionException, EOFException, FileNotFoundException, InterruptedIOException, MalformedURLException, ObjectStreamException, ProtocolException, SocketException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedEncodingException, UTFDataFormatException, ZipException
Thrown By: Many methods
java.io.InvalidObjectException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_33.htm [20/12/2001 11:01:09]
java.io.LineNumberInputStream (JDK 1.0; Deprecated.)
[Chapter 8] 8.2 Popup Menus and Menu Shortcuts
Chapter 8 New AWT Features
8.2 Popup Menus and Menu Shortcuts In Java 1.1, the AWT has some welcome new menuing features. As you can see from Figure 8.1, popup menus (and submenus) are now supported by the AWT. Not shown in the figure, but also supported, are keyboard menu shortcuts, which in this example are attached to the menu items in the pulldown menu. Popup menus are represented by the PopupMenu class. PopupMenu is a subclass of Menu and is used very much like a Menu pane is. To create a popup menu, create a PopupMenu, and add MenuItem objects to it, just as you would do with a regular menu pane. Instead of adding a popup menu to a menubar, however, you must add it to the component over which it pops up. You do this with the add() method of the target component. As part of the addition of popup menus in Java 1.1, a new add() method has been added to the Component class. This new version of add() accepts a single PopupMenu argument. Here's a fragment of the Scribble() constructor in Example 8.1 that creates a popup menu and adds it to a component: // Create the popup menu using a loop. Note the separation of menu // "action command" string from menu label. Good for internationalization. String[] labels = new String[] { "Clear", "Print", "Save", "Load", "Cut", "Copy", "Paste" }; String[] commands = new String[] { "clear", "print", "save", "load", "cut", "copy", "paste" }; popup = new PopupMenu(); // Create the menu. for(int i = 0; i < labels.length; i++) { MenuItem mi = new MenuItem(labels[i]); // Create a menu item. mi.setActionCommand(commands[i]); // Set its action command. mi.addActionListener(this); // And its action listener. popup.add(mi); // Add item to the popup menu. } Menu colors = new Menu("Color"); // Create a submenu. popup.add(colors); // And add it to the popup. String[] colornames = new String[] { "Black", "Red", "Green", "Blue"}; for(int i = 0; i < colornames.length; i++) { MenuItem mi = new MenuItem(colornames[i]); // Create the submenu items mi.setActionCommand(colornames[i]); // in the same way. mi.addActionListener(this); colors.add(mi); }
http://localhost/java/javaref/javanut/ch08_02.htm (1 of 3) [20/12/2001 11:01:09]
[Chapter 8] 8.2 Popup Menus and Menu Shortcuts
// Finally, register the popup menu with the component it appears over. this.add(popup); In addition to creating and registering a popup menu, you must also arrange for it to pop up at the appropriate time. Popup menus are always triggered by mouse events, but the particular "popup trigger" event varies from platform to platform. To hide this platform dependency, the MouseEvent class defines a isPopupTrigger() method that you can use to determine whether a popup menu should be "posted" (i.e., popped up) in response to a given event. To post a menu, call its show() method, specifying the component it should appear over and also the coordinates (from the mouse event) that it should appear at. The processMouseEvent() method of Example 8.1 handles posting the popup menu: public void processMouseEvent(MouseEvent e) { if (e.isPopupTrigger()) popup.show(this, e.getX(), e.getY()); else if (e.getID() == MouseEvent.MOUSE_PRESSED) { last_x = (short)e.getX(); last_y = (short)e.getY(); } else super.processMouseEvent(e); // Pass other event }
// If popup trigger, // pop up the menu. // Save position. types on.
Event handling for the menu items in a PopupMenu is the same as it is for pulldown menu items. The simplest technique is to specify the same action listener object for each menu item, but specify a different string as the "action command" for each item. Then, the actionPerformed() method of the listener can dispatch the ActionEvent based on the command string it contains. The actionPerformed() method of the Scribble class in Example 8.1 shows this technique: public void actionPerformed(ActionEvent event) { // Get the "action command" of the event, and dispatch based on that. // This method calls a lot of the interesting methods in this class. String command = event.getActionCommand(); if (command.equals("clear")) clear(); else if (command.equals("print")) print(); else if (command.equals("save")) save(); else if (command.equals("load")) load(); else if (command.equals("cut")) cut(); else if (command.equals("copy")) copy(); else if (command.equals("paste")) paste(); else if (command.equals("Black")) current_color = Color.black; else if (command.equals("Red")) current_color = Color.red; else if (command.equals("Green")) current_color = Color.green; else if (command.equals("Blue")) current_color = Color.blue; } The MenuShortcut class is another important addition to the menu functionality of Java. Any MenuItem object may have a MenuShortcut object specified that allows the user to invoke the menu item with a keyboard command. You create a MenuShortcut object by specifying the key code of the key to act as the shortcut, and, optionally, whether the Shift modifier is required to invoke the shortcut. The key should be specified as one of the VK_ virtual key constants defined by the KeyEvent class. Note that you do not specify any Ctrl, Alt, or Meta modifier for a shortcut. Like the "popup trigger" event, the standard keyboard modifier for
http://localhost/java/javaref/javanut/ch08_02.htm (2 of 3) [20/12/2001 11:01:09]
[Chapter 8] 8.2 Popup Menus and Menu Shortcuts
menu shortcuts is platform-dependent, so Java hides this from you. Consider the following menu shortcut, for example: MenuShortcut s = new MenuShortcut(KeyEvent.VK_C); This shortcut is invoked as Ctrl-C on a Windows platform or by using the special "Command" modifier on a Mac. The following fragment of the ScribbleFrame() constructor of Example 8.1 creates menu shortcuts and associates them with menu items: // Create three menu items, with menu shortcuts, and add to the menu. MenuItem n, c, q; file.add(n = new MenuItem("New Window", new MenuShortcut(KeyEvent.VK_N))); file.add(c = new MenuItem("Close Window",new MenuShortcut(KeyEvent.VK_W))); file.addSeparator(); // Put a separator in the menu. file.add(q = new MenuItem("Quit", new MenuShortcut(KeyEvent.VK_Q)));
The ScrollPane Container
http://localhost/java/javaref/javanut/ch08_02.htm (3 of 3) [20/12/2001 11:01:09]
Printing
[Chapter 20] 20.16 java.awt.event.ItemListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.16 java.awt.event.ItemListener (JDK 1.1) This interface defines the method that an object must implement to "listen" for item events on AWT components. When an ItemEvent occurs, an AWT component notifies its registered ItemListener objects by invoking their itemStateChanged() methods. public abstract interface ItemListener extends EventListener { // Public Instance Methods public abstract void itemStateChanged(ItemEvent e); }
Implemented By: AWTEventMulticaster
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), Checkbox.addItemListener(), Checkbox.removeItemListener(), CheckboxMenuItem.addItemListener(), CheckboxMenuItem.removeItemListener(), Choice.addItemListener(), Choice.removeItemListener(), ItemSelectable.addItemListener(), ItemSelectable.removeItemListener(), List.addItemListener(), List.removeItemListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
java.awt.event.ItemEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_16.htm [20/12/2001 11:01:09]
java.awt.event.KeyAdapter (JDK 1.1)
[Chapter 16] jar
Chapter 16 JDK Tools
jar Name jar---Java Archive Tool
Availability JDK 1.1 and later.
Synopsis jar c|t|x[f][m][v] [jar-file] [manifest-file] [files]
Description jar is a tool that can be used to create and manipulate Java Archive (JAR) files. A JAR file is a compressed ZIP file with an additional "manifest" file. The syntax of the jar command is reminiscent of the Unix tar (tape archive) command. Options to jar are specified as a block of concatenated letters passed as a single argument, rather than as individual command-line arguments. The first letter of this option argument specifies what action jar is to perform and is required. Other option letters are optional. The various file arguments depend on which option letters are specified.
Options The first argument to jar is a set of letters that specifies the operation it is to perform. The first letter specifies the basic action and is required. The three possible values are the following: c http://localhost/java/javaref/javanut/ch16_02.htm (1 of 3) [20/12/2001 11:01:10]
[Chapter 16] jar
Create a new JAR archive. A list of input files and/or directories must be specified as the final arguments to jar. t List the contents of a JAR archive. If a JAR file is specified with the f option, its contents are listed. Otherwise, the JAR file to be listed is read from standard input. x Extract the contents of a JAR archive. If a JAR file is specified with the f option, its contents are extracted. Otherwise, the JAR file to be extracted is read from standard input. If the command is followed by a list of files and/or directories, only those files or directories are extracted from the JAR archive. Otherwise, all files in the archive are extracted. This action specifier can be followed by optional command letters: f This option indicates that the JAR file to create, list, or extract from is specified on the command line. When f is used with c, t, or x, the JAR filename must be the second command-line argument to jar (i.e., it must follow the block of option letters). If this option is not specified, jar writes the JAR file it creates to standard output, or reads a JAR file from standard input. m This option is only used with the c action. It indicates that jar should read the manifest file (partial or complete) specified on the command line and use that file as the basis for the manifest it includes in the JAR file. When this argument is specified after the f option, the manifest filename should follow the destination filename. If m precedes the f option, the manifest filename should precede the destination filename. v Verbose. If this letter is specified with a c action, jar lists each file it adds to the archive with compression statistics. If it is used with a t action, jar lists the size and modification date for each file in the archive, instead of simply listing the filename. If v is used with x, jar displays the name of each file it extracts from the archive.
Examples To create a simple JAR file: % jar cvf my.jar *.java images To list the contents of a file: % jar tvf your.jar To extract the manifest file from a JAR file:
http://localhost/java/javaref/javanut/ch16_02.htm (2 of 3) [20/12/2001 11:01:10]
[Chapter 16] jar
% jar xf the.jar META-INF/MANIFEST.MF To create a JAR file with a partial manifest specified: % jar cfmv YesNoDialog.jar manifest.stub oreilly/beans/yesno
See Also javakey
appletviewer
http://localhost/java/javaref/javanut/ch16_02.htm (3 of 3) [20/12/2001 11:01:10]
java
[Chapter 4] What's New in Java 1.1
Chapter 4
4. What's New in Java 1.1 Contents: Inner Classes The New AWT Event Model Deprecated Features Other AWT Improvements Internationalization Object Serialization Reflection Java Beans Enterprise APIs: JDBC, RMI, and Security Applet Changes New JDK Utilities Java 1.1 is a huge new release. The number of packages in the API has increased from 8 in Java 1.0 to 23 in Java 1.1, and the number of classes has more than doubled from 211 to 503. On top of these changes to the core Java class libraries, there have been some important changes to the language itself. Also, the JDK--the Java Development Kit from Sun--includes a number of new tools in version 1.1. The new features of Java 1.1 include: Inner classes Changes to the Java language itself to allow classes to be nested within each other, and within blocks of code. Java Beans A framework for defining reusable modular software components. Internationalization A variety of new features that make it possible to write programs that run around the globe. New event model A new model for handling events in graphical user interfaces that should make it easier to create
http://localhost/java/javaref/javanut/ch04_01.htm (1 of 6) [20/12/2001 11:01:10]
[Chapter 4] What's New in Java 1.1
those interfaces. Other new AWT features The Java 1.1 AWT includes support for printing, cut-and-paste, popup menus, menu shortcuts, and focus traversal. It has improved support for colors, fonts, cursors, scrolling, image manipulation, and clipping. Applets JAR files allow all of an applet's files to be grouped into a single archive. Digital signatures allow trusted applets to run with fewer security restrictions. The HTML <APPLET> tag has new features. Object serialization Objects can now be easily "serialized" and sent over the network or written to disk for persistent storage. Reflection Java programs can now "reflect" upon themselves or upon an arbitrary class to determine the methods and fields defined by the class, the arguments passed to a method, and so on. The Reflection API also allows the invocation of methods specified by name. Security Java 1.1 includes a new package that supports digital signatures, message digests, key management, and access control lists. Java Database Connectivity (JDBC) A new package that allows Java programs to send SQL queries to database servers. It includes a "bridge" that allows it to inter-operate with existing ODBC database servers. Remote Method Invocation (RMI) An interface that supports distributed Java applications in which a program running on one computer can invoke methods of Java objects that exist on a different computer. These and other new features are summarized in the sections below. Many of them are also described in more detail elsewhere in this book.
4.1 Java 1.1 Package-by-Package The packages and classes of the Java class library are interlinked and interdependent. Many of the major new features of Java 1.1 rely on classes from multiple packages in the Java API. Before we examine those new features in detail, therefore, we need to understand the big picture of Java 1.1. The paragraphs below discuss each of the 23 packages that constitute the core API for Java 1.1; they introduce the new packages and explain the changes to existing packages. java.applet Despite the introduction of JAR files, digitally signed applets, and new attributes of the
http://localhost/java/javaref/javanut/ch04_01.htm (2 of 6) [20/12/2001 11:01:10]
[Chapter 4] What's New in Java 1.1
<APPLET> tag, the java.applet package has not changed in any significant way. java.awt The java.awt package contains new classes and interfaces to support printing, popup menus, and menu shortcuts, and to improve support for layout management, cursors, scrolling, colors, and clipping. Several classes provide support for the new AWT event model, but most event support is contained in one of several new sub-packages of java.awt. java.awt.datatransfer The classes and interfaces in this package define a generic framework for inter-application (and intra-application) data transfer. This package also includes classes to support a clipboard-based cut-and-paste data transfer model. In the future, this package may be extended to include support for data transfer through a drag-and-drop metaphor. One of the two underlying data transfer mechanisms supported by this package relies on the Object Serialization API of the java.io package. java.awt.event This package defines the classes and interfaces of the new AWT event handling model. The classes and interfaces of this package fall into three categories: ❍ Event classes--the classes that actually represent events. ❍ Event "listeners"--interfaces that define methods that must be implemented by objects interested in being notified when an event of a particular type occurs. ❍ Event "adaptors"--trivial no-op implementations of the event listener interfaces that are suitable for easy subclassing. All the events and event listeners defined in this package extend the EventObject class or the EventListener interface defined in java.util. java.awt.image This package has two new image filter classes that implement improved image scaling. Changes have also been made to the MemoryImageSource and PixelGrabber classes. java.awt.peer The changes to this package for the most part simply reflect changes to java.awt. There are new interfaces that represent a platform-dependent popup menu and scrolling area, for example. java.beans This package constitutes the much-touted JavaBeans API for creating and using embeddable, reusable software components. The classes and interfaces in this package can be used at three different levels: ❍ To create application builder tools that programmers (or even non-programmers) can use to compose applications out of individual Java beans. ❍ To develop Java beans for use in such application builders. ❍ To develop applications (without using a builder tool) that use Java beans.
http://localhost/java/javaref/javanut/ch04_01.htm (3 of 6) [20/12/2001 11:01:10]
[Chapter 4] What's New in Java 1.1
Most of the classes and interfaces of the package are for use by application builders or by developers of advanced beans. Programmers using beans or writing simple beans do not need to be familiar with most of the package. Application builders that manipulate beans rely on the Reflection API defined in java.lang.reflect, and many beans take advantage of the Object Serialization API defined in the java.io package. The JavaBeans API uses the same event model that the Java 1.1 AWT does, and event-related classes and interfaces in this package are extensions of a class and an interface defined in java.util. java.io The java.io package has become by far the largest of the core Java packages. This is because Java 1.1 adds: ❍ A complete suite of new "character stream" classes to complement most of the existing "byte stream" input and output classes. These new "reader" and "writer" streams offer improved efficiency and support internationalization for textual input and output. ❍ New classes and interfaces to support object serialization. ❍ A number of new IOException types. java.lang This package has several new Exception and Error types, as well as new Byte, Short, and Void classes. With the addition of these new classes, all primitive Java data types (including the void type) have corresponding object types. This is important for the java.lang.reflect package, which defines the new Reflection API. In addition, the Class class has been greatly enhanced for use with the Reflection API. Class and ClassLoader have methods to locate "resources" associated with a class, such as images, audio files, Properties files, and so on. Resources are important for internationalization in Java 1.1. java.lang.reflect This new package enables a Java program to examine the structure of Java classes and to "reflect upon" its own structure. java.lang.reflect contains classes that represent the fields, methods, and constructors of a class, and enable a program to obtain complete information about any object, array, method, constructor, or field. The java.beans package relies heavily upon this package. java.math This new package contains only two classes, which support arithmetic on arbitrary-size integers and arbitrary-precision floating-point numbers. The BigInteger class also defines methods for modular arithmetic, primality testing, and other features required for cryptography. java.net The changes to the java.net package are quite low-level. They include the addition of multicast sockets, Unix-style socket options, and new exception types that provide finer granularity when handling networking exceptions. java.rmi
http://localhost/java/javaref/javanut/ch04_01.htm (4 of 6) [20/12/2001 11:01:10]
[Chapter 4] What's New in Java 1.1
This package defines the fundamental classes and interfaces used for Remote Method Invocation. Most of the classes in this package are exception types. Subpackages of java.rmi provide additional, more specialized functionality. When objects must be passed as arguments to remote methods, RMI relies on the object serialization functionality provided in the java.io package. java.rmi.dgc This small package defines the classes and interfaces required for distributed garbage collection (DGC). java.rmi.registry This is another small package that defines the classes and interfaces required for a Java client to look up a remote object by name or for a Java server to advertise the service it provides. java.rmi.server This package is the largest of the RMI packages and is at the heart of Remote Method Invocation. It defines the classes and interface that allow a Java program to create an object that can be used remotely by other Java programs. java.security This package contains the classes and interfaces that represent the fundamental abstractions of cryptographic security: public and private keys, certificates, message digests, and digital signatures. This package does not provide implementations of these abstractions; by design, the Java Security API is implementation independent. Java 1.1 does include a default implementation, but vendor-specific implementations may also be used in conjunction with this package. The default security implementation relies on the BigInteger class defined in the java.math package. java.security.acl This package defines high-level interfaces, and some exceptions, for manipulating access control lists. java.security.interfaces This package defines a few interfaces that are required for the Java Security API's implementation-independent design. java.sql This package is the Java Database Connectivity (JDBC) API. The classes and interfaces it contains allow Java programs to send SQL queries to databases and retrieve the results of those queries. java.text The classes and interfaces in this package are used for internationalization. The package includes classes for formatting dates, times, numbers, and textual messages in a manner appropriate for the default locale, or for any specified locale. It also includes classes for collating strings according to the rules of a given locale and iterating through the characters, words, and sentences of a string in a locale-specific manner. java.util
http://localhost/java/javaref/javanut/ch04_01.htm (5 of 6) [20/12/2001 11:01:10]
[Chapter 4] What's New in Java 1.1
As its name indicates, the java.util package contains miscellaneous utility classes. In Java 1.1, new classes have been added to this package to support the AWT and Java Beans event model, to define "locales" and "resource bundles" used for internationalization, and to manipulate dates, times, and time zones. java.util.zip This package implements classes for computing checksums on streams of data, and for compressing and archiving (and uncompressing and unarchiving) streams of data, using ZLIB compression library and ZIP and GZIP file formats.
Summary
http://localhost/java/javaref/javanut/ch04_01.htm (6 of 6) [20/12/2001 11:01:10]
Inner Classes
[Chapter 4] 4.10 Enterprise APIs: JDBC, RMI, and Security
Chapter 4 What's New in Java 1.1
4.10 Enterprise APIs: JDBC, RMI, and Security Java 1.1 provides a number of important new features that are loosely grouped under the name "Enterprise APIs." These include JDBC (Java DataBase Connectivity), RMI (Remote Method Invocation), and Java Security. With release 1.1, Java has grown too big for all of it to be documented, even in quick-reference format, in a single volume. Therefore, the JDBC, RMI, and Security packages will be documented, along with other, forthcoming Enterprise APIs, in a separate volume, Java Enterprise in a Nutshell. Note, however, that while this volume does not cover the Java Security API, it does cover applet security, signed applets, and the javakey program that is used to create digital signatures, generate key pairs, and manage a database of entities and their keys.
Java Beans
http://localhost/java/javaref/javanut/ch04_10.htm [20/12/2001 11:01:11]
Applet Changes
[Chapter 25] 25.56 java.lang.StackOverflowError (JDK 1.0)
Chapter 25 The java.lang Package
25.56 java.lang.StackOverflowError (JDK 1.0) Signals that a stack overflow has occurred within the Java interpreter. public class StackOverflowError extends VirtualMachineError { // Public Constructors public StackOverflowError(); public StackOverflowError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->VirtualMachineError->StackOverflowError
java.lang.Short (JDK 1.1)
http://localhost/java/javaref/javanut/ch25_56.htm [20/12/2001 11:01:11]
java.lang.String (JDK 1.0)
[Chapter 25] 25.65 java.lang.UnknownError (JDK 1.0)
Chapter 25 The java.lang Package
25.65 java.lang.UnknownError (JDK 1.0) Signals that an unknown error has occurred at the level of the Java Virtual Machine. public class UnknownError extends VirtualMachineError { // Public Constructors public UnknownError(); public UnknownError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->VirtualMachineError->UnknownError
java.lang.Throwable (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_65.htm [20/12/2001 11:01:11]
java.lang.UnsatisfiedLinkError (JDK 1.0)
[Chapter 25] 25.68 java.lang.VirtualMachineError (JDK 1.0)
Chapter 25 The java.lang Package
25.68 java.lang.VirtualMachineError (JDK 1.0) An abstract error type that serves as superclass for a group of errors related to the Java Virtual Machine. See InternalError, UnknownError, OutOfMemoryError, and StackOverflowError. public abstract class VirtualMachineError extends Error { // Public Constructors public VirtualMachineError(); public VirtualMachineError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->VirtualMachineError
Extended By: InternalError, OutOfMemoryError, StackOverflowError, UnknownError
java.lang.VerifyError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_68.htm [20/12/2001 11:01:11]
java.lang.Void (JDK 1.1)
[Chapter 23] The java.beans Package
Chapter 23
23. The java.beans Package Contents: java.beans.BeanInfo (JDK 1.1) java.beans.Beans (JDK 1.1) java.beans.Customizer (JDK 1.1) java.beans.EventSetDescriptor (JDK 1.1) java.beans.FeatureDescriptor (JDK 1.1) java.beans.IndexedPropertyDescriptor (JDK 1.1) java.beans.IntrospectionException (JDK 1.1) java.beans.Introspector (JDK 1.1) java.beans.MethodDescriptor (JDK 1.1) java.beans.ParameterDescriptor (JDK 1.1) java.beans.PropertyChangeEvent (JDK 1.1) java.beans.PropertyChangeListener (JDK 1.1) java.beans.PropertyChangeSupport (JDK 1.1) java.beans.PropertyDescriptor (JDK 1.1) java.beans.PropertyEditor (JDK 1.1) java.beans.PropertyEditorManager (JDK 1.1) java.beans.PropertyEditorSupport (JDK 1.1) java.beans.PropertyVetoException (JDK 1.1) java.beans.SimpleBeanInfo (JDK 1.1) java.beans.VetoableChangeListener (JDK 1.1) java.beans.VetoableChangeSupport (JDK 1.1) java.beans.Visibility (JDK 1.1) The java.beans package contains the classes and interfaces that constitute the JavaBeans API. It is new in Java 1.1. Figure 23.1 shows the class hierarchy for this package. The classes and interfaces in this package are useful to programmers who are developing "beanbox" tools to manipulate beans, and to programmers who are writing their own beans. Programmers who are building applications using beans do not have to be familiar with java.beans. See Chapter 10, Java Beans for more details on writing custom beans. Figure 23.1: The java.beans package http://localhost/java/javaref/javanut/ch23_01.htm (1 of 3) [20/12/2001 11:01:12]
[Chapter 23] The java.beans Package
23.1 java.beans.BeanDescriptor (JDK 1.1) A BeanDescriptor object is a type of FeatureDescriptor that describes a Java bean. The BeanInfo class for a Java bean optionally creates and initializes a BeanDescriptor object to describe the bean. Typically, only application builders and similar tools use the BeanDescriptor. To create a BeanDescriptor, you must specify the class of the bean, and optionally, the class of a Customizer for the bean. You can use the methods of FeatureDescriptor to provide additional information about the bean. public class BeanDescriptor extends FeatureDescriptor { // Public Constructors public BeanDescriptor(Class beanClass); public BeanDescriptor(Class beanClass, Class customizerClass); http://localhost/java/javaref/javanut/ch23_01.htm (2 of 3) [20/12/2001 11:01:12]
[Chapter 23] The java.beans Package
// Public Instance Methods public Class getBeanClass(); public Class getCustomizerClass(); }
Hierarchy: Object->FeatureDescriptor->BeanDescriptor
Returned By: BeanInfo.getBeanDescriptor(), SimpleBeanInfo.getBeanDescriptor()
java.awt.peer.WindowPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch23_01.htm (3 of 3) [20/12/2001 11:01:12]
java.beans.BeanInfo (JDK 1.1)
[Chapter 10] 10.5 Specifying Bean Information
Chapter 10 Java Beans
10.5 Specifying Bean Information The YesNoDialog class itself and the AnswerEvent and AnswerListener classes it relies on are all a required part of our bean. When an application that uses the bean is shipped, it has to include all three of these class files. There are other kinds of classes, however, that are often bundled with a bean that are not intended for use by the application developer. These classes are used by the beanbox tool that manipulates the bean. The bean class itself does not refer to any of these auxiliary beanbox classes so that it is not dependent on them and they do not have to be shipped with the bean in finished products. The first of these optional, auxiliary classes is a BeanInfo class. As explained earlier, a beanbox discovers the properties, events, and methods exported by a bean through "introspection" based on the Java Reflection API. A bean developer who wants to provide additional information about a bean, or who wants to refine the (somewhat rough) information available through introspection, should define a class that implements the BeanInfo interface to provide that information. A BeanInfo class typically subclasses SimpleBeanInfo, which provides a no-op implementation of the BeanInfo interface. When you only want to override one or two methods, it is easier to subclass SimpleBeanInfo than to implement BeanInfo directly. Beanbox tools rely on a naming convention in order to find the BeanInfo class for a given bean: a BeanInfo class should have the same name as the bean, with the string "BeanInfo" appended. Example 10.5 shows an implementation of the YesNoDialogBeanInfo class. This BeanInfo class specifies a number of pieces of information for our bean: ● An icon that can be used to represent the bean. ● A BeanDescriptor object, which includes a reference to a Customizer class for the bean. We'll see an implementation of this class later in the chapter. ● A list of the supported properties of the bean, along with a short description of each one. Some beanbox tools (but not Sun's beanbox) display these strings to the user in some useful way. ● A method that returns the most commonly customized property of the bean--this is called the "default" property. ● References to PropertyEditor classes for two of the properties. We'll see implementations of these property editor classes later in the chapter. ● A list of the methods supported by the bean, again with a short description of each one. Besides specifying this information, a BeanInfo class can also provide information about the events it generates and specify a default event. The various FeatureDescriptor objects used to provide information about such things as properties and methods can also include other information not provided by YesNoDialogBeanInfo, such as a localized display name that is distinct from the programmatic name. Example 10.5: The YesNoDialogBeanInfo Class package oreilly.beans.yesno; http://localhost/java/javaref/javanut/ch10_05.htm (1 of 3) [20/12/2001 11:01:13]
[Chapter 10] 10.5 Specifying Bean Information
import java.beans.*; import java.lang.reflect.*; import java.awt.*; /** The BeanInfo class for the YesNoDialog bean. */ public class YesNoDialogBeanInfo extends SimpleBeanInfo { /** Return an icon for the bean. We should really check the kind argument * to see what size icon the beanbox wants, but since we only have one * icon to offer, we just return it and let the beanbox deal with it. */ public Image getIcon(int kind) { return loadImage("YesNoDialogIcon.gif"); } /** Return a descriptor for the bean itself. It specifies a customizer * for the bean class. We could also add a description string here. */ public BeanDescriptor getBeanDescriptor() { return new BeanDescriptor(YesNoDialog.class, YesNoDialogCustomizer.class); } /** This is a convenience routine for creating PropertyDescriptor objects. */ public static PropertyDescriptor property(String name, String description) throws IntrospectionException { PropertyDescriptor p = new PropertyDescriptor(name, YesNoDialog.class); p.setShortDescription(description); return p; } /** This method returns an array of PropertyDescriptor objects that specify * additional information about the properties supported by the bean. * By explicitly specifying property descriptors, we are able to provide * simple help strings for each property; these would not be available to * the beanbox through simple introspection. We are also able to register * special property editors for two of the properties. */ public PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor[] props = { property("title", "The string that appears in the dialog title bar"), property("message", "The string that appears in the dialog body"), property("yesLabel", "The label for the 'Yes' button, if any"), property("noLabel", "The label for the 'No' button, if any"), property("cancelLabel", "The label for the 'Cancel' button, if any"), property("alignment", "The alignment of the message text"), property("font", "The font to use for message and buttons"), property("background", "The background color for the dialog"), property("foreground", "The text color for message and buttons") }; props[1].setPropertyEditorClass(YesNoDialogMessageEditor.class); props[5].setPropertyEditorClass(YesNoDialogAlignmentEditor.class); return props; } catch (IntrospectionException e) {return super.getPropertyDescriptors(); } } /** The message property is most often customized; make it the default. */
http://localhost/java/javaref/javanut/ch10_05.htm (2 of 3) [20/12/2001 11:01:13]
[Chapter 10] 10.5 Specifying Bean Information
public int getDefaultPropertyIndex() { return 1; } /** This is a convenience method for creating MethodDescriptors. Note that * it assumes we are talking about methods with no arguments. */ public static MethodDescriptor method(String name, String description) throws NoSuchMethodException, SecurityException { Method m = YesNoDialog.class.getMethod(name, new Class[] {}); MethodDescriptor md = new MethodDescriptor(m); md.setShortDescription(description); return md; } /** This method returns an array of method descriptors for the supported * methods of a bean. This allows us to provide useful description strings, * but it also allows us to filter out non-useful methods like wait() * and notify() that the bean inherits and which might otherwise be * displayed by the beanbox. */ public MethodDescriptor[] getMethodDescriptors() { try { MethodDescriptor[] methods = { method("display", "Pop up the dialog; make it visible") }; return methods; } catch (Exception e) { return super.getMethodDescriptors(); } } }
Custom Events
http://localhost/java/javaref/javanut/ch10_05.htm (3 of 3) [20/12/2001 11:01:13]
Defining a Simple Property Editor
[Chapter 23] 23.10 java.beans.MethodDescriptor (JDK 1.1)
Chapter 23 The java.beans Package
23.10 java.beans.MethodDescriptor (JDK 1.1) A MethodDescriptor object is a type of FeatureDescriptor that describes a method supported by a Java bean. The BeanInfo class for a Java bean optionally creates MethodDescriptor objects that describe the methods the bean exports. While a BeanInfo class creates and initializes MethodDescriptor objects, it is typically only application builders and similar tools that use these objects to obtain information about the methods supported by a bean. To create a MethodDescriptor, you must specify the java.lang.reflect.Method object for the method, and optionally specify an array of ParameterDescriptor objects that describe the parameters of the method. Once you have created a MethodDescriptor object, you can use FeatureDescriptor methods to provide additional information about each method. public class MethodDescriptor extends FeatureDescriptor { // Public Constructors public MethodDescriptor(Method method); public MethodDescriptor(Method method, ParameterDescriptor[] parameterDescriptors); // Public Instance Methods public Method getMethod(); public ParameterDescriptor[] getParameterDescriptors(); }
Hierarchy: Object->FeatureDescriptor->MethodDescriptor
Passed To: EventSetDescriptor()
Returned By: BeanInfo.getMethodDescriptors(), EventSetDescriptor.getListenerMethodDescriptors(), SimpleBeanInfo.getMethodDescriptors()
http://localhost/java/javaref/javanut/ch23_10.htm (1 of 2) [20/12/2001 11:01:13]
[Chapter 23] 23.10 java.beans.MethodDescriptor (JDK 1.1)
java.beans.Introspector (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_10.htm (2 of 2) [20/12/2001 11:01:13]
java.beans.ParameterDescriptor (JDK 1.1)
[Chapter 23] 23.11 java.beans.ParameterDescriptor (JDK 1.1)
Chapter 23 The java.beans Package
23.11 java.beans.ParameterDescriptor (JDK 1.1) A ParameterDescriptor object is a type of FeatureDescriptor that describes an argument or parameter to a method of a Java bean. The BeanInfo class for a Java bean optionally creates ParameterDescriptor objects that describe the parameters of the methods that the bean exports. While the BeanInfo class creates and initializes ParameterDescriptor objects, it is typically only application builders and similar tools that use these objects to obtain information about method parameters supported by the bean. The ParameterDescriptor class is a trivial subclass of FeatureDescriptor, and does not provide any new methods. Thus, you should use the methods of FeatureDescriptor to provide information about method parameters. public class ParameterDescriptor extends FeatureDescriptor { // Default Constructor: public ParameterDescriptor() }
Hierarchy: Object->FeatureDescriptor->ParameterDescriptor
Passed To: MethodDescriptor()
Returned By: MethodDescriptor.getParameterDescriptors()
java.beans.MethodDescriptor (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_11.htm [20/12/2001 11:01:13]
java.beans.PropertyChangeEvent (JDK 1.1)
[Chapter 23] 23.12 java.beans.PropertyChangeEvent (JDK 1.1)
Chapter 23 The java.beans Package
23.12 java.beans.PropertyChangeEvent (JDK 1.1) The PropertyChangeEvent class is a subclass of java.util.EventObject. An event of this type is sent to interested PropertyChangeListener objects whenever a Java bean changes a "bound" property, or whenever a PropertyEditor or Customizer changes a property value. A PropertyChangeEvent is also sent to registered VetoableChangeListener objects when a bean attempts to change the value of a "constrained" property. When creating a PropertyChangeEvent, you normally specify the bean that generated the event, the programmatic (locale-independent) name of the property that changed, and the old and new values of the property. If the values cannot be determined, null should be passed instead. If the event is a notification that more than one property value changed, the name should also be null. While Java beans must generate and send PropertyChangeEvent objects, it is typically only application builders and similar tools that are interested in receiving them. public class PropertyChangeEvent extends EventObject { // Public Constructor public PropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue); // Public Instance Methods public Object getNewValue(); public Object getOldValue(); public Object getPropagationId(); public String getPropertyName(); public void setPropagationId(Object propagationId); }
Hierarchy: Object->EventObject(Serializable)->PropertyChangeEvent
Passed To: PropertyChangeListener.propertyChange(), PropertyVetoException(), VetoableChangeListener.vetoableChange()
Returned By: PropertyVetoException.getPropertyChangeEvent()
http://localhost/java/javaref/javanut/ch23_12.htm (1 of 2) [20/12/2001 11:01:13]
[Chapter 23] 23.12 java.beans.PropertyChangeEvent (JDK 1.1)
java.beans.ParameterDescriptor (JDK 1.1)
java.beans.PropertyChangeListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_12.htm (2 of 2) [20/12/2001 11:01:13]
[Chapter 23] 23.13 java.beans.PropertyChangeListener (JDK 1.1)
Chapter 23 The java.beans Package
23.13 java.beans.PropertyChangeListener (JDK 1.1) This interface is an extension of java.util.EventListener and defines the method that a class must implement in order to be notified when property changes occur. A PropertyChangeEvent is sent out to all registered PropertyChangeListener objects whenever a bean changes one of its "bound" properties, or whenever a PropertyEditor or Customizer changes the value of a property. public abstract interface PropertyChangeListener extends EventListener { // Public Instance Methods public abstract void propertyChange(PropertyChangeEvent evt); }
Passed To: Customizer.addPropertyChangeListener(), Customizer.removePropertyChangeListener(), PropertyChangeSupport.addPropertyChangeListener(), PropertyChangeSupport.removePropertyChangeListener(), PropertyEditor.addPropertyChangeListener(), PropertyEditor.removePropertyChangeListener(), PropertyEditorSupport.addPropertyChangeListener(), PropertyEditorSupport.removePropertyChangeListener()
java.beans.PropertyChangeEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_13.htm [20/12/2001 11:01:14]
java.beans.PropertyChangeSupport (JDK 1.1)
[Chapter 23] 23.15 java.beans.PropertyDescriptor (JDK 1.1)
Chapter 23 The java.beans Package
23.15 java.beans.PropertyDescriptor (JDK 1.1) A PropertyDescriptor object is a type of FeatureDescriptor that describes a single property of a Java bean. The BeanInfo class for a Java bean optionally creates and initializes PropertyDescriptor objects to describe the properties that the bean supports. Typically, only application builders and similar tools use the get and is methods to obtain this property description information. You create a PropertyDescriptor by specifying the name of the property and the Class object for the bean. If you have not followed the standard "design patterns" for accessor method naming, you may also specify the accessor methods for the property. Once a PropertyDescriptor is created, the setBound() and setConstrained() methods allow you to specify whether the property is bound and/or constrained. setPropertyEditorClass() allows you to specify a specific property editor that should be used to edit the value of this property (this is useful, for example, when the property is an enumerated type with a specific list of supported values). The methods of the FeatureDescriptor superclass allow additional information about the property to be specified. public class PropertyDescriptor extends FeatureDescriptor { // Public Constructors public PropertyDescriptor(String propertyName, Class beanClass) throws IntrospectionException; public PropertyDescriptor(String propertyName, Class beanClass, String getterName, public PropertyDescriptor'u'String setterName) throws IntrospectionException; public PropertyDescriptor(String propertyName, Method getter, Method setter) throws IntrospectionException; // Public Instance Methods public Class getPropertyEditorClass(); public Class getPropertyType(); public Method getReadMethod(); public Method getWriteMethod(); public boolean isBound(); public boolean isConstrained(); public void setBound(boolean bound); public void setConstrained(boolean constrained); public void setPropertyEditorClass(Class propertyEditorClass); }
Hierarchy: Object->FeatureDescriptor->PropertyDescriptor
http://localhost/java/javaref/javanut/ch23_15.htm (1 of 2) [20/12/2001 11:01:14]
[Chapter 23] 23.15 java.beans.PropertyDescriptor (JDK 1.1)
Extended By: IndexedPropertyDescriptor
Returned By: BeanInfo.getPropertyDescriptors(), SimpleBeanInfo.getPropertyDescriptors()
java.beans.PropertyChangeSupport (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_15.htm (2 of 2) [20/12/2001 11:01:14]
java.beans.PropertyEditor (JDK 1.1)
[Chapter 23] 23.16 java.beans.PropertyEditor (JDK 1.1)
Chapter 23 The java.beans Package
23.16 java.beans.PropertyEditor (JDK 1.1) The PropertyEditor interface defines the methods that must be implemented by a Java beans property editor intended for use within an application builder or similar tool. PropertyEditor is a complex interface because it defines methods to support several different ways of displaying property values to the user, and it also defines methods to support several different ways of allowing the user to edit the property value. For a property of type x, the author of a Java bean typically implements a property editor of class xEditor. While the editor is implemented by the bean author, it is usually only instantiated or used by application builders or similar tools (or by a Customizer class for a Bean). In addition to implementing the PropertyEditor interface, a property editor must have a constructor that expects no arguments, so that it can be easily instantiated by an application builder. Also, it must accept registration and deregistration of PropertyChangeListener objects, and it must send a PropertyChangeEvent to all registered listeners when it changes the value of the property being edited. The PropertyEditorSupport class is a trivial implementation of PropertyEditor, suitable for subclassing, or for supporting a list of PropertyChangeListener objects. public abstract interface PropertyEditor { // Public Instance Methods public abstract void addPropertyChangeListener(PropertyChangeListener listener); public abstract String getAsText(); public abstract Component getCustomEditor(); public abstract String getJavaInitializationString(); public abstract String[] getTags(); public abstract Object getValue(); public abstract boolean isPaintable(); public abstract void paintValue(Graphics gfx, Rectangle box); public abstract void removePropertyChangeListener(PropertyChangeListener listener); public abstract void setAsText(String text) throws IllegalArgumentException; public abstract void setValue(Object value); public abstract boolean supportsCustomEditor(); }
Implemented By: PropertyEditorSupport
http://localhost/java/javaref/javanut/ch23_16.htm (1 of 2) [20/12/2001 11:01:14]
[Chapter 23] 23.16 java.beans.PropertyEditor (JDK 1.1)
Returned By: PropertyEditorManager.findEditor()
java.beans.PropertyDescriptor (JDK 1.1)
java.beans.PropertyEditorManager (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_16.htm (2 of 2) [20/12/2001 11:01:14]
[Chapter 23] 23.19 java.beans.PropertyVetoException (JDK 1.1)
Chapter 23 The java.beans Package
23.19 java.beans.PropertyVetoException (JDK 1.1) The PropertyVetoException signals that a VetoableChangeListener that received a PropertyChangeEvent for a "constrained" property of a bean has vetoed that proposed change. When this exception is received, the property in question should revert back to its original value, and any VetoableChangeListener objects that have already been notified of the property change must be re-notified to indicate that the property has reverted to its old value. The VetoableChangeSupport class handles this re-notification automatically and re-throws the PropertyVetoException to notify its caller that the change was rejected. public class PropertyVetoException extends Exception { // Public Constructor public PropertyVetoException(String mess, PropertyChangeEvent evt); // Public Instance Methods public PropertyChangeEvent getPropertyChangeEvent(); }
Hierarchy: Object->Throwable(Serializable)->Exception->PropertyVetoException
Thrown By: VetoableChangeListener.vetoableChange(), VetoableChangeSupport.fireVetoableChange()
java.beans.PropertyEditorSupport (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_19.htm [20/12/2001 11:01:14]
java.beans.SimpleBeanInfo (JDK 1.1)
[Chapter 23] 23.21 java.beans.VetoableChangeListener (JDK 1.1)
Chapter 23 The java.beans Package
23.21 java.beans.VetoableChangeListener (JDK 1.1) This interface is an extension of java.util.EventListener and defines the method that a class must implement in order to be notified when a Java bean makes a change to a "constrained" property. A PropertyChangeEvent is passed to the vetoableChange() method when such a change occurs, and if the VetoableChangeListener wants to prevent the change from occurring, this method should throw a PropertyVetoException. public abstract interface VetoableChangeListener extends EventListener { // Public Instance Methods public abstract void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException; }
Passed To: VetoableChangeSupport.addVetoableChangeListener(), VetoableChangeSupport.removeVetoableChangeListener()
java.beans.SimpleBeanInfo (JDK 1.1)
http://localhost/java/javaref/javanut/ch23_21.htm [20/12/2001 11:01:15]
java.beans.VetoableChangeSupport (JDK 1.1)
[Chapter 28] 28.12 java.net.MulticastSocket (JDK 1.1)
Chapter 28 The java.net Package
28.12 java.net.MulticastSocket (JDK 1.1) This subclass of DatagramSocket is used to send and receive multicast UDP packets. It extends DatagramSocket by adding joinGroup() and leaveGroup() methods to join and leave multicast groups. The IP address specified to these methods should be a valid multicast address in the range of 224.0.0.1 to 239.255.255.255. Note that you do not have to join a group to send a packet to a multicast address, but you must join the group to receive packets sent to that address. MulticastSocket defines a variant send() method that allows you to specify a time-to-live (TTL) value for the packet you send. This value specifies the number of network "hops" the packet may travel before it expires. You can also set a default TTL for all packets sent though a MulticastSocket with setTTL(). Note that untrusted applets are not allowed to use multicast sockets. public class MulticastSocket extends DatagramSocket { // Public Constructors public MulticastSocket() throws IOException; public MulticastSocket(int port) throws IOException; // Public Instance Methods public InetAddress getInterface() throws SocketException; public byte getTTL() throws IOException; public void joinGroup(InetAddress mcastaddr) throws IOException; public void leaveGroup(InetAddress mcastaddr) throws IOException; public synchronized void send(DatagramPacket p, byte ttl) throws IOException; public void setInterface(InetAddress inf) throws SocketException; public void setTTL(byte ttl) throws IOException; }
Hierarchy: Object->DatagramSocket->MulticastSocket
java.net.MalformedURLException (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_12.htm [20/12/2001 11:01:15]
java.net.NoRouteToHostException (JDK 1.1)
[Chapter 20] 20.19 java.awt.event.KeyListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.19 java.awt.event.KeyListener (JDK 1.1) This interface defines the methods that an object must implement to "listen" for key events on AWT components. When a KeyEvent occurs, an AWT component notifies its registered KeyListener objects by invoking one of their methods. An easy way to implement this interface is by subclassing the KeyAdapter class. public abstract interface KeyListener extends EventListener { // Public Instance Methods public abstract void keyPressed(KeyEvent e); public abstract void keyReleased(KeyEvent e); public abstract void keyTyped(KeyEvent e); }
Implemented By: AWTEventMulticaster, KeyAdapter
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), Component.addKeyListener(), Component.removeKeyListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
java.awt.event.KeyEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_19.htm [20/12/2001 11:01:15]
java.awt.event.MouseAdapter (JDK 1.1)
[Chapter 18] 18.35 java.awt.Label (JDK 1.0)
Chapter 18 The java.awt Package
18.35 java.awt.Label (JDK 1.0) This class is a Component that displays a single specified line of read-only text. The constant values specify the text alignment within the component and may be specified to the constructor or to setAlignment(). public class Label extends Component { // Public Constructors public Label(); public Label(String text); public Label(String text, int alignment); // Constants public static final int CENTER; public static final int LEFT; public static final int RIGHT; // Public Instance Methods public void addNotify(); // Overrides Component public int getAlignment(); public String getText(); public synchronized void setAlignment(int alignment); public synchronized void setText(String text); // Protected Instance Methods protected String paramString(); // Overrides Component }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Label
Passed To: Toolkit.createLabel()
http://localhost/java/javaref/javanut/ch18_35.htm (1 of 2) [20/12/2001 11:01:15]
[Chapter 18] 18.35 java.awt.Label (JDK 1.0)
java.awt.ItemSelectable (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_35.htm (2 of 2) [20/12/2001 11:01:15]
java.awt.LayoutManager (JDK 1.0)
[Chapter 22] 22.12 java.awt.peer.LabelPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.12 java.awt.peer.LabelPeer (JDK 1.0) public abstract interface LabelPeer extends ComponentPeer { // Public Instance Methods public abstract void setAlignment(int alignment); public abstract void setText(String label); }
Returned By: Toolkit.createLabel()
java.awt.peer.FramePeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_12.htm [20/12/2001 11:01:16]
java.awt.peer.LightweightPeer (JDK 1.1)
[Chapter 18] 18.37 java.awt.LayoutManager2 (JDK 1.1)
Chapter 18 The java.awt Package
18.37 java.awt.LayoutManager2 (JDK 1.1) This interface is an extension of the LayoutManager interface. It defines additional layout management methods for layout managers that perform constraint-based layout. GridBagLayout is an example of a constraint-based layout manager--each component added to the layout is associated with a GridBagConstraints object that specifies the "constraints" on how the component is to be laid out. Java programs do not directly invoke the methods of this interface--they are used by the Container object for which the layout manager is registered. public abstract interface LayoutManager2 extends LayoutManager { // Public Instance Methods public abstract void addLayoutComponent(Component comp, Object constraints); public abstract float getLayoutAlignmentX(Container target); public abstract float getLayoutAlignmentY(Container target); public abstract void invalidateLayout(Container target); public abstract Dimension maximumLayoutSize(Container target); }
Implemented By: BorderLayout, CardLayout, GridBagLayout
java.awt.LayoutManager (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_37.htm [20/12/2001 11:01:16]
java.awt.List (JDK 1.0)
[Chapter 22] 22.13 java.awt.peer.LightweightPeer (JDK 1.1)
Chapter 22 The java.awt.peer Package
22.13 java.awt.peer.LightweightPeer (JDK 1.1) public interface LightweightPeer extends ComponentPeer { }
Returned By: Toolkit.createComponent()
java.awt.peer.LabelPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_13.htm [20/12/2001 11:01:16]
java.awt.peer.ListPeer (JDK 1.0)
[Chapter 20] 20.22 java.awt.event.MouseListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.22 java.awt.event.MouseListener (JDK 1.1) This interface defines the methods that an object must implement to "listen" for mouse events on AWT components. When a MouseEvent occurs, an AWT component notifies its registered MouseListener objects (or MouseMotionListener objects if the event involves mouse motion) by invoking one of their methods. An easy way to implement this interface is by subclassing the MouseAdapter class. public abstract interface MouseListener extends EventListener { // Public Instance Methods public abstract void mouseClicked(MouseEvent e); public abstract void mouseEntered(MouseEvent e); public abstract void mouseExited(MouseEvent e); public abstract void mousePressed(MouseEvent e); public abstract void mouseReleased(MouseEvent e); }
Implemented By: AWTEventMulticaster, MouseAdapter
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), Component.addMouseListener(), Component.removeMouseListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
java.awt.event.MouseEvent (JDK 1.1) http://localhost/java/javaref/javanut/ch20_22.htm (1 of 2) [20/12/2001 11:01:17]
java.awt.event.MouseMotionAdapter (JDK 1.1)
[Chapter 20] 20.22 java.awt.event.MouseListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_22.htm (2 of 2) [20/12/2001 11:01:17]
[Chapter 20] 20.24 java.awt.event.MouseMotionListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.24 java.awt.event.MouseMotionListener (JDK 1.1) This interface defines the methods that an object must implement to "listen" for mouse motion events on AWT components. When a MouseEvent occurs involving a mouse drag or mouse motion with no buttons down, an AWT component notifies its registered MouseMotionListener objects by invoking one of their methods. An easy way to implement this is by subclassing the MouseMotionAdapter class. public abstract interface MouseMotionListener extends EventListener { // Public Instance Methods public abstract void mouseDragged(MouseEvent e); public abstract void mouseMoved(MouseEvent e); }
Implemented By: AWTEventMulticaster, MouseMotionAdapter
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), Component.addMouseMotionListener(), Component.removeMouseMotionListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
java.awt.event.MouseMotionAdapter (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_24.htm (1 of 2) [20/12/2001 11:01:17]
java.awt.event.PaintEvent (JDK 1.1)
[Chapter 20] 20.24 java.awt.event.MouseMotionListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_24.htm (2 of 2) [20/12/2001 11:01:17]
[Chapter 20] 20.27 java.awt.event.TextListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.27 java.awt.event.TextListener (JDK 1.1) This interface defines the method that an object must implement to "listen" for text events on AWT components. When a TextEvent occurs, an AWT component notifies its registered TextListener objects by invoking their textValueChanged() methods. public abstract interface TextListener extends EventListener { // Public Instance Methods public abstract void textValueChanged(TextEvent e); }
Implemented By: AWTEventMulticaster
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), TextComponent.addTextListener(), TextComponent.removeTextListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
Type Of: TextComponent.textListener
java.awt.event.TextEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_27.htm [20/12/2001 11:01:18]
java.awt.event.WindowAdapter (JDK 1.1)
[Chapter 30] 30.25 java.util.TooManyListenersException (JDK 1.1)
Chapter 30 The java.util Package
30.25 java.util.TooManyListenersException (JDK 1.1) An exception of this type signals that an AWT component or Java bean may only have one EventListener object registered for some specific type of event. That is, it signals that a particular event is a "unicast" event rather than a "multicast" event. This exception type serves a formal purpose in the AWT and JavaBeans event model. Its presence in the throws clause of an EventListener registration method (even if the method never actually throws the exception) signals that an event is a unicast event. public class TooManyListenersException extends Exception { // Public Constructors public TooManyListenersException(); public TooManyListenersException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->TooManyListenersException
java.util.TimeZone (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_25.htm [20/12/2001 11:01:18]
java.util.Vector (JDK 1.0)
[Chapter 20] 20.30 java.awt.event.WindowListener (JDK 1.1)
Chapter 20 The java.awt.event Package
20.30 java.awt.event.WindowListener (JDK 1.1) This interface defines the methods that an object must implement to "listen" for window events on AWT components. When a WindowEvent occurs, an AWT component notifies its registered WindowListener objects by invoking one of their methods. An easy way to implement this interface is by subclassing the WindowAdapter class. public abstract interface WindowListener extends EventListener { // Public Instance Methods public abstract void windowActivated(WindowEvent e); public abstract void windowClosed(WindowEvent e); public abstract void windowClosing(WindowEvent e); public abstract void windowDeactivated(WindowEvent e); public abstract void windowDeiconified(WindowEvent e); public abstract void windowIconified(WindowEvent e); public abstract void windowOpened(WindowEvent e); }
Implemented By: AWTEventMulticaster, WindowAdapter
Passed To: AWTEventMulticaster.add(), AWTEventMulticaster.remove(), Window.addWindowListener(), Window.removeWindowListener()
Returned By: AWTEventMulticaster.add(), AWTEventMulticaster.remove()
http://localhost/java/javaref/javanut/ch20_30.htm (1 of 2) [20/12/2001 11:01:18]
[Chapter 20] 20.30 java.awt.event.WindowListener (JDK 1.1)
java.awt.event.WindowEvent (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_30.htm (2 of 2) [20/12/2001 11:01:18]
The java.awt.image Package
[Chapter 18] 18.38 java.awt.List (JDK 1.0)
Chapter 18 The java.awt Package
18.38 java.awt.List (JDK 1.0) This class is a Component that graphically displays a list of strings. The list is scrollable if necessary. The constructor takes optional arguments that specify the number of visible rows in the list and whether selection of more than one item is allowed. The various instance methods allow strings to be added and removed from the List, and allow the selected item or items to be queried. public class List extends Component implements ItemSelectable { // Public Constructors public List(); 1.1 public List(int rows); public List(int rows, boolean multipleMode); // Public Instance Methods 1.1 public void add(String item); 1.1 public synchronized void add(String item, int index); 1.1 public synchronized void addActionListener(ActionListener l); public void addItem(String item); public synchronized void addItem(String item, int index); 1.1 public synchronized void addItemListener(ItemListener l); // From ItemSelectable public void addNotify(); // Overrides Component # public boolean allowsMultipleSelections(); # public synchronized void clear(); # public int countItems(); public synchronized void delItem(int position); # public synchronized void delItems(int start, int end); public synchronized void deselect(int index); public String getItem(int index); 1.1 public int getItemCount(); 1.1 public synchronized String[] getItems(); 1.1 public Dimension getMinimumSize(int rows); 1.1 public Dimension getMinimumSize(); // Overrides Component 1.1 public Dimension getPreferredSize(int rows); 1.1 public Dimension getPreferredSize(); // Overrides Component public int getRows(); public synchronized int getSelectedIndex(); public synchronized int[] getSelectedIndexes(); public synchronized String getSelectedItem(); public synchronized String[] getSelectedItems(); 1.1 public Object[] getSelectedObjects(); // From ItemSelectable public int getVisibleIndex(); 1.1 public boolean isIndexSelected(int index); http://localhost/java/javaref/javanut/ch18_38.htm (1 of 2) [20/12/2001 11:01:19]
[Chapter 18] 18.38 java.awt.List (JDK 1.0)
1.1 public boolean isMultipleMode(); # public boolean isSelected(int index); public synchronized void makeVisible(int index); # public Dimension minimumSize(int rows); # public Dimension minimumSize(); // Overrides Component # public Dimension preferredSize(int rows); # public Dimension preferredSize(); // Overrides Component 1.1 public synchronized void remove(String item); 1.1 public synchronized void remove(int position); 1.1 public synchronized void removeActionListener(ActionListener l); 1.1 public synchronized void removeAll(); 1.1 public synchronized void removeItemListener(ItemListener l); // From ItemSelectable public void removeNotify(); // Overrides Component public synchronized void replaceItem(String newValue, int index); public synchronized void select(int index); 1.1 public synchronized void setMultipleMode(boolean b); # public synchronized void setMultipleSelections(boolean b); // Protected Instance Methods protected String paramString(); // Overrides Component 1.1 protected void processActionEvent(ActionEvent e); 1.1 protected void processEvent(AWTEvent e); // Overrides Component 1.1 protected void processItemEvent(ItemEvent e); }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->List(ItemSelectable)
Passed To: Toolkit.createList()
java.awt.LayoutManager2 (JDK 1.1)
java.awt.MediaTracker (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_38.htm (2 of 2) [20/12/2001 11:01:19]
[Chapter 22] 22.14 java.awt.peer.ListPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.14 java.awt.peer.ListPeer (JDK 1.0) public abstract interface ListPeer extends ComponentPeer { // Public Instance Methods 1.1 public abstract void add(String item, int index); public abstract void addItem(String item, int index); public abstract void clear(); public abstract void delItems(int start, int end); public abstract void deselect(int index); 1.1 public abstract Dimension getMinimumSize(int rows); 1.1 public abstract Dimension getPreferredSize(int rows); public abstract int[] getSelectedIndexes(); public abstract void makeVisible(int index); public abstract Dimension minimumSize(int v); public abstract Dimension preferredSize(int v); 1.1 public abstract void removeAll(); public abstract void select(int index); 1.1 public abstract void setMultipleMode(boolean b); public abstract void setMultipleSelections(boolean v); }
Returned By: Toolkit.createList()
java.awt.peer.LightweightPeer (JDK 1.1)
http://localhost/java/javaref/javanut/ch22_14.htm [20/12/2001 11:01:19]
java.awt.peer.MenuBarPeer (JDK 1.0)
[Chapter 28] 28.11 java.net.MalformedURLException (JDK 1.0)
Chapter 28 The java.net Package
28.11 java.net.MalformedURLException (JDK 1.0) Signals that an unparseable URL specification has been passed to a method. public class MalformedURLException extends IOException { // Public Constructors public MalformedURLException(); public MalformedURLException(String msg); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->MalformedURLException
Thrown By: URL()
java.net.InetAddress (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_11.htm [20/12/2001 11:01:20]
java.net.MulticastSocket (JDK 1.1)
[Chapter 24] 24.63 java.io.StringReader (JDK 1.1)
Chapter 24 The java.io Package
24.63 java.io.StringReader (JDK 1.1) This class is a character input stream that uses a String object as the source of the characters it returns. When you create a StringReader, you must specify the String that it is to read from. StringReader defines the normal Reader methods, and supports mark() and reset(). If reset() is called before mark() has been called, the stream is reset to the beginning of the specified string. StringReader is a character stream analog to StringBufferInputStream, which is deprecated in Java 1.1. StringReader is also similar to CharArrayReader. public class StringReader extends Reader { // Public Constructor public StringReader(String s); // Public Instance Methods public void close(); // Defines Reader public void mark(int readAheadLimit) throws IOException; // Overrides Reader public boolean markSupported(); // Overrides Reader public int read() throws IOException; // Overrides Reader public int read(char[] cbuf, int off, int len) throws IOException; // Defines Reader public boolean ready(); // Overrides Reader public void reset() throws IOException; // Overrides Reader public long skip(long ns) throws IOException; // Overrides Reader }
Hierarchy: Object->Reader->StringReader
java.io.StringBufferInputStream (JDK 1.0; Deprecated.)
http://localhost/java/javaref/javanut/ch24_63.htm [20/12/2001 11:01:20]
java.io.StringWriter (JDK 1.1)
[Chapter 25] 25.37 java.lang.Math (JDK 1.0)
Chapter 25 The java.lang Package
25.37 java.lang.Math (JDK 1.0) This class defines constants for the mathematical values e and pi, and defines static methods for floating-point trigonometry, exponentiation, and other operations. It is the equivalent of the C <math.h> functions. It also contains methods for computing minimum and maximum values and for generating pseudo-random numbers. public final class Math extends Object { // No Constructor // Constants public static final double E; public static final double PI; // Class Methods public static native double IEEEremainder(double f1, double f2); public static int abs(int a); public static long abs(long a); public static float abs(float a); public static double abs(double a); public static native double acos(double a); public static native double asin(double a); public static native double atan(double a); public static native double atan2(double a, double b); public static native double ceil(double a); public static native double cos(double a); public static native double exp(double a); public static native double floor(double a); public static native double log(double a); public static int max(int a, int b); public static long max(long a, long b); public static float max(float a, float b); public static double max(double a, double b); public static int min(int a, int b); public static long min(long a, long b); public static float min(float a, float b); public static double min(double a, double b); public static native double pow(double a, double b); public static synchronized double random(); public static native double rint(double a); public static int round(float a); http://localhost/java/javaref/javanut/ch25_37.htm (1 of 2) [20/12/2001 11:01:20]
[Chapter 25] 25.37 java.lang.Math (JDK 1.0)
public public public public
static static static static
long round(double a); native double sin(double a); native double sqrt(double a); native double tan(double a);
}
java.lang.Long (JDK 1.0)
java.lang.NegativeArraySizeException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_37.htm (2 of 2) [20/12/2001 11:01:20]
[Chapter 22] 22.15 java.awt.peer.MenuBarPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.15 java.awt.peer.MenuBarPeer (JDK 1.0) public abstract interface MenuBarPeer extends MenuComponentPeer { // Public Instance Methods public abstract void addHelpMenu(Menu m); public abstract void addMenu(Menu m); public abstract void delMenu(int index); }
Returned By: Toolkit.createMenuBar()
java.awt.peer.ListPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_15.htm [20/12/2001 11:01:20]
java.awt.peer.MenuComponentPeer (JDK 1.0)
[Chapter 22] 22.16 java.awt.peer.MenuComponentPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.16 java.awt.peer.MenuComponentPeer (JDK 1.0) public abstract interface MenuComponentPeer { // Public Instance Methods public abstract void dispose(); }
Extended By: MenuBarPeer, MenuItemPeer
Returned By: MenuComponent.getPeer()
java.awt.peer.MenuBarPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_16.htm [20/12/2001 11:01:21]
java.awt.peer.MenuItemPeer (JDK 1.0)
[Chapter 18] 18.43 java.awt.MenuContainer (JDK 1.0)
Chapter 18 The java.awt Package
18.43 java.awt.MenuContainer (JDK 1.0) This interface defines the methods necessary for MenuContainer types such as the Menu, Frame, and MenuBar objects. Unless you implement new menu-like components, you never need to use it. public abstract interface MenuContainer { // Public Instance Methods public abstract Font getFont(); public abstract boolean postEvent(Event evt); public abstract void remove(MenuComponent comp); }
Implemented By: Component, Frame, Menu, MenuBar
Returned By: MenuComponent.getParent()
java.awt.MenuComponent (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_43.htm [20/12/2001 11:01:21]
java.awt.MenuItem (JDK 1.0)
[Chapter 22] 22.17 java.awt.peer.MenuItemPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.17 java.awt.peer.MenuItemPeer (JDK 1.0) public abstract interface MenuItemPeer extends MenuComponentPeer { // Public Instance Methods public abstract void disable(); public abstract void enable(); 1.1 public abstract void setEnabled(boolean b); public abstract void setLabel(String label); }
Extended By: CheckboxMenuItemPeer, MenuPeer
Returned By: Toolkit.createMenuItem()
java.awt.peer.MenuComponentPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_17.htm [20/12/2001 11:01:21]
java.awt.peer.MenuPeer (JDK 1.0)
[Chapter 22] 22.18 java.awt.peer.MenuPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.18 java.awt.peer.MenuPeer (JDK 1.0) public abstract interface MenuPeer extends MenuItemPeer { // Public Instance Methods public abstract void addItem(MenuItem item); public abstract void addSeparator(); public abstract void delItem(int index); }
Hierarchy: (MenuPeer(MenuItemPeer(MenuComponentPeer)))
Extended By: PopupMenuPeer
Returned By: Toolkit.createMenu()
java.awt.peer.MenuItemPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_18.htm [20/12/2001 11:01:22]
java.awt.peer.PanelPeer (JDK 1.0)
[Chapter 22] 22.20 java.awt.peer.PopupMenuPeer (JDK 1.1)
Chapter 22 The java.awt.peer Package
22.20 java.awt.peer.PopupMenuPeer (JDK 1.1) public abstract interface PopupMenuPeer extends MenuPeer { // Public Instance Methods public abstract void show(Event e); }
Hierarchy: (PopupMenuPeer(MenuPeer(MenuItemPeer(MenuComponentPeer))))
Returned By: Toolkit.createPopupMenu()
java.awt.peer.PanelPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_20.htm [20/12/2001 11:01:22]
java.awt.peer.ScrollPanePeer (JDK 1.1)
[Chapter 12] 12.2 Invoking a Named Method
Chapter 12 Reflection
12.2 Invoking a Named Method Example 12.2 demonstrates another use of the Reflection API. This UniversalActionListener object uses reflection to invoke a named method of a specified object, passing another optionally specified object as an argument. It does this in the framework of the ActionListener interface, so that it can serve as an action listener within a Java 1.1 GUI. By using the reflection capabilities of the UniversalActionListener, a program can avoid having to create a lot of trivial ActionListener implementations to handle action events. The main() method at the end of this example is a simple test GUI that demonstrates how you could use the UniversalActionListener object. Contrast it with the anonymous class event-handling techniques demonstrated in Chapter 7, Events. Java does not allow methods to be passed directly as data values, but the Reflection API makes it possible for methods passed by name to be invoked indirectly. Note that this technique is not particularly efficient. For asynchronous event handling in a GUI, though, it is certainly efficient enough: indirect method invocation through the Reflection API will always be much faster than the response time required by the limits of human perception. Invoking a method by name is not an appropriate technique, however, when repetitive, synchronous calls are required. Thus, you should not use this technique for passing a comparison method to a sorting routine or passing a filename filter to a directory listing method. In cases like these, you should use the standard technique of implementing a class that contains the desired method and passing an instance of the class to the appropriate routine. Example 12.2: Invoking a Named Method with Reflection import java.awt.event.*; import java.lang.reflect.*; import java.awt.*; // Only used for the test program below. public class UniversalActionListener implements ActionListener { protected Object target; protected Object arg; protected Method m; public UniversalActionListener(Object target, String methodname, Object arg) throws NoSuchMethodException, SecurityException { this.target = target; // Save the target object. this.arg = arg; // And method argument. // Now look up and save the Method to invoke on that target object. Class c, parameters[]; c = target.getClass(); // The Class object. if (arg == null) parameters = new Class[0]; // Method parameter. else parameters = new Class[] { arg.getClass() };
http://localhost/java/javaref/javanut/ch12_02.htm (1 of 2) [20/12/2001 11:01:22]
[Chapter 12] 12.2 Invoking a Named Method
m = c.getMethod(methodname, parameters);
// Find matching method.
} public void actionPerformed(ActionEvent event) { Object[] arguments; if (arg == null) arguments = new Object[0]; // Set up arguments. else arguments = new Object[] { arg }; try { m.invoke(target, arguments); } // And invoke the method. catch (IllegalAccessException e) { // Should never happen. System.err.println("UniversalActionListener: " + e); } catch (InvocationTargetException e) { // Should never happen. System.err.println("UniversalActionListener: " + e); } } // A simple test program for the UniversalActionListener. public static void main(String[] args) throws NoSuchMethodException { Frame f = new Frame("UniversalActionListener Test");// Create window. f.setLayout(new FlowLayout()); // Set layout manager. Button b1 = new Button("tick"); // Create buttons. Button b2 = new Button("tock"); Button b3 = new Button("Close Window"); f.add(b1); f.add(b2); f.add(b3); // Add them to window. // Specify what the buttons do. Invoke a named method with // the UniversalActionListener object. b1.addActionListener(new UniversalActionListener(b1, "setLabel", "tock")); b1.addActionListener(new UniversalActionListener(b2, "setLabel", "tick")); b1.addActionListener(new UniversalActionListener(b3, "hide", null)); b2.addActionListener(new UniversalActionListener(b1, "setLabel", "tick")); b2.addActionListener(new UniversalActionListener(b2, "setLabel", "tock")); b2.addActionListener(new UniversalActionListener(b3, "show", null)); b3.addActionListener(new UniversalActionListener(f, "dispose", null)); f.pack(); // Set window size. f.show(); // And pop it up. } }
Obtaining Class and Member Information
http://localhost/java/javaref/javanut/ch12_02.htm (2 of 2) [20/12/2001 11:01:22]
Java Syntax
[Chapter 25] 25.42 java.lang.NoSuchMethodError (JDK 1.0)
Chapter 25 The java.lang Package
25.42 java.lang.NoSuchMethodError (JDK 1.0) Signals that a specified method could not be found. public class NoSuchMethodError extends IncompatibleClassChangeError { // Public Constructors public NoSuchMethodError(); public NoSuchMethodError(String s); }
Hierarchy: Object->Throwable(Serializable)->Error->LinkageError->IncompatibleClassChangeError->NoSuchMethodError
java.lang.NoSuchFieldException (JDK 1.1)
http://localhost/java/javaref/javanut/ch25_42.htm [20/12/2001 11:01:23]
java.lang.NoSuchMethodException (JDK 1.0)
[Chapter 25] 25.43 java.lang.NoSuchMethodException (JDK 1.0)
Chapter 25 The java.lang Package
25.43 java.lang.NoSuchMethodException (JDK 1.0) This exception signals that the specified method does not exist in the specified class. public class NoSuchMethodException extends Exception { // Public Constructors public NoSuchMethodException(); public NoSuchMethodException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->NoSuchMethodException
Thrown By: Class.getConstructor(), Class.getDeclaredConstructor(), Class.getDeclaredMethod(), Class.getMethod()
java.lang.NoSuchMethodError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_43.htm [20/12/2001 11:01:23]
java.lang.NullPointerException (JDK 1.0)
[Chapter 20] 20.23 java.awt.event.MouseMotionAdapter (JDK 1.1)
Chapter 20 The java.awt.event Package
20.23 java.awt.event.MouseMotionAdapter (JDK 1.1) This class is a trivial implementation of MouseMotionListener; it provides empty bodies for each of the methods of that interface. When you are not interested in all of these methods, it is often easier to subclass MouseMotionAdapter than it is to implement MouseMotionListener from scratch. public abstract class MouseMotionAdapter extends Object implements MouseMotionListener { // Default Constructor: public MouseMotionAdapter() // Public Instance Methods public void mouseDragged(MouseEvent e); // From MouseMotionListener public void mouseMoved(MouseEvent e); // From MouseMotionListener }
Hierarchy: Object->MouseMotionAdapter(MouseMotionListener(EventListener))
java.awt.event.MouseListener (JDK 1.1)
http://localhost/java/javaref/javanut/ch20_23.htm [20/12/2001 11:01:23]
java.awt.event.MouseMotionListener (JDK 1.1)
[Chapter 18] 18.47 java.awt.Point (JDK 1.0)
Chapter 18 The java.awt Package
18.47 java.awt.Point (JDK 1.0) This class holds the X and Y coordinates of a two-dimensional point. The move() method sets the coordinates, and the translate() method adds the specified values to the coordinates. The x and y fields are public and may be manipulated directly. public class Point extends Object implements Serializable { // Public Constructors 1.1 public Point(); 1.1 public Point(Point p); public Point(int x, int y); // Public Instance Variables public int x; public int y; // Public Instance Methods public boolean equals(Object obj); // Overrides Object 1.1 public Point getLocation(); public int hashCode(); // Overrides Object public void move(int x, int y); 1.1 public void setLocation(Point p); 1.1 public void setLocation(int x, int y); public String toString(); // Overrides Object public void translate(int x, int y); }
Passed To: Component.contains(), Component.getComponentAt(), Component.setLocation(), Container.getComponentAt(), Point(), Point.setLocation(), Polygon.contains(), Rectangle(), Rectangle.add(), Rectangle.contains(), Rectangle.setLocation(), ScrollPane.setScrollPosition()
http://localhost/java/javaref/javanut/ch18_47.htm (1 of 2) [20/12/2001 11:01:24]
[Chapter 18] 18.47 java.awt.Point (JDK 1.0)
Returned By: Component.getLocation(), Component.getLocationOnScreen(), Component.location(), ComponentPeer.getLocationOnScreen(), GridBagLayout.getLayoutOrigin(), GridBagLayout.location(), MouseEvent.getPoint(), Point.getLocation(), Rectangle.getLocation(), ScrollPane.getScrollPosition()
java.awt.Panel (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_47.htm (2 of 2) [20/12/2001 11:01:24]
java.awt.Polygon (JDK 1.0)
[Chapter 15] 15.2 The Tag
Chapter 15 Java-Related HTML Tags
15.2 The Tag The tag, with its NAME and VALUE attributes, specifies a named parameter and its corresponding string value that are passed to the applet. These applet parameters function like system properties or command-line arguments do for a regular application. Any number of tags may appear between <APPLET> and . An applet can look up the value of a parameter specified in a tag with the Applet.getParameter() method, which is something like the System.getProperty() method for Java applications.
The <APPLET> Tag
http://localhost/java/javaref/javanut/ch15_02.htm [20/12/2001 11:01:24]
An Example HTML File
[Chapter 4] 4.12 New JDK Utilities
Chapter 4 What's New in Java 1.1
4.12 New JDK Utilities JDK 1.1 includes a number of new tools. In the discussion of applets above, we've already seen jar for creating JAR archives and javakey for adding digital signatures to JAR archives. In fact, javakey can do much more than that--it is a very flexible tool for managing a database of entities, generating keys and certificates, and generating digital signatures. serialver is a new tool used in conjunction with object serialization. When an object is deserialized, it is important to verify that the version of the class file for that object matches the version that was used to serialize it. This is done by computing a unique identifier for the class and encoding it in a private variable of the class. When an incompatible change is made to the class, a new unique identifier is computed, and the new value is stored in the private variable. It is the serialver tool that is used to compute this unique identifier. native2ascii is a tool for programmers who program in a locale that uses a non-ASCII file encoding. The javac compiler can only compile files encoded in ASCII, with all Unicode characters converted to the \uxxxx format. What native2ascii does is to convert its input file to Unicode, and then output that Unicode version as an ASCII file that uses the \u escape for all non-ASCII Unicode characters. After you process a locally-encoded file with native2ascii, javac can compile it. In addition to the tools described here, JDK 1.1 also includes two new programs, rmic and rmiregistry, that are used in conjunction with Remote Method Invocation. They will be documented in Java Enterprise in a Nutshell.
Applet Changes
http://localhost/java/javaref/javanut/ch04_12.htm [20/12/2001 11:01:24]
Inner Classes and Other New Language Features
[Chapter 30] 30.19 java.util.Random (JDK 1.0)
Chapter 30 The java.util Package
30.19 java.util.Random (JDK 1.0) This class implements a pseudo-random number generator. nextDouble() and nextFloat() return a value between 0.0 and 1.0. nextLong() and nextInt() return long and int values distributed across the range of those data types. nextGaussian() returns pseudo-random values with a Gaussian distribution--the mean of the values is 0.0, and the standard deviation is 1.0. You can use the setSeed() method or the optional constructor argument to initialize the pseudo-random number generator with some variable seed value other than the current time (the default), or with a constant to ensure a repeatable sequence of pseudo-randomness. public class Random extends Object implements Serializable { // Public Constructors public Random(); public Random(long seed); // Public Instance Methods 1.1public void nextBytes(byte[] bytes); public double nextDouble(); public float nextFloat(); public synchronized double nextGaussian(); public int nextInt(); public long nextLong(); public synchronized void setSeed(long seed); // Protected Instance Methods 1.1protected synchronized int next(int bits); }
Passed To: BigInteger()
java.util.PropertyResourceBundle (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_19.htm (1 of 2) [20/12/2001 11:01:24]
java.util.ResourceBundle (JDK 1.1)
[Chapter 30] 30.19 java.util.Random (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_19.htm (2 of 2) [20/12/2001 11:01:24]
[Chapter 28] 28.13 java.net.NoRouteToHostException (JDK 1.1)
Chapter 28 The java.net Package
28.13 java.net.NoRouteToHostException (JDK 1.1) This exception signals that a socket could not be connected to a remote host, because the host could not be contacted. Typically this means that some link in the network between the local machine and the remote host is down, or that the host is behind a firewall. public class NoRouteToHostException extends SocketException { // Public Constructors public NoRouteToHostException(String msg); public NoRouteToHostException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->SocketException->NoRouteToHostException
java.net.MulticastSocket (JDK 1.1)
http://localhost/java/javaref/javanut/ch28_13.htm [20/12/2001 11:01:25]
java.net.ProtocolException (JDK 1.0)
[Chapter 30] 30.14 java.util.NoSuchElementException (JDK 1.0)
Chapter 30 The java.util Package
30.14 java.util.NoSuchElementException (JDK 1.0) Signals that there are no elements in an object (such as a Vector) or that there are no more elements in an object (such as an Enumeration). public class NoSuchElementException extends RuntimeException { // Public Constructors public NoSuchElementException(); public NoSuchElementException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->NoSuchElementException
java.util.MissingResourceException (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_14.htm [20/12/2001 11:01:25]
java.util.Observable (JDK 1.0)
[Chapter 24] 24.36 java.io.NotActiveException (JDK 1.1)
Chapter 24 The java.io Package
24.36 java.io.NotActiveException (JDK 1.1) This exception is thrown in several circumstances. It indicates that the invoked method was not invoked at the right time or in the correct context. Typically it means that an ObjectOutputStream or ObjectInputStream is not currently active, and therefore the requested operation could not be performed. public class NotActiveException extends ObjectStreamException { // Public Constructors public NotActiveException(String reason); public NotActiveException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ObjectStreamException->NotActiveException
Thrown By: ObjectInputStream.defaultReadObject(), ObjectInputStream.registerValidation()
java.io.LineNumberReader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_36.htm [20/12/2001 11:01:25]
java.io.NotSerializableException (JDK 1.1)
[Chapter 24] 24.37 java.io.NotSerializableException (JDK 1.1)
Chapter 24 The java.io Package
24.37 java.io.NotSerializableException (JDK 1.1) This exception signals that an object could not be serialized. It is thrown when serialization is attempted on an instance of a class that does not implement the Serializable interface. Note that it is also thrown when an attempt is made to serialize a Serializable object that refers to (or "contains") an object that is not Serializable. A subclass of a class that is Serializable can prevent itself from being serialized by throwing this exception from its writeObject() and/or readObject() methods. public class NotSerializableException extends ObjectStreamException { // Public Constructors public NotSerializableException(String classname); public NotSerializableException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ObjectStreamException->NotSerializableException
java.io.NotActiveException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_37.htm [20/12/2001 11:01:26]
java.io.ObjectInput (JDK 1.1)
[Chapter 25] 25.44 java.lang.NullPointerException (JDK 1.0)
Chapter 25 The java.lang Package
25.44 java.lang.NullPointerException (JDK 1.0) Signals an attempt to access a field or invoke a method of a null object. public class NullPointerException extends RuntimeException { // Public Constructors public NullPointerException(); public NullPointerException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->NullPointerException
java.lang.NoSuchMethodException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_44.htm [20/12/2001 11:01:26]
java.lang.Number (JDK 1.0)
[Chapter 25] 25.45 java.lang.Number (JDK 1.0)
Chapter 25 The java.lang Package
25.45 java.lang.Number (JDK 1.0) This is an abstract class that is the superclass of Byte, Short, Integer, Long, Float, and Double. It defines the conversion functions that those types all implement. public abstract class Number extends Object implements Serializable { // Default Constructor: public Number() // Public Instance Methods 1.1public byte byteValue(); public abstract double doubleValue(); public abstract float floatValue(); public abstract int intValue(); public abstract long longValue(); 1.1public short shortValue(); }
Extended By: BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short
Returned By: ChoiceFormat.parse(), DecimalFormat.parse(), NumberFormat.parse()
java.lang.NullPointerException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_45.htm [20/12/2001 11:01:26]
java.lang.NumberFormatException (JDK 1.0)
[Chapter 25] 25.46 java.lang.NumberFormatException (JDK 1.0)
Chapter 25 The java.lang Package
25.46 java.lang.NumberFormatException (JDK 1.0) Signals an illegal number format. public class NumberFormatException extends IllegalArgumentException { // Public Constructors public NumberFormatException(); public NumberFormatException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException-> IllegalArgumentException->NumberFormatException
Thrown By: BigDecimal(), BigDecimal.valueOf(), BigInteger(), Byte(), Byte.decode(), Byte.parseByte(), Byte.valueOf(), Color.decode(), Double(), Double.valueOf(), Float(), Float.valueOf(), Integer(), Integer.decode(), Integer.parseInt(), Integer.valueOf(), Long(), Long.parseLong(), Long.valueOf(), Short(), Short.decode(), Short.parseShort(), Short.valueOf()
java.lang.Number (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_46.htm [20/12/2001 11:01:26]
java.lang.Object (JDK 1.0)
[Chapter 13] 13.5 Reserved Words
Chapter 13 Java Syntax
13.5 Reserved Words Table 13.6 lists reserved words in Java. These are keywords or boolean literal values. Note that byvalue, cast, const, future, generic, goto, inner, operator, outer, rest, and var are reserved by Java but currently unused. abstract boolean break byte byvalue case cast catch char class const continue
Table 13.6: Java Reserved Words default goto operator synchronized do if outer this double implements package throw else import private throws extends inner protected transient false instanceof public true final int rest try finally interface return var float long short void for native static volatile future new super while generic null switch
Reserved Method Names Table 13.7 lists the method names of the Object class. Strictly speaking, these method names are not reserved, but since the methods are inherited by every class, they should not be used as the name of a method, except when intentionally overriding an Object method. Table 13.7: Reserved Method Names clone getClass notifyAll equals hashCode toString
http://localhost/java/javaref/javanut/ch13_05.htm (1 of 2) [20/12/2001 11:01:26]
[Chapter 13] 13.5 Reserved Words
finalize notify
wait
Modifiers
http://localhost/java/javaref/javanut/ch13_05.htm (2 of 2) [20/12/2001 11:01:26]
Java Documentation Comment Syntax
[Chapter 9] Object Serialization
Chapter 9
9. Object Serialization Contents: Simple Serialization Custom Serialization Serialization and Class Versioning Serialized Applets Advanced Serialization Object serialization is one of the important new features of Java 1.1. Despite its importance, however, serialization is done with a very simple API. This chapter demonstrates several uses of serialization.
9.1 Simple Serialization Objects are serialized with the ObjectOutputStream and they are deserialized with the ObjectInputStream. Both of these classes are part of the java.io package, and they function, in many ways, like DataOutputStream and DataInputStream because they define the same methods for writing and reading binary representations of Java primitive types to and from streams. What ObjectOutputStream and ObjectInputStream add, however, is the ability to write and read non-primitive object and array values to and from a stream. An object is serialized by passing it to the writeObject() method of an ObjectOutputStream. This writes out the values of all of its fields, including private fields and fields inherited from superclasses. The values of primitive fields are simply written to the stream as they would be with a DataOutputStream. When a field in an object refers to another object, an array, or a string, however, the writeObject() method is invoked recursively to serialize that object as well. If that object (or an array element) refers to another object, writeObject() is again invoked recursively. Thus, a single call to writeObject() may result in an entire "object graph" being serialized. When two or more objects each refer to the other, the serialization algorithm is careful to only output each object once--writeObject() cannot enter infinite recursion. Deserializing an object simply follows the reverse of this process. An object is read from a stream of data by calling the readObject() method of an ObjectInputStream. This re-creates the object in the state it was in when serialized. If the object refers to other objects, they are recursively deserialized as well. This ability to serialize an entire graph of objects and read those objects back in later is a very powerful feature that hides itself in two simple looking methods. We used object serialization in Example 8.1, but unless you were paying attention, you might have missed those crucial writeObject() and readObject() calls. Serialization is used in that Scribble example to give the program an automatic file format for saving the user's scribbles. To refresh your memory, Example 9.1 shows the save() method of that application. Note the creation of the http://localhost/java/javaref/javanut/ch09_01.htm (1 of 2) [20/12/2001 11:01:27]
[Chapter 9] Object Serialization
ObjectOutputStream and the use of the writeObject() method. The corresponding load() method simply reverses the streams to read the scribble back in. You may want to refer to the complete example in Chapter 8, New AWT Features to examine the save() and load() methods in context. Also note the use of a GZIPOutputStream (from java.util.zip) to compress the serialized object data before writing it to disk. Example 9.1: Using Serialized Objects as an Application File Format /** * Prompt the user for a filename, and save the scribble in that file. * Serialize the vector of lines with an ObjectOutputStream. * Compress the serialized objects with a GZIPOutputStream. * Write the compressed, serialized data to a file with a FileOutputStream. * Don't forget to flush and close the stream. */ public void save() { // Create a file dialog to query the user for a filename. FileDialog f = new FileDialog(frame, "Save Scribble", FileDialog.SAVE); f.show(); // Display the dialog and block. String filename = f.getFile(); // Get the user's response if (filename != null) { // If user didn't click "Cancel." try { // Create the necessary output streams to save the scribble. FileOutputStream fos = new FileOutputStream(filename); // Save to file. GZIPOutputStream gzos = new GZIPOutputStream(fos); // Compress. ObjectOutputStream out = new ObjectOutputStream(gzos); // Save objects out.writeObject(lines); // Write the entire Vector of scribbles. out.flush(); // Always flush the output. out.close(); // And close the stream. } // Print out exceptions. We should really display them in a dialog... catch (IOException e) { System.out.println(e); } } }
New Feature Demo
http://localhost/java/javaref/javanut/ch09_01.htm (2 of 2) [20/12/2001 11:01:27]
Custom Serialization
[Chapter 24] 24.44 java.io.ObjectStreamException (JDK 1.1)
Chapter 24 The java.io Package
24.44 java.io.ObjectStreamException (JDK 1.1) This class is the superclass of a number of more specific exception types that may be raised in the process of serializing and deserializing objects with the ObjectOutputStream and ObjectInputStream classes. public abstract class ObjectStreamException extends IOException { // Protected Constructors protected ObjectStreamException(String classname); protected ObjectStreamException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ObjectStreamException
Extended By: InvalidClassException, InvalidObjectException, NotActiveException, NotSerializableException, OptionalDataException, StreamCorruptedException, WriteAbortedException
java.io.ObjectStreamClass (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_44.htm [20/12/2001 11:01:27]
java.io.OptionalDataException (JDK 1.1)
[Chapter 24] 24.38 java.io.ObjectInput (JDK 1.1)
Chapter 24 The java.io Package
24.38 java.io.ObjectInput (JDK 1.1) This interface extends the DataInput interface and adds methods for deserializing objects and reading bytes and arrays of bytes. public abstract interface ObjectInput extends DataInput { // Public Instance Methods public abstract int available() throws IOException; public abstract void close() throws IOException; public abstract int read() throws IOException; public abstract int read(byte[] b) throws IOException; public abstract int read(byte[] b, int off, int len) throws IOException; public abstract Object readObject() throws ClassNotFoundException, IOException; public abstract long skip(long n) throws IOException; }
Implemented By: ObjectInputStream
Passed To: Externalizable.readExternal()
java.io.NotSerializableException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_38.htm [20/12/2001 11:01:27]
java.io.ObjectInputStream (JDK 1.1)
[Chapter 24] 24.40 java.io.ObjectInputValidation (JDK 1.1)
Chapter 24 The java.io Package
24.40 java.io.ObjectInputValidation (JDK 1.1) A class implements this interface and defines the validateObject() method in order to be able to validate itself when it, and all the objects it depends on, have been completely deserialized from an ObjectInputStream. The validateObject() method is only invoked, however, if the object is passed to ObjectInputStream.registerValidation(); this must be done from the readObject() method of the object. Note that if an object is deserialized as part of a larger object graph, its validateObject() method is not invoked until the entire graph is read, and the original call to ObjectInputStream.readObject() is about to return. validateObject() should throw an InvalidObjectException if the object fails validation. This stops object serialization, and causes the original call to ObjectInputStream.readObject() to terminate with the InvalidObjectException exception. public abstract interface ObjectInputValidation { // Public Instance Methods public abstract void validateObject() throws InvalidObjectException; }
Passed To: ObjectInputStream.registerValidation()
java.io.ObjectInputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_40.htm [20/12/2001 11:01:28]
java.io.ObjectOutput (JDK 1.1)
[Chapter 24] 24.41 java.io.ObjectOutput (JDK 1.1)
Chapter 24 The java.io Package
24.41 java.io.ObjectOutput (JDK 1.1) This interface extends the DataOutput interface and adds methods for serializing objects and writing bytes and arrays of bytes. public abstract interface ObjectOutput extends DataOutput { // Public Instance Methods public abstract void close() throws IOException; public abstract void flush() throws IOException; public abstract void write(int b) throws IOException; // From DataOutput public abstract void write(byte[] b) throws IOException; // From DataOutput public abstract void write(byte[] b, int off, int len) throws IOException; // From DataOutput public abstract void writeObject(Object obj) throws IOException; }
Implemented By: ObjectOutputStream
Passed To: Externalizable.writeExternal()
java.io.ObjectInputValidation (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_41.htm [20/12/2001 11:01:28]
java.io.ObjectOutputStream (JDK 1.1)
[Chapter 30] 30.16 java.util.Observer (JDK 1.0)
Chapter 30 The java.util Package
30.16 java.util.Observer (JDK 1.0) This interface defines the update() method required for an object to "observe" subclasses of Observable. An Observer registers interest in an Observable() by calling the Observable.addObserver() method. Observer objects that have been registered in this way will have their update() method invoked by the Observable when that object has changed. public abstract interface Observer { // Public Instance Methods public abstract void update(Observable o, Object arg); }
Passed To: Observable.addObserver(), Observable.deleteObserver()
java.util.Observable (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_16.htm [20/12/2001 11:01:29]
java.util.Properties (JDK 1.0)
[Chapter 28] 28.25 java.net.URLStreamHandler (JDK 1.0)
Chapter 28 The java.net Package
28.25 java.net.URLStreamHandler (JDK 1.0) This abstract class defines the openConnection() method that creates a URLConnection for a given URL. A separate subclass of this class may be defined for various URL protocol types. A URLStreamHandler is created by a URLStreamHandlerFactory. Normal applications never need to use or subclass this class. public abstract class URLStreamHandler extends Object { // Default Constructor: public URLStreamHandler() // Protected Instance Methods protected abstract URLConnection openConnection(URL u) throws IOException; protected void parseURL(URL u, String spec, int start, int limit); protected void setURL(URL u, String protocol, String host, int port, String file, String ref); protected String toExternalForm(URL u); }
Returned By: URLStreamHandlerFactory.createURLStreamHandler()
java.net.URLEncoder (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_25.htm [20/12/2001 11:01:29]
java.net.URLStreamHandlerFactory (JDK 1.0)
[Chapter 24] 24.45 java.io.OptionalDataException (JDK 1.1)
Chapter 24 The java.io Package
24.45 java.io.OptionalDataException (JDK 1.1) This exception is thrown by the readObject() method of an ObjectInputStream when it encounters primitive type data where it expects object data. Despite the exception name, this data is not "optional," and object deserialization is aborted. public class OptionalDataException extends ObjectStreamException { // No Constructor // Public Instance Variables public boolean eof; public int length; }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ObjectStreamException->OptionalDataException
Thrown By: ObjectInputStream.readObject()
java.io.ObjectStreamException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_45.htm [20/12/2001 11:01:30]
java.io.OutputStream (JDK 1.0)
[Chapter 18] 18.61 java.awt.Window (JDK 1.0)
Chapter 18 The java.awt Package
18.61 java.awt.Window (JDK 1.0) This class represents a top-level window with no borders or menu bar. Window is a Container with BorderLayout as its default layout manager. Window is rarely used directly; its subclasses Frame and Dialog are more commonly useful. show() (which overrides Component.show()) makes a Window visible and brings it to the front of other windows. toFront() brings a window to the front, and toBack() buries a window beneath others. pack() is an important method that initiates layout management for the window, and sets the window size to match the preferred size of the components contained within the window. getToolkit() returns the Toolkit() in use for this window. Call dispose() when a Window is no longer needed to free its window system resources. public class Window extends Container { // Public Constructor public Window(Frame parent); // Public Instance Methods public void addNotify(); // Overrides Container 1.1 public synchronized void addWindowListener(WindowListener l); public void dispose(); 1.1 public Component getFocusOwner(); 1.1 public Locale getLocale(); // Overrides Component public Toolkit getToolkit(); // Overrides Component public final String getWarningString(); 1.1 public boolean isShowing(); // Overrides Component public void pack(); 1.1 public boolean postEvent(Event e); // Overrides Component 1.1 public synchronized void removeWindowListener(WindowListener l); public void show(); // Overrides Component public void toBack(); public void toFront(); // Protected Instance Methods 1.1 protected void processEvent(AWTEvent e); // Overrides Container 1.1 protected void processWindowEvent(WindowEvent e); }
http://localhost/java/javaref/javanut/ch18_61.htm (1 of 2) [20/12/2001 11:01:30]
[Chapter 18] 18.61 java.awt.Window (JDK 1.0)
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Container->Window
Extended By: Dialog, Frame
Passed To: Toolkit.createWindow(), WindowEvent()
Returned By: WindowEvent.getWindow()
java.awt.Toolkit (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_61.htm (2 of 2) [20/12/2001 11:01:30]
The java.awt.datatransfer Package
[Chapter 18] 18.46 java.awt.Panel (JDK 1.0)
Chapter 18 The java.awt Package
18.46 java.awt.Panel (JDK 1.0) This class is a Container that is itself contained within a container. Unlike Frame and Dialog, Panel is a container that does not create a separate window of its own. Panel is suitable for holding portions of a larger interface within a parent Frame or Dialog or within another Panel. (Note that Applet is a subclass of Panel, and thus applets are displayed in a Panel that is contained within a Web browser or applet viewer.) The default LayoutManager for a Panel is FlowLayout. public class Panel extends Container { // Public Constructors public Panel(); 1.1 public Panel(LayoutManager layout); // Public Instance Methods public void addNotify(); // Overrides Container }
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Container->Panel
Extended By: Applet
Passed To: Toolkit.createPanel()
java.awt.MenuShortcut (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_46.htm [20/12/2001 11:01:30]
java.awt.Point (JDK 1.0)
[Chapter 22] 22.19 java.awt.peer.PanelPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.19 java.awt.peer.PanelPeer (JDK 1.0) public interface PanelPeer extends ContainerPeer { }
Hierarchy: (PanelPeer(ContainerPeer(ComponentPeer)))
Returned By: Toolkit.createPanel()
java.awt.peer.MenuPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_19.htm [20/12/2001 11:01:30]
java.awt.peer.PopupMenuPeer (JDK 1.1)
[Chapter 29] 29.15 java.text.ParseException (JDK 1.1)
Chapter 29 The java.text Package
29.15 java.text.ParseException (JDK 1.1) This exception signals that a string had an incorrect format and could not be parsed. It is typically thrown by the parse() or parseObject() methods of Format and its subclasses, but is also thrown by certain methods in the java.text package that are passed patterns or other rules in string form. The getErrorOffset() method of this class returns the character position at which the parsing error occurred in the offending string. public class ParseException extends Exception { // Public Constructor public ParseException(String s, int errorOffset); // Public Instance Methods public int getErrorOffset(); }
Hierarchy: Object->Throwable(Serializable)->Exception->ParseException
Thrown By: DateFormat.parse(), Format.parseObject(), MessageFormat.parse(), NumberFormat.parse(), RuleBasedCollator()
java.text.NumberFormat (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_15.htm [20/12/2001 11:01:31]
java.text.ParsePosition (JDK 1.1)
[Chapter 30] 30.22 java.util.Stack (JDK 1.0)
Chapter 30 The java.util Package
30.22 java.util.Stack (JDK 1.0) This class implements a last-in-first-out stack of objects. push() puts an object on the top of the stack. pop() removes and returns the top object from the stack. peek() returns the top object without removing it. public class Stack extends Vector { // Default Constructor: public Stack() // Public Instance Methods public boolean empty(); public synchronized Object peek(); public synchronized Object pop(); public Object push(Object item); public synchronized int search(Object o); }
Hierarchy: Object->Vector(Cloneable, Serializable)->Stack
java.util.SimpleTimeZone (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_22.htm [20/12/2001 11:01:31]
java.util.StringTokenizer (JDK 1.0)
[Chapter 24] 24.50 java.io.PipedReader (JDK 1.1)
Chapter 24 The java.io Package
24.50 java.io.PipedReader (JDK 1.1) PipedReader is a character input stream that reads characters from a PipedWriter character output stream to which it is connected. PipedReader implements one-half of a pipe, and is useful for communication between two threads of an application. A PipedReader cannot be used until it is connected to a PipedWriter object, which may be passed to the PipedReader() constructor or to the connect() method. PipedReader inherits most of the methods of its superclass. See Reader for more information. PipedReader is the character stream analog of PipedInputStream. public class PipedReader extends Reader { // Public Constructors public PipedReader(); public PipedReader(PipedWriter src) throws IOException; // Public Instance Methods public void close() throws IOException; // Defines Reader public void connect(PipedWriter src) throws IOException; public int read(char[] cbuf, int off, int len) throws IOException; Defines Reader }
Hierarchy: Object->Reader->PipedReader
Passed To: PipedWriter(), PipedWriter.connect()
java.io.PipedOutputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_50.htm [20/12/2001 11:01:31]
java.io.PipedWriter (JDK 1.1)
//
[Chapter 24] 24.51 java.io.PipedWriter (JDK 1.1)
Chapter 24 The java.io Package
24.51 java.io.PipedWriter (JDK 1.1) PipedWriter is a character output stream that writes characters to the PipedReader character input stream to which it is connected. PipedWriter implements one half of a pipe, and is useful for communication between two threads of an application. A PipedWriter cannot be used until it is connected to a PipedReader object, which may be passed to the PipedWriter() constructor, or to the connect() method. PipedWriter inherits most of the methods of its superclass. See Writer for more information. PipedWriter is the character stream analog of PipedOutputStream. public class PipedWriter extends Writer { // Public Constructors public PipedWriter(); public PipedWriter(PipedReader sink) throws IOException; // Public Instance Methods public void close() throws IOException; // Defines Writer public void connect(PipedReader sink) throws IOException; public void flush() throws IOException; // Defines Writer public void write(char[] cbuf, int off, int len) throws IOException; Defines Writer }
Hierarchy: Object->Writer->PipedWriter
Passed To: PipedReader(), PipedReader.connect()
java.io.PipedReader (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_51.htm [20/12/2001 11:01:31]
java.io.PrintStream (JDK 1.0)
//
[Chapter 24] 24.52 java.io.PrintStream (JDK 1.0)
Chapter 24 The java.io Package
24.52 java.io.PrintStream (JDK 1.0) This class is a FilterOutputStream that implements a number of methods for displaying textual representation of Java primitive data types. The print() methods output a standard textual representation of each data type. The println() methods do the same, and follow that representation with a newline. The methods convert various Java primitive types to String representations and then output the resulting string. When an Object is passed to a print() or println(), it is converted to a String by calling its toString() method. PrintStream is the OutputStream type that makes it easiest to output text. As such, it is the most commonly used of the output streams. The System.out variable is a PrintStream. Note that in Java 1.0 this class does not handle Unicode characters correctly--it discards the top 8 bits of all 16-bit characters, and thus works only with Latin-1 (ISO8859-1) characters. Although this problem has been fixed in Java 1.1, PrintStream has been superseded in Java 1.1 with PrintWriter. The constructors of this class have been deprecated, but the class itself has not, because it is still used by the System.out and System.err standard output streams. PrintStream and its PrintWriter replacement output textual representations of Java data types. Use DataOutputStream to output binary representations of data. public class PrintStream extends FilterOutputStream { // Public Constructors # public PrintStream(OutputStream out); # public PrintStream(OutputStream out, boolean autoFlush); // Public Instance Methods public boolean checkError(); public void close(); // Overrides FilterOutputStream public void flush(); // Overrides FilterOutputStream public void print(boolean b); public void print(char c); public void print(int i); public void print(long l); public void print(float f); public void print(double d); public void print(char[] s); public void print(String s); public void print(Object obj); http://localhost/java/javaref/javanut/ch24_52.htm (1 of 2) [20/12/2001 11:01:32]
[Chapter 24] 24.52 java.io.PrintStream (JDK 1.0)
public void println(); public void println(boolean x); public void println(char x); public void println(int x); public void println(long x); public void println(float x); public void println(double x); public void println(char[] x); public void println(String x); public void println(Object x); public void write(int b); // Overrides FilterOutputStream public void write(byte[] buf, int off, int len); // Overrides FilterOutputStream // Protected Instance Methods 1.1 protected void setError(); }
Hierarchy: Object->OutputStream->FilterOutputStream->PrintStream
Passed To: Component.list(), Container.list(), Properties.list(), System.setErr(), System.setOut(), Throwable.printStackTrace()
Type Of: System.err, System.out
java.io.PipedWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_52.htm (2 of 2) [20/12/2001 11:01:32]
java.io.PrintWriter (JDK 1.1)
[Chapter 30] 30.18 java.util.PropertyResourceBundle (JDK 1.1)
Chapter 30 The java.util Package
30.18 java.util.PropertyResourceBundle (JDK 1.1) This class is a concrete subclass of ResourceBundle. It reads a Properties file from a specified InputStream and implements the ResourceBundle API for looking up named resources from the resulting Properties object. A Properties file contains lines of the form: name=value Each such line defines a named property with the specified String value. Although you can instantiate a PropertyResourceBundle yourself, it is more common to simply define a Properties file, and then allow ResourceBundle.getBundle() to look up that file and return the necessary PropertyResourceBundle object. See also Properties and ResourceBundle. public class PropertyResourceBundle extends ResourceBundle { // Public Constructor public PropertyResourceBundle(InputStream stream) throws IOException; // Public Instance Methods public Enumeration getKeys(); // Defines ResourceBundle public Object handleGetObject(String key); // Defines ResourceBundle }
Hierarchy: Object->ResourceBundle->PropertyResourceBundle
java.util.Properties (JDK 1.0)
http://localhost/java/javaref/javanut/ch30_18.htm [20/12/2001 11:01:33]
java.util.Random (JDK 1.0)
[Chapter 28] 28.14 java.net.ProtocolException (JDK 1.0)
Chapter 28 The java.net Package
28.14 java.net.ProtocolException (JDK 1.0) Signals a protocol error in the Socket class. public class ProtocolException extends IOException { // Public Constructors public ProtocolException(String host); public ProtocolException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ProtocolException
Thrown By: HttpURLConnection.setRequestMethod()
java.net.NoRouteToHostException (JDK 1.1)
http://localhost/java/javaref/javanut/ch28_14.htm [20/12/2001 11:01:35]
java.net.ServerSocket (JDK 1.0)
[Chapter 24] 24.55 java.io.PushbackReader (JDK 1.1)
Chapter 24 The java.io Package
24.55 java.io.PushbackReader (JDK 1.1) This class is a character input stream that uses another input stream as its input source, and adds the ability to push characters back onto the stream. This feature is often useful when writing parsers. When you create a PushbackReader stream, you specify the stream to be read from, and may optionally specify the size of the pushback buffer--i.e., the number of characters that may be pushed back onto the stream or "unread." If you do not specify a size for this buffer, the default size is one character. PushbackReader inherits or overrides all the standard Reader methods, and also adds three unread() methods that are used to push a single character, an array of characters, or a portion of an array of characters back onto the stream. This class is the character stream analog of PushbackInputStream. public class PushbackReader extends FilterReader { // Public Constructors public PushbackReader(Reader in, int size); public PushbackReader(Reader in); // Public Instance Methods public void close() throws IOException; // Overrides FilterReader public boolean markSupported(); // Overrides FilterReader public int read() throws IOException; // Overrides FilterReader public int read(char[] cbuf, int off, int len) throws IOException; // Overrides FilterReader public boolean ready() throws IOException; // Overrides FilterReader public void unread(int c) throws IOException; public void unread(char[] cbuf, int off, int len) throws IOException; public void unread(char[] cbuf) throws IOException; }
Hierarchy: Object->Reader->FilterReader->PushbackReader
java.io.PushbackInputStream (JDK 1.0)
http://localhost/java/javaref/javanut/ch24_55.htm [20/12/2001 11:01:36]
java.io.RandomAccessFile (JDK 1.0)
[Chapter 18] 18.52 java.awt.Rectangle (JDK 1.0)
Chapter 18 The java.awt Package
18.52 java.awt.Rectangle (JDK 1.0) This class defines a rectangle as the X and Y coordinate of its upper-left corner and a width and height. The instance methods perform various tests and transformations on the rectangle. The x, y, width, and height variables are public and may thus be manipulated directly. Rectangle objects are used in several places in the java.awt package to specify clipping rectangles and bounding boxes. public class Rectangle extends Object implements Shape, Serializable { // Public Constructors public Rectangle(); 1.1 public Rectangle(Rectangle r); public Rectangle(int x, int y, int width, int height); public Rectangle(int width, int height); public Rectangle(Point p, Dimension d); public Rectangle(Point p); public Rectangle(Dimension d); // Public Instance Variables public int height; public int width; public int x; public int y; // Public Instance Methods public void add(int newx, int newy); public void add(Point pt); public void add(Rectangle r); 1.1 public boolean contains(Point p); 1.1 public boolean contains(int x, int y); public boolean equals(Object obj); // Overrides Object 1.1 public Rectangle getBounds(); // From Shape 1.1 public Point getLocation(); 1.1 public Dimension getSize(); public void grow(int h, int v); public int hashCode(); // Overrides Object # public boolean inside(int x, int y); public Rectangle intersection(Rectangle r);
http://localhost/java/javaref/javanut/ch18_52.htm (1 of 2) [20/12/2001 11:01:37]
[Chapter 18] 18.52 java.awt.Rectangle (JDK 1.0)
# # # 1.1 1.1 1.1 1.1 1.1 1.1
public boolean intersects(Rectangle r); public boolean isEmpty(); public void move(int x, int y); public void reshape(int x, int y, int width, int height); public void resize(int width, int height); public void setBounds(Rectangle r); public void setBounds(int x, int y, int width, int height); public void setLocation(Point p); public void setLocation(int x, int y); public void setSize(Dimension d); public void setSize(int width, int height); public String toString(); // Overrides Object public void translate(int x, int y); public Rectangle union(Rectangle r);
}
Passed To: Component.setBounds(), GridBagLayout.AdjustForGravity(), PaintEvent(), PaintEvent.setUpdateRect(), PropertyEditor.paintValue(), PropertyEditorSupport.paintValue(), Rectangle(), Rectangle.add(), Rectangle.intersection(), Rectangle.intersects(), Rectangle.setBounds(), Rectangle.union()
Returned By: Component.bounds(), Component.getBounds(), Graphics.getClipBounds(), Graphics.getClipRect(), PaintEvent.getUpdateRect(), Polygon.getBoundingBox(), Polygon.getBounds(), Rectangle.getBounds(), Rectangle.intersection(), Rectangle.union(), Shape.getBounds()
Type Of: Polygon.bounds
java.awt.PrintJob (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_52.htm (2 of 2) [20/12/2001 11:01:37]
java.awt.ScrollPane (JDK 1.1)
[Chapter 25] 25.50 java.lang.Runnable (JDK 1.0)
Chapter 25 The java.lang Package
25.50 java.lang.Runnable (JDK 1.0) This interface specifies the run() method that is required for use with the Thread class. Any class that implements this interface can provide the "body" of a thread. See Thread for more information. public abstract interface Runnable { // Public Instance Methods public abstract void run(); }
Implemented By: Thread
Passed To: Thread()
java.lang.Process (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_50.htm [20/12/2001 11:01:38]
java.lang.Runtime (JDK 1.0)
[Chapter 25] 25.52 java.lang.RuntimeException (JDK 1.0)
Chapter 25 The java.lang Package
25.52 java.lang.RuntimeException (JDK 1.0) This exception type is not used directly, but serves as a superclass of a group of run-time exceptions that need not be declared in the throws clause of a method definition. These exceptions need not be declared because they are run-time conditions that can generally occur in any Java method. Thus, declaring them would be unduly burdensome, and Java does not require it. public class RuntimeException extends Exception { // Public Constructors public RuntimeException(); public RuntimeException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException
Extended By: ArithmeticException, ArrayStoreException, ClassCastException, EmptyStackException, IllegalArgumentException, IllegalMonitorStateException, IllegalStateException, IndexOutOfBoundsException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NullPointerException, SecurityException
java.lang.Runtime (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_52.htm [20/12/2001 11:01:38]
java.lang.SecurityException (JDK 1.0)
[Chapter 18] 18.54 java.awt.Scrollbar (JDK 1.0)
Chapter 18 The java.awt Package
18.54 java.awt.Scrollbar (JDK 1.0) This Component represents a graphical scrollbar. setValue() sets the displayed value of the scrollbar. setValues() sets the displayed value, the page size, and the minimum and maximum values. The constants HORIZONTAL and VERTICAL are legal values for the scrollbar orientation. public class Scrollbar extends Component implements Adjustable { // Public Constructors public Scrollbar(); public Scrollbar(int orientation); public Scrollbar(int orientation, int value, int visible, int minimum, int maximum); // Constants public static final int HORIZONTAL; public static final int VERTICAL; // Public Instance Methods 1.1 public synchronized void addAdjustmentListener(AdjustmentListener l); // From Adjustable public void addNotify(); // Overrides Component 1.1 public int getBlockIncrement(); // From Adjustable # public int getLineIncrement(); public int getMaximum(); // From Adjustable public int getMinimum(); // From Adjustable public int getOrientation(); // From Adjustable # public int getPageIncrement(); 1.1 public int getUnitIncrement(); // From Adjustable public int getValue(); // From Adjustable # public int getVisible(); 1.1 public int getVisibleAmount(); // From Adjustable 1.1 public synchronized void removeAdjustmentListener(AdjustmentListener l); // From Adjustable 1.1 public synchronized void setBlockIncrement(int v); // From Adjustable # public void setLineIncrement(int v); 1.1 public synchronized void setMaximum(int newMaximum); // From Adjustable 1.1 public synchronized void setMinimum(int newMinimum); // From Adjustable 1.1 public synchronized void setOrientation(int orientation); # public void setPageIncrement(int v); 1.1 public synchronized void setUnitIncrement(int v); // From Adjustable public synchronized void setValue(int newValue); // From Adjustable public synchronized void setValues(int value, int visible, int minimum, int maximum); 1.1 public synchronized void setVisibleAmount(int newAmount); // From Adjustable // Protected Instance Methods http://localhost/java/javaref/javanut/ch18_54.htm (1 of 2) [20/12/2001 11:01:38]
[Chapter 18] 18.54 java.awt.Scrollbar (JDK 1.0)
1.1 1.1
protected String paramString(); // Overrides Component protected void processAdjustmentEvent(AdjustmentEvent e); protected void processEvent(AWTEvent e); // Overrides Component
}
Hierarchy: Object->Component(ImageObserver, MenuContainer, Serializable)->Scrollbar(Adjustable)
Passed To: Toolkit.createScrollbar()
java.awt.ScrollPane (JDK 1.1)
java.awt.Shape (JDK 1.1)
http://localhost/java/javaref/javanut/ch18_54.htm (2 of 2) [20/12/2001 11:01:38]
[Chapter 22] 22.22 java.awt.peer.ScrollbarPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.22 java.awt.peer.ScrollbarPeer (JDK 1.0) public abstract interface ScrollbarPeer extends ComponentPeer { // Public Instance Methods public abstract void setLineIncrement(int l); public abstract void setPageIncrement(int l); public abstract void setValues(int value, int visible, int minimum, int maximum); }
Returned By: Toolkit.createScrollbar()
java.awt.peer.ScrollPanePeer (JDK 1.1)
http://localhost/java/javaref/javanut/ch22_22.htm [20/12/2001 11:01:39]
java.awt.peer.TextAreaPeer (JDK 1.0)
[Chapter 8] New AWT Features
Chapter 8
8. New AWT Features Contents: The ScrollPane Container Popup Menus and Menu Shortcuts Printing Data Transfer with Cut-and-Paste New Feature Demo In addition to the new AWT event model that we saw in Chapter 7, Events, there are a number of important new AWT features in Java 1.1. These new features were outlined in Chapter 4, What's New in Java 1.1. This chapter details many of those new features and demonstrates them in a single extended example application at the end of the chapter. The major features of the example are: ● The new ScrollPane component ● Popup menus and menu shortcuts ● Printing ● Data transfer through cut-and-paste In addition, the example also demonstrates the use of object serialization to save and load application state. This functionality is described in Chapter 9, Object Serialization.
8.1 The ScrollPane Container The new ScrollPane container holds a single child component that is usually larger than the ScrollPane itself. The ScrollPane displays a fixed-size area of the child and provides horizontal and vertical scrollbars so the user can scroll the child component within the "viewport" of the ScrollPane. Figure 8.1 shows a top-level window created by the application listed in Example 8.1 at the end of this chapter. As you can see, the application creates a ScrollPane container to hold the larger Scribble component that supports free-hand drawing. Figure 8.1: New AWT features demo application
http://localhost/java/javaref/javanut/ch08_01.htm (1 of 2) [20/12/2001 11:01:39]
[Chapter 8] New AWT Features
The ScrollPane is quite easy to use. Simply create it and add a child component as you would with any other container. Note, however, that ScrollPane only supports a single child and it cannot have a LayoutManager specified. The ScrollPane is created in the ScribbleFrame() constructor of the example. The important thing to note is that the ScrollPane does not have any preferred or natural size of its own, so you should use setSize() to specify the size you want it to be. The ScrollPane class defines three constants that are legal values of its "scrollbar display policy." Because the example does not specify one of these constants, the policy defaults to SCROLLBARS_AS_NEEDED, which indicates that scrollbars are displayed for any dimension in which the contained child is larger than the available "viewport" space of the ScrollPane container. Here is an excerpt of the ScribbleFrame() constructor that shows the creation of the ScrollPane: ScrollPane pane = new ScrollPane(); pane.setSize(300, 300); this.add(pane, "Center"); Scribble scribble; scribble = new Scribble(this, 500, 500); pane.add(scribble);
Inside the Java 1.1 Event Model
http://localhost/java/javaref/javanut/ch08_01.htm (2 of 2) [20/12/2001 11:01:39]
// Create a ScrollPane. // Specify its size. // Add it to the frame. // Create a bigger scribble area. // Add it to the ScrollPane.
Popup Menus and Menu Shortcuts
[Chapter 22] 22.21 java.awt.peer.ScrollPanePeer (JDK 1.1)
Chapter 22 The java.awt.peer Package
22.21 java.awt.peer.ScrollPanePeer (JDK 1.1) public abstract interface ScrollPanePeer extends ContainerPeer { // Public Instance Methods public abstract void childResized(int w, int h); public abstract int getHScrollbarHeight(); public abstract int getVScrollbarWidth(); public abstract void setScrollPosition(int x, int y); public abstract void setUnitIncrement(Adjustable adj, int u); public abstract void setValue(Adjustable adj, int v); }
Hierarchy: (ScrollPanePeer(ContainerPeer(ComponentPeer)))
Returned By: Toolkit.createScrollPane()
java.awt.peer.PopupMenuPeer (JDK 1.1)
http://localhost/java/javaref/javanut/ch22_21.htm [20/12/2001 11:01:40]
java.awt.peer.ScrollbarPeer (JDK 1.0)
[Chapter 25] 25.53 java.lang.SecurityException (JDK 1.0)
Chapter 25 The java.lang Package
25.53 java.lang.SecurityException (JDK 1.0) Signals that an operation is not permitted for security reasons. public class SecurityException extends RuntimeException { // Public Constructors public SecurityException(); public SecurityException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException->SecurityException
Thrown By: Beans.setDesignTime(), Beans.setGuiAvailable(), Class.getConstructor(), Class.getConstructors(), Class.getDeclaredClasses(), Class.getDeclaredConstructor(), Class.getDeclaredConstructors(), Class.getDeclaredField(), Class.getDeclaredFields(), Class.getDeclaredMethod(), Class.getDeclaredMethods(), Class.getField(), Class.getFields(), Class.getMethod(), Class.getMethods(), ObjectInputStream.enableResolveObject(), ObjectOutputStream.enableReplaceObject()
java.lang.RuntimeException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_53.htm [20/12/2001 11:01:40]
java.lang.SecurityManager (JDK 1.0)
[Chapter 25] 25.54 java.lang.SecurityManager (JDK 1.0)
Chapter 25 The java.lang Package
25.54 java.lang.SecurityManager (JDK 1.0) This abstract class defines the methods necessary to implement a security policy for the execution of untrusted code. Before performing potentially sensitive operations, Java calls methods of the SecurityManager object currently in effect to determine whether the operations are permitted. These methods throw a SecurityException if the operation is not permitted. Normal applications do not need to use or subclass the SecurityManager class. It is typically only used by Web browsers, applet viewers, and other programs that need to run untrusted code in a controlled environment. public abstract class SecurityManager extends Object { // Protected Constructor protected SecurityManager(); // Protected Instance Variables protected boolean inCheck; // Public Instance Methods public void checkAccept(String host, int port); public void checkAccess(Thread g); public void checkAccess(ThreadGroup g); 1.1public void checkAwtEventQueueAccess(); public void checkConnect(String host, int port); public void checkConnect(String host, int port, Object context); public void checkCreateClassLoader(); public void checkDelete(String file); public void checkExec(String cmd); public void checkExit(int status); public void checkLink(String lib); public void checkListen(int port); 1.1public void checkMemberAccess(Class clazz, int which); 1.1public void checkMulticast(InetAddress maddr); 1.1public void checkMulticast(InetAddress maddr, byte ttl); public void checkPackageAccess(String pkg); public void checkPackageDefinition(String pkg); 1.1public void checkPrintJobAccess(); public void checkPropertiesAccess(); public void checkPropertyAccess(String key); public void checkRead(FileDescriptor fd); public void checkRead(String file);
http://localhost/java/javaref/javanut/ch25_54.htm (1 of 2) [20/12/2001 11:01:40]
[Chapter 25] 25.54 java.lang.SecurityManager (JDK 1.0)
public void checkRead(String file, Object context); 1.1public void checkSecurityAccess(String action); public void checkSetFactory(); 1.1public void checkSystemClipboardAccess(); public boolean checkTopLevelWindow(Object window); public void checkWrite(FileDescriptor fd); public void checkWrite(String file); public boolean getInCheck(); public Object getSecurityContext(); 1.1public ThreadGroup getThreadGroup(); // Protected Instance Methods protected native int classDepth(String name); protected native int classLoaderDepth(); protected native ClassLoader currentClassLoader(); 1.1protected Class currentLoadedClass(); protected native Class[] getClassContext(); protected boolean inClass(String name); protected boolean inClassLoader(); }
Passed To: System.setSecurityManager()
Returned By: System.getSecurityManager()
java.lang.SecurityException (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_54.htm (2 of 2) [20/12/2001 11:01:40]
java.lang.Short (JDK 1.1)
[Chapter 19] 19.4 java.awt.datatransfer.StringSelection (JDK 1.1)
Chapter 19 The java.awt.datatransfer Package
19.4 java.awt.datatransfer.StringSelection (JDK 1.1) This convenience class implements the Transferable and ClipboardOwner interfaces in order to make it very easy to transfer String values through the AWT data transfer mechanism. It is able to transfer String values using either the DataFlavor.stringFlavor or DataFlavor.plainTextFlavor data flavors. To create a StringSelection object, simply pass the String you want to transfer to the StringSelection() constructor. You can then make the StringSelection available for transfer by passing it to the setContents() method of the Clipboard. You need never call the methods of StringSelection yourself. public class StringSelection extends Object implements Transferable, ClipboardOwner { // Public Constructor public StringSelection(String data); // Public Instance Methods public synchronized Object getTransferData(DataFlavor flavor) public synchronized Object getTransferData'u'throws UnsupportedFlavorException, IOException; public synchronized Object getTransferData'u'// From Transferable public synchronized DataFlavor[] getTransferDataFlavors(); // From Transferable public boolean isDataFlavorSupported(DataFlavor flavor); // From Transferable public void lostOwnership(Clipboard clipboard, Transferable contents); // From ClipboardOwner }
java.awt.datatransfer.DataFlavor (JDK 1.1)
http://localhost/java/javaref/javanut/ch19_04.htm [20/12/2001 11:01:40]
java.awt.datatransfer.Transferable (JDK 1.1)
[Chapter 30] 30.21 java.util.SimpleTimeZone (JDK 1.1)
Chapter 30 The java.util Package
30.21 java.util.SimpleTimeZone (JDK 1.1) This concrete subclass of TimeZone is a simple implementation of that abstract class, and is suitable for use in locales that use the Gregorian calendar. Programs do not usually need to instantiate this class directly; instead, they use one of the static "factory" methods of TimeZone to obtain a suitable TimeZone subclass. You would instantiate this class directly only if you needed to support a time zone with nonstandard daylight savings time rules. In that case, you would use call setStartRule() and setEndRule() to specify the starting and ending dates of daylight savings time for the time zone. public class SimpleTimeZone extends TimeZone { // Public Constructors public SimpleTimeZone(int rawOffset, String ID); public SimpleTimeZone(int rawOffset, String ID, int startMonth, int startDayOfWeekInMonth, int startDayOfWeek, int startTime, int endMonth, int endDayOfWeekInMonth, int endDayOfWeek, int endTime); // Public Instance Methods public Object clone(); // Overrides TimeZone public boolean equals(Object obj); // Overrides Object public int getOffset(int era, int year, int month, int day, int dayOfWeek, int millis); // Defines TimeZone public int getRawOffset(); // Defines TimeZone public synchronized int hashCode(); // Overrides Object public boolean inDaylightTime(Date date); // Defines TimeZone public void setEndRule(int month, int dayOfWeekInMonth, int dayOfWeek, int time); public void setRawOffset(int offsetMillis); // Defines TimeZone public void setStartRule(int month, int dayOfWeekInMonth, int dayOfWeek, int time); public void setStartYear(int year); public boolean useDaylightTime(); // Defines TimeZone }
Hierarchy: Object->TimeZone(Serializable, Cloneable)->SimpleTimeZone
java.util.ResourceBundle (JDK 1.1)
http://localhost/java/javaref/javanut/ch30_21.htm [20/12/2001 11:01:41]
java.util.Stack (JDK 1.0)
[Chapter 18] 18.55 java.awt.Shape (JDK 1.1)
Chapter 18 The java.awt Package
18.55 java.awt.Shape (JDK 1.1) This interface encapsulates some very generic information about geometric shapes. All Shape objects must have a bounding box--i.e., a rectangle that completely encloses the represented shape. When the forthcoming Java2D API is integrated with the AWT, this interface may be changed. For this reason, Java 1.1 applications can use this interface, but should not implement it in their own classes. public abstract interface Shape { // Public Instance Methods public abstract Rectangle getBounds(); }
Implemented By: Polygon, Rectangle
Passed To: Graphics.setClip()
Returned By: Graphics.getClip()
java.awt.Scrollbar (JDK 1.0)
http://localhost/java/javaref/javanut/ch18_55.htm [20/12/2001 11:01:41]
java.awt.SystemColor (JDK 1.1)
[Chapter 28] 28.17 java.net.SocketException (JDK 1.0)
Chapter 28 The java.net Package
28.17 java.net.SocketException (JDK 1.0) Signals an exceptional condition while using a socket. public class SocketException extends IOException { // Public Constructors public SocketException(String msg); public SocketException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->SocketException
Extended By: BindException, ConnectException, NoRouteToHostException
Thrown By: DatagramSocket(), DatagramSocket.getSoTimeout(), DatagramSocket.setSoTimeout(), DatagramSocketImpl.bind(), DatagramSocketImpl.create(), DatagramSocketImpl.getOption(), DatagramSocketImpl.setOption(), MulticastSocket.getInterface(), MulticastSocket.setInterface(), ServerSocket.setSoTimeout(), Socket(), Socket.getSoLinger(), Socket.getSoTimeout(), Socket.getTcpNoDelay(), Socket.setSoLinger(), Socket.setSoTimeout(), Socket.setTcpNoDelay(), SocketImpl.getOption(), SocketImpl.setOption()
java.net.Socket (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_17.htm [20/12/2001 11:01:42]
java.net.SocketImpl (JDK 1.0)
[Chapter 28] 28.18 java.net.SocketImpl (JDK 1.0)
Chapter 28 The java.net Package
28.18 java.net.SocketImpl (JDK 1.0) This abstract class defines the methods necessary to implement communication through sockets. Different subclasses of this class may provide different implementations suitable in different environments (such as behind firewalls). These socket implementations are used by the Socket and ServerSocket classes. Normal applications never need to use or subclass this class. public abstract class SocketImpl extends Object { // Default Constructor: public SocketImpl() // Protected Instance Variables protected InetAddress address; protected FileDescriptor fd; protected int localport; protected int port; // Public Instance Methods public String toString(); // Overrides Object // Protected Instance Methods protected abstract void accept(SocketImpl s) throws IOException; protected abstract int available() throws IOException; protected abstract void bind(InetAddress host, int port) throws IOException; protected abstract void close() throws IOException; protected abstract void connect(String host, int port) throws IOException; protected abstract void connect(InetAddress address, int port) throws IOException; protected abstract void create(boolean stream) throws IOException; protected FileDescriptor getFileDescriptor(); protected InetAddress getInetAddress(); protected abstract InputStream getInputStream() throws IOException; protected int getLocalPort(); protected abstract OutputStream getOutputStream() throws IOException; protected int getPort(); protected abstract void listen(int backlog) throws IOException; }
Passed To: Socket(), SocketImpl.accept()
http://localhost/java/javaref/javanut/ch28_18.htm (1 of 2) [20/12/2001 11:01:42]
[Chapter 28] 28.18 java.net.SocketImpl (JDK 1.0)
Returned By: SocketImplFactory.createSocketImpl()
java.net.SocketException (JDK 1.0)
java.net.SocketImplFactory (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_18.htm (2 of 2) [20/12/2001 11:01:42]
[Chapter 28] 28.19 java.net.SocketImplFactory (JDK 1.0)
Chapter 28 The java.net Package
28.19 java.net.SocketImplFactory (JDK 1.0) This interface defines a method that creates SocketImpl objects. SocketImplFactory objects may be registered to create SocketImpl objects for the Socket and ServerSocket classes. Normal applications never need to use or implement this interface. public abstract interface SocketImplFactory { // Public Instance Methods public abstract SocketImpl createSocketImpl(); }
Passed To: ServerSocket.setSocketFactory(), Socket.setSocketImplFactory()
java.net.SocketImpl (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_19.htm [20/12/2001 11:01:42]
java.net.UnknownHostException (JDK 1.0)
[Chapter 2] 2.10 Strings
Chapter 2 How Java Differs from C
2.10 Strings Strings in Java are not null-terminated arrays of characters as they are in C. Instead, they are instances of the java.lang.String class. Java strings are unusual, in that the compiler treats them almost as if they were primitive types--for example, it automatically creates a String object when it encounters a double-quoted constant in the program. And, the language defines an operator that operates on String objects--the + operator for string concatenation. An important feature of String objects is that they are immutable--i.e., there are no methods defined that allow you to change the contents of a String. If you need to modify the contents of a String, you have to create a StringBuffer object from the String object, modify the contents of the StringBuffer, and then create a new String from the contents of the StringBuffer. Note that it is moot to ask whether Java strings are terminated with a NUL character (\u0000) or not. Java performs run-time bounds checking on all array and string accesses, so there is no way to examine the value of any internal terminator character that appears after the last character of the string. Both the String and StringBuffer classes are documented in Chapter 25, The java.lang Package, and you'll find a complete set of methods for string handling and manipulation there. Some of the more important String methods are: length(), charAt(), equals(), compareTo(), indexOf(), lastIndexOf(), and substring().
Arrays
http://localhost/java/javaref/javanut/ch02_10.htm [20/12/2001 11:01:42]
Operators
[Chapter 29] 29.19 java.text.StringCharacterIterator (JDK 1.1)
Chapter 29 The java.text Package
29.19 java.text.StringCharacterIterator (JDK 1.1) This class is a trivial implementation of the CharacterIterator interface that works for text stored in Java String objects. See CharacterIterator for details. public final class StringCharacterIterator extends Object implements CharacterIterator { // Public Constructors public StringCharacterIterator(String text); public StringCharacterIterator(String text, int pos); public StringCharacterIterator(String text, int begin, int end, int pos); // Public Instance Methods public Object clone(); // Overrides Object public char current(); // From CharacterIterator public boolean equals(Object obj); // Overrides Object public char first(); // From CharacterIterator public int getBeginIndex(); // From CharacterIterator public int getEndIndex(); // From CharacterIterator public int getIndex(); // From CharacterIterator public int hashCode(); // Overrides Object public char last(); // From CharacterIterator public char next(); // From CharacterIterator public char previous(); // From CharacterIterator public char setIndex(int p); // From CharacterIterator }
Hierarchy: Object->StringCharacterIterator(CharacterIterator(Cloneable))
java.text.SimpleDateFormat (JDK 1.1)
http://localhost/java/javaref/javanut/ch29_19.htm [20/12/2001 11:01:43]
The java.util Package
[Chapter 25] 25.59 java.lang.StringIndexOutOfBoundsException (JDK 1.0)
Chapter 25 The java.lang Package
25.59 java.lang.StringIndexOutOfBoundsException (JDK 1.0) Signals that the index used to access a character of a String or StringBuffer is less than zero or is too large. public class StringIndexOutOfBoundsException extends IndexOutOfBoundsException { // Public Constructors public StringIndexOutOfBoundsException(); public StringIndexOutOfBoundsException(String s); public StringIndexOutOfBoundsException(int index); }
Hierarchy: Object->Throwable(Serializable)->Exception->RuntimeException-> IndexOutOfBoundsException->StringIndexOutOfBoundsException
java.lang.StringBuffer (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_59.htm [20/12/2001 11:01:43]
java.lang.System (JDK 1.0)
[Chapter 24] 24.65 java.io.SyncFailedException (JDK 1.1)
Chapter 24 The java.io Package
24.65 java.io.SyncFailedException (JDK 1.1) Signals that a call to FileDescriptor.sync() did not complete successfully. public class SyncFailedException extends IOException { // Public Constructor public SyncFailedException(String desc); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->SyncFailedException
Thrown By: FileDescriptor.sync()
java.io.StringWriter (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_65.htm [20/12/2001 11:01:43]
java.io.UnsupportedEncodingException (JDK 1.1)
[Chapter 22] 22.23 java.awt.peer.TextAreaPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.23 java.awt.peer.TextAreaPeer (JDK 1.0) public abstract interface TextAreaPeer extends TextComponentPeer { // Public Instance Methods 1.1 public abstract Dimension getMinimumSize(int rows, int columns); 1.1 public abstract Dimension getPreferredSize(int rows, int columns); 1.1 public abstract void insert(String text, int pos); public abstract void insertText(String txt, int pos); public abstract Dimension minimumSize(int rows, int cols); public abstract Dimension preferredSize(int rows, int cols); 1.1 public abstract void replaceRange(String text, int start, int end); public abstract void replaceText(String txt, int start, int end); }
Hierarchy: (TextAreaPeer(TextComponentPeer(ComponentPeer)))
Returned By: Toolkit.createTextArea()
java.awt.peer.ScrollbarPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_23.htm [20/12/2001 11:01:43]
java.awt.peer.TextComponentPeer (JDK 1.0)
[Chapter 22] 22.24 java.awt.peer.TextComponentPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.24 java.awt.peer.TextComponentPeer (JDK 1.0) public abstract interface TextComponentPeer extends ComponentPeer { // Public Instance Methods 1.1 public abstract int getCaretPosition(); public abstract int getSelectionEnd(); public abstract int getSelectionStart(); public abstract String getText(); public abstract void select(int selStart, int selEnd); 1.1 public abstract void setCaretPosition(int pos); public abstract void setEditable(boolean editable); public abstract void setText(String l); }
Extended By: TextAreaPeer, TextFieldPeer
java.awt.peer.TextAreaPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_24.htm [20/12/2001 11:01:44]
java.awt.peer.TextFieldPeer (JDK 1.0)
[Chapter 22] 22.25 java.awt.peer.TextFieldPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.25 java.awt.peer.TextFieldPeer (JDK 1.0) public abstract interface TextFieldPeer extends TextComponentPeer { // Public Instance Methods 1.1 public abstract Dimension getMinimumSize(int columns); 1.1 public abstract Dimension getPreferredSize(int columns); public abstract Dimension minimumSize(int cols); public abstract Dimension preferredSize(int cols); 1.1 public abstract void setEchoChar(char echoChar); public abstract void setEchoCharacter(char c); }
Hierarchy: (TextFieldPeer(TextComponentPeer(ComponentPeer)))
Returned By: Toolkit.createTextField()
java.awt.peer.TextComponentPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_25.htm [20/12/2001 11:01:44]
java.awt.peer.WindowPeer (JDK 1.0)
[Chapter 25] 25.62 java.lang.ThreadDeath (JDK 1.0)
Chapter 25 The java.lang Package
25.62 java.lang.ThreadDeath (JDK 1.0) Signals that a thread should terminate. This error is thrown in a thread when the Thread.stop() method is called for that thread. This is an unusual Error type that simply causes a thread to be terminated, but does not print an error message or cause the interpreter to exit. You may catch ThreadDeath errors to do any necessary cleanup for a thread, but if you do, you must re-throw the error, so that the thread actually terminates. public class ThreadDeath extends Error { // Default Constructor: public ThreadDeath() }
Hierarchy: Object->Throwable(Serializable)->Error->ThreadDeath
java.lang.Thread (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_62.htm [20/12/2001 11:01:44]
java.lang.ThreadGroup (JDK 1.0)
[Chapter 25] 25.63 java.lang.ThreadGroup (JDK 1.0)
Chapter 25 The java.lang Package
25.63 java.lang.ThreadGroup (JDK 1.0) This class defines a group of threads and allows operations on the group as a whole. A ThreadGroup may contain Thread objects, as well as "child" ThreadGroup objects. All ThreadGroup objects are created as children of some other ThreadGroup, and thus there is a parent/child hierarchy of ThreadGroup objects. Some programs may find it convenient to define their own ThreadGroup, but generally thread groups are only used by system-level applications. public class ThreadGroup extends Object { // Public Constructors public ThreadGroup(String name); public ThreadGroup(ThreadGroup parent, String name); // Public Instance Methods public int activeCount(); public int activeGroupCount(); 1.1public boolean allowThreadSuspension(boolean b); public final void checkAccess(); public final void destroy(); public int enumerate(Thread[] list); public int enumerate(Thread[] list, boolean recurse); public int enumerate(ThreadGroup[] list); public int enumerate(ThreadGroup[] list, boolean recurse); public final int getMaxPriority(); public final String getName(); public final ThreadGroup getParent(); public final boolean isDaemon(); 1.1public synchronized boolean isDestroyed(); public void list(); public final boolean parentOf(ThreadGroup g); public final void resume(); public final void setDaemon(boolean daemon); public final void setMaxPriority(int pri); public final void stop(); http://localhost/java/javaref/javanut/ch25_63.htm (1 of 2) [20/12/2001 11:01:44]
[Chapter 25] 25.63 java.lang.ThreadGroup (JDK 1.0)
public final void suspend(); public String toString(); // Overrides Object public void uncaughtException(Thread t, Throwable e); }
Passed To: SecurityManager.checkAccess(), Thread(), ThreadGroup(), ThreadGroup.enumerate(), ThreadGroup.parentOf()
Returned By: SecurityManager.getThreadGroup(), Thread.getThreadGroup(), ThreadGroup.getParent()
java.lang.ThreadDeath (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_63.htm (2 of 2) [20/12/2001 11:01:44]
java.lang.Throwable (JDK 1.0)
[Chapter 24] 24.67 java.io.UTFDataFormatException (JDK 1.0)
Chapter 24 The java.io Package
24.67 java.io.UTFDataFormatException (JDK 1.0) An IOException that signals that a malformed UTF-8 string has been encountered by a class that implements the DataInput interface. UTF-8 is an ASCII-compatible "transformation format" for Unicode characters that is often used to store and transmit Unicode text. public class UTFDataFormatException extends IOException { // Public Constructors public UTFDataFormatException(); public UTFDataFormatException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->UTFDataFormatException
java.io.UnsupportedEncodingException (JDK 1.1)
http://localhost/java/javaref/javanut/ch24_67.htm [20/12/2001 11:01:45]
java.io.WriteAbortedException (JDK 1.1)
[Chapter 28] 28.20 java.net.UnknownHostException (JDK 1.0)
Chapter 28 The java.net Package
28.20 java.net.UnknownHostException (JDK 1.0) Signals that the name of a specified host could not be resolved. public class UnknownHostException extends IOException { // Public Constructors public UnknownHostException(String host); public UnknownHostException(); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->UnknownHostException
Thrown By: InetAddress.getAllByName(), InetAddress.getByName(), InetAddress.getLocalHost(), Socket()
java.net.SocketImplFactory (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_20.htm [20/12/2001 11:01:45]
java.net.UnknownServiceException (JDK 1.0)
[Chapter 28] 28.21 java.net.UnknownServiceException (JDK 1.0)
Chapter 28 The java.net Package
28.21 java.net.UnknownServiceException (JDK 1.0) Signals an attempt to use an unsupported service of a network connection. public class UnknownServiceException extends IOException { // Public Constructors public UnknownServiceException(); public UnknownServiceException(String msg); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->UnknownServiceException
java.net.UnknownHostException (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_21.htm [20/12/2001 11:01:45]
java.net.URL (JDK 1.0)
[Chapter 19] 19.6 java.awt.datatransfer.UnsupportedFlavorException (JDK 1.1)
Chapter 19 The java.awt.datatransfer Package
19.6 java.awt.datatransfer.UnsupportedFlavorException (JDK 1.1) An exception of this type signals that a Transferable object could not provide data in the requested format. public class UnsupportedFlavorException extends Exception { // Public Constructor public UnsupportedFlavorException(DataFlavor flavor); }
Hierarchy: Object->Throwable(Serializable)->Exception->UnsupportedFlavorException
Thrown By: StringSelection.getTransferData(), Transferable.getTransferData()
java.awt.datatransfer.Transferable (JDK 1.1)
http://localhost/java/javaref/javanut/ch19_06.htm [20/12/2001 11:01:46]
The java.awt.event Package
[Chapter 28] 28.26 java.net.URLStreamHandlerFactory (JDK 1.0)
Chapter 28 The java.net Package
28.26 java.net.URLStreamHandlerFactory (JDK 1.0) This interface defines a method that creates a URLStreamHandler object for a specified protocol. Normal applications never need to use or implement this interface. public abstract interface URLStreamHandlerFactory { // Public Instance Methods public abstract URLStreamHandler createURLStreamHandler(String protocol); }
Passed To: URL.setURLStreamHandlerFactory()
java.net.URLStreamHandler (JDK 1.0)
http://localhost/java/javaref/javanut/ch28_26.htm [20/12/2001 11:01:46]
The java.text Package
[Chapter 25] 25.69 java.lang.Void (JDK 1.1)
Chapter 25 The java.lang Package
25.69 java.lang.Void (JDK 1.1) The Void class may not be instantiated, and serves merely as a placeholder for its static TYPE field, which is a Class object constant that represents the void type. public final class Void extends Object { // No Constructor // Constants public static final Class TYPE; }
java.lang.VirtualMachineError (JDK 1.0)
http://localhost/java/javaref/javanut/ch25_69.htm [20/12/2001 11:01:46]
The java.lang.reflect Package
[Chapter 22] 22.26 java.awt.peer.WindowPeer (JDK 1.0)
Chapter 22 The java.awt.peer Package
22.26 java.awt.peer.WindowPeer (JDK 1.0) public abstract interface WindowPeer extends ContainerPeer { // Public Instance Methods public abstract void toBack(); public abstract void toFront(); }
Hierarchy: (WindowPeer(ContainerPeer(ComponentPeer)))
Extended By: DialogPeer, FramePeer
Returned By: Toolkit.createWindow()
java.awt.peer.TextFieldPeer (JDK 1.0)
http://localhost/java/javaref/javanut/ch22_26.htm [20/12/2001 11:01:47]
The java.beans Package
[Chapter 31] 31.13 java.util.zip.ZipEntry (JDK 1.1)
Chapter 31 The java.util.zip Package
31.13 java.util.zip.ZipEntry (JDK 1.1) This class describes a single entry (typically a compressed file) stored within a ZIP file. The various methods get and set various pieces of information about the entry. The ZipEntry class is used by the ZipFile and ZipInputStream, which read ZIP files, and by the ZipOutputStream, which writes ZIP files. When reading a ZIP file, the ZipEntry objects returned by the ZipFile or ZipInputStream contain the name, size, modification time, and other information about each entry in the file. When writing a ZIP file, on the other hand, you must create your own ZipEntry objects, and initialize them to contain the entry name and other appropriate information before writing the contents of the entry. public class ZipEntry extends Object { // Public Constructor public ZipEntry(String name); // Constants public static final int DEFLATED; public static final int STORED; // Public Instance Methods public String getComment(); public long getCompressedSize(); public long getCrc(); public byte[] getExtra(); public int getMethod(); public String getName(); public long getSize(); public long getTime(); public boolean isDirectory(); public void setComment(String comment); public void setCrc(long crc); public void setExtra(byte[] extra); public void setMethod(int method); public void setSize(long size); public void setTime(long time); public String toString(); // Overrides Object http://localhost/java/javaref/javanut/ch31_13.htm (1 of 2) [20/12/2001 11:01:47]
[Chapter 31] 31.13 java.util.zip.ZipEntry (JDK 1.1)
}
Passed To: ZipFile.getInputStream(), ZipOutputStream.putNextEntry()
Returned By: ZipFile.getEntry(), ZipInputStream.getNextEntry()
java.util.zip.InflaterInputStream (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_13.htm (2 of 2) [20/12/2001 11:01:47]
java.util.zip.ZipException (JDK 1.1)
[Chapter 31] 31.14 java.util.zip.ZipException (JDK 1.1)
Chapter 31 The java.util.zip Package
31.14 java.util.zip.ZipException (JDK 1.1) Signals that an error has occurred in reading or writing a ZIP file. public class ZipException extends IOException { // Public Constructors public ZipException(); public ZipException(String s); }
Hierarchy: Object->Throwable(Serializable)->Exception->IOException->ZipException
Thrown By: ZipFile()
java.util.zip.ZipEntry (JDK 1.1)
http://localhost/java/javaref/javanut/ch31_14.htm [20/12/2001 11:01:48]
java.util.zip.ZipFile (JDK 1.1)
[Preface] Audience
Preface
Audience This book is for computer professionals, students, technical people, and Finnish hackers. It's for everyone who has a need for hands-on experience with the Java language with an eye towards building real applications. This book could also be considered a crash course in object-oriented programming; as you learn about Java, you'll also learn a powerful and practical approach to object-oriented software development. Superficially, Java looks like C or C++, so you'll be in the best position to use this book if you've some experience with one of these languages. If you do not, you might want to reference books like O'Reilly's Practical C Programming for a more thorough treatment of basic C syntax. However, don't make too much of the syntactic similarities between Java and C or C++. In many respects, Java acts like more dynamic languages such as Smalltalk and Lisp. Knowledge of another object-oriented programming language should certainly help, although you may have to change some ideas and unlearn a few habits. Java is considerably simpler than languages like C++ and Smalltalk. Much of the interest in Java has centered around World Wide Web applets. Although we encourage you to take a broader view, you would have every right to be disappointed if we ignored the Web. Much of the book does discuss Java as a language for World Wide Web applications, so you should be familiar with the basic ideas behind Web browsers, servers, and Web documents.
The Past Year
http://localhost/java/javaref/exp/ch00_02.htm [20/12/2001 11:01:48]
Using This Book
[Preface] Using This Book
Preface
Using This Book This book divides roughly into three sections: ● Chapters 1 and 2 provide a basic introduction to Java concepts and a tutorial to give you a jump start on Java programming. ● Chapters 3 through 6 discuss tools for working with Java (the compiler, the interpreter, HTML support, etc.) and the language itself. Chapter 6, Threads covers the language's thread facilities, which should be of particular interest to advanced programmers. ● Chapters 7 through 14 discuss the class libraries. Chapter 7, Basic Utility Classes covers basic utilities; Chapter 8, Input/Output Facilities covers I/O facilities; Chapter 9, Network Programming covers networking; and Chapters 10 through 14 cover the Abstract Windowing Toolkit (AWT), which provides graphics and graphic user interface (GUI) support. If you're like us, you don't read books from front to back. If you are really like us, you usually don't read the preface at all. However, on the off chance that you will see this in time, here are a few suggestions. If you are an experienced programmer who has to learn Java in the next five minutes, you are probably looking for the examples. You might want to start by glancing at the tutorial in Chapter 2, A First Applet. If that doesn't float your boat, you should at least look at the information in Chapter 3, Tools of the Trade, which tells you how to use the compiler and interpreter, and gives you the basics of a standalone Java application. This should get you started. Chapter 9, Network Programming is essential if you are interested in writing advanced networked applications. This is probably the most interesting and important part of Java. Unfortunately, we are still waiting for Sun to release a production version of HotJava, or for someone else to release a browser that implements all of Java's networking features.[1] Until then, you can still write interesting standalone applications that use the Net. Maybe you'll even write the browser we're waiting for. [1] Just before this book went to press, Sun released a "pre-beta 1" version of HotJava. That's definitely good news, though the pre-beta version doesn't support downloadable content and protocol handlers. These are promised for the "real" beta release. Chapters 13 and 14 discusses Java's graphics features. You will need to read this if you are interested in animation and other live displays.
http://localhost/java/javaref/exp/ch00_03.htm (1 of 2) [20/12/2001 11:01:49]
[Preface] Using This Book
Audience
http://localhost/java/javaref/exp/ch00_03.htm (2 of 2) [20/12/2001 11:01:49]
Getting Wired
[Preface] Getting Wired
Preface
Getting Wired There are many online sources for information about Java. Sun Microsystem's official Web site for Java topics is http://www.javasoft.com/; look here for the latest news, updates, and Java releases. www.javasoft.com is where you'll find the Java Developers Kit (JDK), which includes the compiler, the interpreter, and other tools. Another good source of Java information, including free applets, utility classes, and applications, is the Gamelan site, run by EarthWeb; its URL is http://www.gamelan.com. You should also visit O'Reilly & Associates' Java site at http://www.ora.com/info/java. There you'll find information about other books in O'Reilly's Java series, and a pointer to the home page for Exploring Java, http://www.ora.com/catalog/expjava/, where you'll find the source code and examples for this book. The comp.lang.java newsgroup can be a good source of information, announcements, and a place to ask intelligent questions.
Using This Book
http://localhost/java/javaref/exp/ch00_04.htm [20/12/2001 11:01:49]
Conventions Used in This Book
[Preface] Conventions Used in This Book
Preface
Conventions Used in This Book The font conventions used in this book are quite simple. Italic is used for: ● UNIX pathnames, filenames, and program names ● Internet addresses, such as domain names and URLs ● New terms where they are defined Boldface is used for: ● Names of GUI buttons and menus Typewriter Font is used for: ● Anything that might appear in a Java program, including method names, variable names, and class names ● Command lines and options that should be typed verbatim on the screen ● Tags that might appear in an HTML document In the main body of text, we always use a pair of empty parentheses after a method name to distinguish methods from variables and other creatures. In the Java source listings, we follow the coding conventions most frequently used in the Java community. Class names begin with capital letters; variable and method names begin with lowercase. All the letters in the names of constants are capitalized. We don't use underscores to separate words in a long name; following common practice, we capitalize individual words (after the first) and run the words together. For example: thisIsAVariable, thisIsAMethod(), ThisIsAClass, and THISISACONSTANT.
Getting Wired
http://localhost/java/javaref/exp/ch00_05.htm [20/12/2001 11:01:49]
Acknowledgments
[Preface] Acknowledgments
Preface
Acknowledgments Many people contributed to putting this book together under a schedule that became increasingly rushed as time passed. Thanks to their efforts, we gave birth to something we can all be proud of. Foremost we would like to thank Tim O'Reilly for giving us the opportunity to write this book. Special thanks to Mike Loukides, the series editor, whose endless patience and experience got us through the difficult parts and to Paula Ferguson, whose organizational and editing abilities got the material into its final form. It's due largely to Mike and Paula's tireless efforts that this book has gotten to you as quickly as it has. We could not have asked for a more skillful or responsive team of people with whom to work. Particular thanks are due to our technical reviewers: Andrew Cohen, Eric Raymond, and Lisa Farley. All of them gave thorough reviews that were invaluable in assembling the final draft. Eric contributed many bits of text that eventually found their way into the book. Speaking of borrowings, the original version of the glossary came from David Flanagan's book, Java in a Nutshell. We also borrowed the class hierarchy diagrams from David's book. These diagrams were based on similar diagrams by Charles L. Perkins. His original diagrams are available at http://rendezvous.com/java/. Thanks also to Marc Wallace and Steven Burkett for reading the book in progress. As for the crowd in St. Louis: a special thanks to LeeAnn Langdon of the Library Ltd. and Kerri Bonasch. Deepest thanks to Victoria Doerr for her patience and love. Finally, thanks for the support of the "lunch" crowd: Karl "Gooch" Stefvater, Bryan "Butter" O'Connor, Brian "Brian" Gottlieb, and the rest of the clan at Washington University. Many people in O'Reilly's production and design groups contributed their blood, sweat, and tears to the project. Mary Anne Weeks Mayo was production editor and copy editor, and had the stress-filled job of working under a very tight deadline with chapters arriving asynchronously (which means at random and later than expected). Seth Maislin wrote the index, and Stephen Spainhour adapted David Flanagan's glossary for this book. Chris Reilley converted rough diagrams into professional technical illustrations. Erik Ray, Ellen Siever, and Lenny Muellner converted HTML files into SGML and made sure we could convert electrons into paper without mishap. Lenny also implemented a new design for this book, which was created by Nancy Priest. Hanna Dyer created the back cover; Edie Freedman designed the front cover.
http://localhost/java/javaref/exp/ch00_06.htm (1 of 2) [20/12/2001 11:01:49]
[Preface] Acknowledgments
Conventions Used in This Book
http://localhost/java/javaref/exp/ch00_06.htm (2 of 2) [20/12/2001 11:01:49]
Yet Another Language?
[Chapter 1] 1.2 A Virtual Machine
Chapter 1 Yet Another Language?
1.2 A Virtual Machine Java is both a compiled and an interpreted language. Java source code is turned into simple binary instructions, much like ordinary microprocessor machine code. However, whereas C or C++ source is refined to native instructions for a particular model of processor, Java source is compiled into a universal format--instructions for a virtual machine. Compiled Java byte-code, also called J-code, is executed by a Java run-time interpreter. The run-time system performs all the normal activities of a real processor, but it does so in a safe, virtual environment. It executes the stack-based instruction set and manages a storage heap. It creates and manipulates primitive data types, and loads and invokes newly referenced blocks of code. Most importantly, it does all this in accordance with a strictly defined open specification that can be implemented by anyone who wants to produce a Java-compliant virtual machine. Together, the virtual machine and language definition provide a complete specification. There are no features of Java left undefined or implementation dependent. For example, Java specifies the sizes of all its primitive data types, rather than leave it up to each implementation. The Java interpreter is relatively lightweight and small; it can be implemented in whatever form is desirable for a particular platform. On most systems, the interpreter is written in a fast, natively compiled language like C or C++. The interpreter can be run as a separate application, or it can be embedded in another piece of software, such as a Web browser. All of this means that Java code is implicitly portable. The same Java application can run on any platform that provides a Java run-time environment, as shown in Figure 1.1. You don't have to produce alternate versions of your application for different platforms, and you never have to distribute source code to end users. Figure 1.1: Java virtual machine environment
http://localhost/java/javaref/exp/ch01_02.htm (1 of 3) [20/12/2001 11:01:50]
[Chapter 1] 1.2 A Virtual Machine
The fundamental unit of Java code is the class. As in other object-oriented languages, classes are application components that hold executable code and data. Compiled Java classes are distributed in a universal binary format that contains Java byte-code and other class information. Classes can be maintained discretely and stored in files or archives on a local system or on a network server. Classes are located and loaded dynamically at run-time, as they are needed by an application. In addition to the platform-specific run-time system, Java has a number of fundamental classes that contain architecture-dependent methods. These native methods serve as Java's gateway to the real world. These methods are implemented in a native language on the host platform. They provide access to resources such as the network, the windowing system, and the host filesystem. The rest of Java is written entirely in Java, and is therefore portable. This includes fundamental Java utilities like the Java compiler, which is also a Java application and is therefore immediately available on all Java platforms. In general, interpreters are slow, but because the Java interpreter runs compiled byte-code, Java is a fast interpreted language. Java has also been designed so that software implementations of the run-time system can optimize their performance by compiling byte-code to native machine code on the fly. This is called "just in time" compilation. Sun claims that with just in time compilation, Java code can execute nearly as fast as native compiled code and maintain its transportability and security. The one performance hit that natively compiled Java code will always suffer is array bounds checking. But on the other hand, some of the basic design features of Java place more information in the hands of the compiler, which allows for certain kinds of optimizations not possible in C or C++.
http://localhost/java/javaref/exp/ch01_02.htm (2 of 3) [20/12/2001 11:01:50]
[Chapter 1] 1.2 A Virtual Machine
Enter Java
http://localhost/java/javaref/exp/ch01_02.htm (3 of 3) [20/12/2001 11:01:50]
Java Compared
[Chapter 1] 1.3 Java Compared
Chapter 1 Yet Another Language?
1.3 Java Compared Java is a new language, but it draws on many years of programming experience with other languages in its choice of features. So a lot can be said in comparing and contrasting Java with other languages. There are at least three pillars necessary to support a universal language for network programming today: portability, speed, and security. Figure 1.2 shows how Java compares to other languages. Figure 1.2: Programming languages compared
You may have heard that Java is a lot like C or C++, but that's really not true, except at a superficial level. When you first look at Java code, you'll see that the basic syntax looks a lot like C or C++. But that's where the similarities end. Java is by no means a direct descendant of C or a next generation C++. If you compare language features, you'll see that Java actually has more in common with languages like Smalltalk and Lisp. In fact, Java's implementation is about as far from native C as you can imagine. The surface-level similarities to C and C++ are worth noting, however. Java borrows heavily from C and C++ syntax, so you'll see lots of familiar language constructs, including an abundance of curly braces and semicolons. Java also subscribes to the C philosophy that a good language should be compact; in other words, it should be sufficiently small and regular so that a programmer can hold all the language's capabilities in his or her head at once. As C is extensible with libraries, packages of Java classes can be added to the core language components.
http://localhost/java/javaref/exp/ch01_03.htm (1 of 3) [20/12/2001 11:01:50]
[Chapter 1] 1.3 Java Compared
C has been successful because it provides a reasonably featureful programming environment, with high performance and an acceptable degree of portability. Java also tries to balance functionality, speed, and portability, but it does so in a very different way. While C trades functionality to get portability, Java trades speed for portability. Java also addresses security issues, while C doesn't. Java is an interpreted language, so it won't be as fast as a compiled language like C. But Java is fast enough, especially for interactive, network-based applications, where the application is often idle, waiting for the user to do something or waiting for data from the network. For situations where speed is critical, a Java implementation can optimize performance by compiling byte-code to native machine code on the fly. Scripting languages, like Tcl, Perl, and Wksh, are becoming quite popular, and for good reason. There's no reason a scripting language could not be suitable for safe, networked applications (e.g., Safe Tcl), but most scripting languages are not designed for serious, large-scale programming. The attraction to scripting languages is that they are dynamic; they are powerful tools for rapid prototyping. Some scripting languages, like awk and Perl, also provide powerful tools for text-processing tasks more general-purpose languages find unwieldy. Scripting languages are also highly portable. One problem with scripting languages, however, is that they are rather casual about program structure and data typing. Most scripting languages (with a hesitant exception for Perl 5.0) are not object oriented. They also have vastly simplified type systems and generally don't provide for sophisticated scoping of variables and functions. These characteristics make them unsuitable for building large, modular applications. Speed is another problem with scripting languages; the high-level, fully interpreted nature of these languages often makes them quite slow. Java offers some of the essential advantages of a scripting language, along with the added benefits of a lower-level language.[1] Incremental development with object-oriented components, combined with Java's simplicity, make it possible to develop applications rapidly and change them easily, with a short concept to implementation time. Java also comes with a large base of core classes for common tasks such as building GUIs and doing network communications. But along with these features, Java has the scalability and software-engineering advantages of more static languages. It provides a safe structure on which to build higher-level networked tools and languages. [1] Don't confuse Java with JavaScript. JavaScript is an object-based scripting language being developed by Netscape and is designed to create dynamic, interactive Web applications. JavaScript is a very different language from Java in most respects. For more information on JavaScript, check out Netscape's Web site (http://home.netscape.com). As I've already said, Java is similar in design to languages like Smalltalk and Lisp. However, these languages are used mostly as research vehicles, rather than for developing large-scale systems. One reason is that they never developed a standard portable binding to operating-system services analogous to the C standard library or the Java core classes. Smalltalk is compiled to an interpreted byte-code format, and it can be dynamically compiled to native code on the fly, just like Java. But Java improves on the design by using a byte-code verifier to ensure the correctness of Java code. This verifier gives Java a performance advantage over Smalltalk because Java code requires fewer run-time checks. Java's byte-code verifier also helps with security issues, something that Smalltalk doesn't address. Smalltalk is a mature language though, and Java's designers took lessons from many of its features.
http://localhost/java/javaref/exp/ch01_03.htm (2 of 3) [20/12/2001 11:01:50]
[Chapter 1] 1.3 Java Compared
Throughout the rest of this chapter, we'll take a bird's eye view of the Java language. I'll explain what's new and what's not so new about Java; how it differs from other languages, and why.
A Virtual Machine
http://localhost/java/javaref/exp/ch01_03.htm (3 of 3) [20/12/2001 11:01:50]
Safety of Design
[Chapter 1] 1.4 Safety of Design
Chapter 1 Yet Another Language?
1.4 Safety of Design You have no doubt heard a lot about the fact that Java is designed to be a safe language. But what do we mean by safe? Safe from what or whom? The security features that attract the most attention for Java are those features that make possible new types of dynamically portable software. Java provides several layers of protection from dangerously flawed code, as well as more mischievous things like viruses and trojan horses. In the next section, we'll take a look at how the Java virtual machine architecture assesses the safety of code before it's run, and how the Java class loader builds a wall around untrusted classes. These features provide the foundation for high-level security policies that allow or disallow various kinds of activities on an application-by-application basis. In this section though, we'll look at some general features of the Java programming language. What is perhaps more important, although often overlooked in the security din, is the safety that Java provides by addressing common design and programming problems. Java is intended to be as safe as possible from the simple mistakes we make ourselves, as well as those we inherit from contractors and third-party software vendors. The goal with Java has been to keep the language simple, provide tools that have demonstrated their usefulness, and let users build more complicated facilities on top of the language when needed.
Syntactic Sweet 'n Low Java is parsimonious in its features; simplicity rules. Compared to C, Java uses few automatic type coercions, and the ones that remain are simple and well-defined. Unlike C++, Java doesn't allow programmer-defined operator overloading. The string concatenation operator + is the only system-defined, overloaded operator in Java. All methods in Java are like C++ virtual methods, so overridden methods are dynamically selected at run-time. Java doesn't have a preprocessor, so it doesn't have macros, #define statements, or conditional source compilation. These constructs exist in other languages primarily to support platform dependencies, so in that sense they should not be needed in Java. Another common use for conditional compilation is for debugging purposes. Debugging code can be included directly in your Java source code by making it conditional on a constant (i.e., static and final) variable. The Java compiler is smart enough to remove this code when it determines that it won't be called. Java provides a well-defined package structure for organizing class files. The package system allows the compiler to handle most of the functionality of make. The compiler also works with compiled Java http://localhost/java/javaref/exp/ch01_04.htm (1 of 5) [20/12/2001 11:01:51]
[Chapter 1] 1.4 Safety of Design
classes because all type information is preserved; there is no need for header files. All of this means that Java code requires little context to read. Indeed, you may sometimes find it faster to look at the Java source code than to refer to class documentation. Java replaces some features that have been troublesome in other languages. For example, Java supports only a single inheritance class hierarchy, but allows multiple inheritance of interfaces. An interface, like an abstract class in C++, specifies the behavior of an object without defining its implementation, a powerful mechanism borrowed from Objective C. It allows a class to implement the behavior of the interface, without needing to be a subclass of the interface. Interfaces in Java eliminate the need for multiple inheritance of classes, without causing the problems associated with multiple inheritance. As you'll see in Chapter 4, The Java Language, Java is a simple, yet elegant, programming language.
Type Safety and Method Binding One attribute of a language is the kind of type checking it uses. When we categorize a language as static or dynamic we are referring to the amount of information about variable types that is known at compile time versus what is determined while the application is running. In a strictly statically typed language like C or C++, data types are etched in stone when the source code is compiled. The compiler benefits from having enough information to enforce usage rules, so that it can catch many kinds of errors before the code is executed. The code doesn't require run-time type checking, which is advantageous because it can be compiled to be small and fast. But statically typed languages are inflexible. They don't support high-level constructs like lists and collections as naturally as languages with dynamic type checking, and they make it impossible for an application to safely import new data types while it's running. In contrast, a dynamic language like Smalltalk or Lisp has a run-time system that manages the types of objects and performs necessary type checking while an application is executing. These kinds of languages allow for more complex behavior, and are in many respects more powerful. However, they are also generally slower, less safe, and harder to debug. The differences in languages have been likened to the differences between kinds of automobiles.[2] Statically typed languages like C++ are analogous to a sports car--reasonably safe and fast--but useful only if you're driving on a nicely paved road. Highly dynamic languages like Smalltalk are more like an offroad vehicle: they afford you more freedom, but can be somewhat unwieldy. It can be fun (and sometimes faster) to go roaring through the back woods, but you might also get stuck in a ditch or mauled by bears. [2] The credit for the car analogy goes to Marshall P. Cline, author of the C++ FAQ. Another attribute of a language deals with when it binds method calls to their definitions. In an early-binding language like C or C++, the definitions of methods are normally bound at compile-time, unless the programmer specifies otherwise. Smalltalk, on the other hand, is a late-binding language because it locates the definitions of methods dynamically at run-time. Early-binding is important for performance reasons; an application can run without the overhead incurred by searching method tables at run-time. But late-binding is more flexible. It's also necessary in an object-oriented language, where a subclass can override methods in its superclass, and only the run-time system can determine which http://localhost/java/javaref/exp/ch01_04.htm (2 of 5) [20/12/2001 11:01:51]
[Chapter 1] 1.4 Safety of Design
method to run. Java provides some of the benefits of both C++ and Smalltalk; it's a statically typed, late-binding language. Every object in Java has a well-defined type that is known at compile time. This means the Java compiler can do the same kind of static type checking and usage analysis as C++. As a result, you can't assign an object to the wrong type of reference or call nonexistent methods within it. The Java compiler goes even further and prevents you from messing up and trying to use uninitialized variables. However, Java is fully run-time typed as well. The Java run-time system keeps track of all objects and makes it possible to determine their types and relationships during execution. This means you can inspect an object at run-time to determine what it is. Unlike C or C++, casts from one type of object to another are checked by the run-time system, and it's even possible to use completely new kinds of dynamically loaded objects with a level of type safety. Since Java is a late-binding language, all methods are like virtual methods in C++. This makes it possible for a subclass to override methods in its superclass. But Java also allows you to gain the performance benefits of early-binding by declaring (with the final modifier) that certain methods can't be overridden by subclassing, removing the need for run-time lookup.
Incremental Development Java carries all data-type and method-signature information with it from its source code to its compiled byte-code form. This means that Java classes can be developed incrementally. Your own Java classes can also be used safely with classes from other sources your compiler has never seen. In other words, you can write new code that references binary class files, without losing the type safety you gain from having the source code. The Java run-time system can load new classes while an application is running, thus providing the capabilities of a dynamic linker. A common irritation with C++ is the "fragile base class" problem. In C++, the implementation of a base class can be effectively frozen by the fact that it has many derived classes; changing the base class may require recompilation of the derived classes. This is an especially difficult problem for developers of class libraries. Java avoids this problem by dynamically locating fields within classes. As long as a class maintains a valid form of its original structure, it can evolve without breaking other classes that are derived from it or that make use of it.
Dynamic Memory Management Some of the most important differences between Java and C or C++ involve how Java manages memory. Java eliminates ad hoc pointers and adds garbage collection and true arrays to the language. These features eliminate many otherwise insurmountable problems with safety, portability, and optimization. Garbage collection alone should save countless programmers from the single largest source of programming errors in C or C++: explicit memory allocation and deallocation. In addition to maintaining objects in memory, the Java run-time system keeps track of all references to those objects. When an object is no longer in use, Java automatically removes it from memory. You can simply throw away references to objects you no longer use and have confidence that the system will clean them up at an appropriate time. Sun's current implementation of Java uses a conservative, mark and sweep garbage
http://localhost/java/javaref/exp/ch01_04.htm (3 of 5) [20/12/2001 11:01:51]
[Chapter 1] 1.4 Safety of Design
collector that runs intermittently in the background, which means that most garbage collecting takes place between mouse clicks and keyboard hits. Once you get used to garbage collection, you won't go back. Being able to write air-tight C code that juggles memory without dropping any on the floor is an important skill, but once you become addicted to Java you can "realloc" some of those brain cells to new tasks. You may hear people say that Java doesn't have pointers. Strictly speaking, this statement is true, but it's also misleading. What Java provides are references--a safe kind of pointer--and Java is rife with them. A reference is a strongly typed handle for an object. All objects in Java, with the exception of primitive numeric types, are accessed through references. If necessary, you can use references to build all the normal kinds of data structures you're accustomed to building with pointers, like linked lists, trees, and so forth. The only difference is that with references you have to do so in a type-safe way. Another important difference between a reference and a pointer is that you can't do pointer arithmetic with references. A reference is an atomic thing; you can't manipulate the value of a reference except by assigning it to an object. References are passed by value, and you can't reference an object through more than a single level of indirection. The protection of references is one of the most fundamental aspects of Java security. It means that Java code has to play by the rules; it can't peek into places it shouldn't. Unlike C or C++ pointers, Java references can point only to class types. There are no pointers to methods. People often complain about this missing feature, but you will find that most tasks that call for pointers to methods, such as callbacks, can be accomplished using interfaces and anonymous adapter classes instead. [3] [3] Java 1.1 does have a Method class, which lets you have a reference to a method. You can use a Method object to construct a callback, but it's tricky. Finally, arrays in Java are true, first-class objects. They can be dynamically allocated and assigned like other objects. Arrays know their own size and type, and although you can't directly define array classes or subclass them, they do have a well-defined inheritance relationship based on the relationship of their base types. Having true arrays in the language alleviates much of the need for pointer arithmetic like that in C or C++.
Error Handling Java's roots are in networked devices and embedded systems. For these applications, it's important to have robust and intelligent error management. Java has a powerful exception-handling mechanism, somewhat like that in newer implementations of C++. Exceptions provide a more natural and elegant way to handle errors. Exceptions allow you to separate error-handling code from normal code, which makes for cleaner, more readable applications. When an exception occurs, it causes the flow of program execution to be transferred to a predesignated catcher block of code. The exception carries with it an object that contains information about the situation that caused the exception. The Java compiler requires that a method either declare the exceptions it can generate or catch and deal with them itself. This promotes error information to the same level of importance as argument and return typing. As a Java programmer, you know precisely what exceptional conditions you must deal with, and you have help from the compiler in writing correct software that doesn't leave them unhandled. http://localhost/java/javaref/exp/ch01_04.htm (4 of 5) [20/12/2001 11:01:51]
[Chapter 1] 1.4 Safety of Design
Multithreading Applications today require a high degree of parallelism. Even a very single-minded application can have a complex user interface. As machines get faster, users become more sensitive to waiting for unrelated tasks that seize control of their time. Threads provide efficient multiprocessing and distribution of tasks. Java makes threads easy to use because support for them is built into the language. Concurrency is nice, but there's more to programming with threads than just performing multiple tasks simultaneously. In many cases, threads need to be synchronized, which can be tricky without explicit language support. Java supports synchronization based on the monitor and condition model developed by C.A.R. Hoare--a sort of lock and key system for accessing resources. A keyword, synchronized, designates methods for safe, serialized access within an object. Only one synchronized method within the object may run at a given time. There are also simple, primitive methods for explicit waiting and signaling between threads interested in the same object. Learning to program with threads is an important part of learning to program in Java. See Chapter 6, Threads for a discussion of this topic. For complete coverage of threads, see Java Threads, by Scott Oaks and Henry Wong (O'Reilly & Associates).
Scalability At the lowest level, Java programs consist of classes. Classes are intended to be small, modular components. They can be separated physically on different systems, retrieved dynamically, and even cached in various distribution schemes. Over classes, Java provides packages, a layer of structure that groups classes into functional units. Packages provide a naming convention for organizing classes and a second level of organizational control over the visibility of variables and methods in Java applications. Within a package, a class is either publicly visible or protected from outside access. Packages form another type of scope that is closer to the application level. This lends itself to building reusable components that work together in a system. Packages also help in designing a scalable application that can grow without becoming a bird's nest of tightly coupled code dependency.
Java Compared
http://localhost/java/javaref/exp/ch01_04.htm (5 of 5) [20/12/2001 11:01:51]
Safety of Implementation
[Chapter 1] 1.5 Safety of Implementation
Chapter 1 Yet Another Language?
1.5 Safety of Implementation It's one thing to create a language that prevents you from shooting yourself in the foot; it's quite another to create one that prevents others from shooting you in the foot. Encapsulation is a technique for hiding data and behavior within a class; it's an important part of object-oriented design. It helps you write clean, modular software. In most languages however, the visibility of data items is simply part of the relationship between the programmer and the compiler. It's a matter of semantics, not an assertion about the actual security of the data in the context of the running program's environment. When Bjarne Stroustrup chose the keyword private to designate hidden members of classes in C++, he was probably thinking about shielding you from the messy details of a class developer's code, not the issues of shielding that developer's classes and objects from the onslaught of someone else's viruses and trojan horses. Arbitrary casting and pointer arithmetic in C or C++ make it trivial to violate access permissions on classes without breaking the rules of the language. Consider the following code: // C++ class Finances { private: char creditCardNumber[16]; ... }; main() { Finances finances; // Forge a pointer to peek inside the class char *cardno = (char *)finances; printf("Card Number = %s\n", cardno); } In this little C++ drama, we have written some code that violates the encapsulation of the Finances class and pulls out some secret information. If this example seems unrealistic, consider how important it
http://localhost/java/javaref/exp/ch01_05.htm (1 of 5) [20/12/2001 11:01:52]
[Chapter 1] 1.5 Safety of Implementation
is to protect the foundation (system) classes of the run-time environment from similar kinds of attacks. If untrusted code can corrupt the components that provide access to real resources, such as the filesystem, the network, or the windowing system, it certainly has a chance at stealing your credit card numbers. In Visual BASIC, it's also possible to compromise the system by peeking, poking, and, under DOS, installing interrupt handlers. Even some recent languages that have some commonalities with Java lack important security features. For example, the Apple Newton uses an object-oriented language called NewtonScript that is compiled into an interpreted byte-code format. However, NewtonScript has no concept of public and private members, so a Newton application has free reign to access any information it finds. General Magic's Telescript language is another example of a device-independent language that does not fully address security concerns. If a Java application is to dynamically download code from an untrusted source on the Internet and run it alongside applications that might contain confidential information, protection has to extend very deep. The Java security model wraps three layers of protection around imported classes, as shown in Figure 1.3. Figure 1.3: The Java security model
At the outside, application-level security decisions are made by a security manager. A security manager controls access to system resources like the filesystem, network ports, and the windowing environment. A security manager relies on the ability of a class loader to protect basic system classes. A class loader handles loading classes from the network. At the inner level, all system security ultimately rests on the Java verifier, which guarantees the integrity of incoming classes. The Java byte-code verifier is an integral part of the Java run-time system. Class loaders and security managers, however, are implemented by applications that load applets, such as applet viewers and Web browsers. All these pieces need to be functioning properly to ensure security in the Java environment.[4] [4] You may have seen reports about various security flaws in Java. While these weaknesses are real, it's important to realize that they have been found in the implementations of various components, namely Sun's byte-code verifier and Netscape's class loader and security manager, not in the basic security model itself. One of the reasons Sun has released the source code for Java is to encourage people to search for weaknesses, so they can be removed. http://localhost/java/javaref/exp/ch01_05.htm (2 of 5) [20/12/2001 11:01:52]
[Chapter 1] 1.5 Safety of Implementation
The Verifier Java's first line of defense is the byte-code verifier. The verifier reads byte-code before they are run and makes sure they are well-behaved and obey the basic rules of the Java language. A trusted Java compiler won't produce code that does otherwise. However, it's possible for a mischievous person to deliberately assemble bad code. It's the verifier's job to detect this. Once code has been verified, it's considered safe from certain inadvertent or malicious errors. For example, verified code can't forge pointers or violate access permissions on objects. It can't perform illegal casts or use objects in ways other than they are intended. It can't even cause certain types of internal errors, such as overflowing or underflowing the operand stack. These fundamental guarantees underlie all of Java's security. You might be wondering, isn't this kind of safety implicit in lots of interpreted languages? Well, while it's true that you shouldn't be able to corrupt the interpreter with bogus BASIC code, remember that the protection in most interpreted languages happens at a higher level. Those languages are likely to have heavyweight interpreters that do a great deal of run-time work, so they are necessarily slower and more cumbersome. By comparison, Java byte-code is a relatively light, low-level instruction set. The ability to statically verify the Java byte-code before execution lets the Java interpreter run at full speed with full safety, without expensive run-time checks. Of course, you are always going to pay the price of running an interpreter, but that's not a serious problem with the speed of modern CPUs. Java byte-code can also be compiled on the fly to native machine code, which has even less run-time overhead. The verifier is a type of theorem prover. It steps through the Java byte-code and applies simple, inductive rules to determine certain aspects of how the byte-code will behave. This kind of analysis is possible because compiled Java byte-code has a lot more type information stored within it than other languages of this kind. The byte-code also has to obey a few extra rules that simplify its behavior. First, most byte-code instructions operate only on individual data types. For example, with stack operations, there are separate instructions for object references and for each of the numeric types in Java. Similarly, there is a different instruction for moving each type of value into and out of a local variable. Second, the type of object resulting from any operation is always known in advance. There are no byte-code operations that consume values and produce more than one possible type of value as output. As a result, it's always possible to look at the next instruction and its operands, and know the type of value that will result. Because an operation always produces a known type, by looking at the starting state, it's possible to determine the types of all items on the stack and in local variables at any point in the future. The collection of all this type information at any given time is called the type state of the stack; this is what Java tries to analyze before it runs an application. Java doesn't know anything about the actual values of stack and variable items at this time, just what kind of items they are. However, this is enough information to enforce the security rules and to insure that objects are not manipulated illegally. To make it feasible to analyze the type state of the stack, Java places an additional restriction on how Java byte-code instructions are executed: all paths to the same point in the code have to arrive with
http://localhost/java/javaref/exp/ch01_05.htm (3 of 5) [20/12/2001 11:01:52]
[Chapter 1] 1.5 Safety of Implementation
exactly the same type state.[5] This restriction makes it possible for the verifier to trace each branch of the code just once and still know the type state at all points. Thus, the verifier can insure that instruction types and stack value types always correspond, without actually following the execution of the code. [5] The implications of this rule are mainly of interest to compiler writers. The rule means that Java byte-code can't perform certain types of iterative actions within a single frame of execution. A common example would be looping and pushing values onto the stack. This is not allowed because the path of execution would return to the top of the loop with a potentially different type state on each pass, and there is no way that a static analysis of the code can determine whether it obeys the security rules.
Class Loader Java adds a second layer of security with a class loader. A class loader is responsible for bringing Java binary classes that contain byte-code into the interpreter. Every application that loads classes from the network must use a class loader to handle this task. After a class has been loaded and passed through the verifier, it remains associated with its class loader. As a result, classes are effectively partitioned into separate namespaces based on their origin. When a class references another class, the request is served by its original class loader. This means that classes retrieved from a specific source can be restricted to interact only with other classes retrieved from that same location. For example, a Java-enabled Web browser can use a class loader to build a separate space for all the classes loaded from a given uniform resource locator (URL). The search for classes always begins with the built-in Java system classes. These classes are loaded from the locations specified by the Java interpreter's class path (see Chapter 3, Tools of the Trade). Classes in the class path are loaded by the system only once and can't be replaced. This means that it's impossible for an applet to replace fundamental system classes with its own versions that change their functionality.
Security Manager Finally, a security manager is responsible for making application-level security decisions. A security manager is an object that can be installed by an application to restrict access to system resources. The security manager is consulted every time the application tries to access items like the filesystem, network ports, external processes, and the windowing environment, so the security manager can allow or deny the request. A security manager is most useful for applications that run untrusted code as part of their normal operation. Since a Java-enabled Web browser can run applets that may be retrieved from untrusted sources on the Net, such a browser needs to install a security manager as one of its first actions. This security manager then restricts the kinds of access allowed after that point. This lets the application impose an effective level of trust before running an arbitrary piece of code. And once a security manager is installed, it can't be replaced. A security manager can be as simple or complex as a particular application warrants. Sometimes it's sufficient simply to deny access to all resources or to general categories of services such as the filesystem or network. But it's also possible to make sophisticated decisions based on high-level information. For
http://localhost/java/javaref/exp/ch01_05.htm (4 of 5) [20/12/2001 11:01:52]
[Chapter 1] 1.5 Safety of Implementation
example, a Java-enabled Web browser could implement a security manager that lets users specify how much an applet is to be trusted or that allows or denies access to specific resources on a case-by-case basis. Of course, this assumes that the browser can determine which applets it ought to trust. We'll see how this problem is solved shortly. The integrity of a security manager is based on the protection afforded by the lower levels of the Java security model. Without the guarantees provided by the verifier and the class loader, high-level assertions about the safety of system resources are meaningless. The safety provided by the Java byte-code verifier means that the interpreter can't be corrupted or subverted, and that Java code has to use components as they are intended. This, in turn, means that a class loader can guarantee that an application is using the core Java system classes and that these classes are the only means of accessing basic system resources. With these restrictions in place, it's possible to centralize control over those resources with a security manager.
Safety of Design
http://localhost/java/javaref/exp/ch01_05.htm (5 of 5) [20/12/2001 11:01:52]
Application and User Level Security
[Chapter 1] 1.6 Application and User Level Security
Chapter 1 Yet Another Language?
1.6 Application and User Level Security There's a fine line between having enough power to do something useful and having all the power to do anything you want. Java provides the foundation for a secure environment in which untrusted code can be quarantined, managed, and safely executed. However, unless you are content with keeping that code in a little black box and running it just for its own benefit, you will have to grant it access to at least some system resources so that it can be useful. Every kind of access carries with it certain risks and benefits. The advantages of granting an untrusted applet access to your windowing system, for example, are that it can display information and let you interact in a useful way. The associated risks are that the applet may instead display something worthless, annoying, or offensive. Since most people can accept that level of risk, graphical applets and the World Wide Web in general are possible. At one extreme, the simple act of running an application gives it a resource, computation time, that it may put to good use or burn frivolously. It's difficult to prevent an untrusted application from wasting your time, or even attempting a "denial of service" attack. At the other extreme, a powerful, trusted application may justifiably deserve access to all sorts of system resources (e.g., the filesystem, process creation, network interfaces); a malicious application could wreak havoc with these resources. The message here is that important and sometimes complex security issues have to be addressed. In some situations, it may be acceptable to simply ask the user to "OK" requests. Sun's HotJava Web browser can pop up a dialog box and ask the user's permission for an applet to access an otherwise restricted file. However, we can put only so much burden on our users. An experienced person will quickly grow tired of answering questions; an inexperienced user may not even be able to answer the questions. Is it okay for me to grant an applet access to something if I don't understand what that is? Making decisions about what is dangerous and what is not can be difficult. Even ostensibly harmless access, like displaying a window can become a threat when paired with the ability for an untrusted application to communicate off of your host. The Java SecurityManager provides an option to flag windows created by an untrusted application with a special, recognizable border to prevent it from impersonating another application and perhaps tricking you into revealing your password or your secret recipe collection. There is also a grey area, in which an application can do devious things that aren't quite destructive. An applet that can mail a bug report can also mail-bomb your boss. The Java language provides the tools to implement whatever security policies you want. However, what these policies will be ultimately depends on who you are, what you are doing, and where you are doing it. To fully exploit the power of Java, we need to have some basis on which to make reasonable decisions http://localhost/java/javaref/exp/ch01_06.htm (1 of 3) [20/12/2001 11:01:53]
[Chapter 1] 1.6 Application and User Level Security
about the level of trust an application should have. Web browsers such as HotJava start by defining a few rules and some coarse levels of security that restrict where applets may come from and what system resources they may access. These rules are sufficient to keep the waving Duke applet from clutching your password file, but they aren't sufficient for applications you'd like to trust with sensitive information. What if you want to implement a secure applet to carry a credit card number to the mall, or more likely the credit-card company? How are people to trust that the applet they are using is really secure? If it's named the "Bank of Boofa" applet, how do they know it's legit? You might think of trusting only certain hosts for these kinds of applications. However, as Java class files begin to fill the Net, the situation will become more complicated. Hosts can be impersonated. If your communications pass through an untrusted network, you can't be sure you're talking to the intended entity. Furthermore, class files may need to be cached or retrieved through complicated distribution mechanisms. For these kinds of applications, what we really need is a mechanism for verifying the authorship and authenticity of an item and making sure that it has not been tampered with by the time that you received it. Fortunately, this is a problem solved a while ago by your friendly neighborhood cryptographers.
Signing Classes Digital signatures provide a means of authenticating documents. Like their inky analogs, they associate a name with an item in a way that is supposed to be difficult to forge. Unlike pen on paper, though, electronic digital signatures are actually difficult to forge when used properly. By their nature, digital signatures also provide the benefit that, if authenticated, a document is known not to have been altered in transit. In other words, you can't clip out a digital signature and attach it to a new document. The details of cryptography are a bit beyond the scope of this book but the basics are important and interesting.[6] Digital signatures are one side of the coin of public-key cryptography. Public-key algorithms rely on the fundamental mathematical difficulty of factoring arbitrarily large numbers. In a public-key system, there are two pieces of information: a public key (as you might have guessed) and a private one. These keys have a special asymmetric relationship such that a message encrypted with one key can be decrypted only by knowing the other. This means that by giving you my public key, you can send me messages that only I can read. No one else, including you, has enough information to decrypt the encoded message, so it's safe to send it over untrusted networks. Now, by reversing this process, I can encrypt something with my private key so that anyone can use my public key to read the message. The important thing in this case is that the task of creating such a message without the private key is just as difficult as decoding the message in the first scenario. Since no one else knows my private key, only the real me could have sent the message. This is the basis for digital signatures. For Java, this means that we can tell a browser "I trust applets signed by John Doe"; if the browser succeeds in decoding an applet using John Doe's public key, it knows that the applet really came from John Doe, and therefore can be allowed greater privileges. [6] See Bruce Schneier's encyclopedic Applied Cryptography (John Wiley & Sons). This process can be used to authenticate Java class files and other types of objects sent over the network. The author of a class signs the code with a digital signature, and we authenticate it when we retrieve it. Now we know that we have the authentic class, or do we? There is one problem that a digital signature alone doesn't solve: at some point we still have to assume we have the author's authentic public key. This http://localhost/java/javaref/exp/ch01_06.htm (2 of 3) [20/12/2001 11:01:53]
[Chapter 1] 1.6 Application and User Level Security
is where a key-certification agency comes into play. A key-certification agency validates a key by issuing a certificate that lists a name and an official public key. The certificate is signed with the agency's own digital signature. The agency presumably has a well-known public key to verify the certificate. Of course, this doesn't solve the problem entirely, but it reduces the number of people you have to trust and the amount of information you have to transport reliably. Presumably the agency is a reputable organization, its private keys are well guarded, and it certifies keys only after some kind of real-world validation such as person-to-person contact. The most recent Java release (1.1) contains the tools you need to work with signed classes. You can sign Java classes; you can tell the HotJava browser whose classes you trust (and how much you trust them). Other browsers, like Netscape Navigator, should support signed classes in the future. You can also use the security API in your own Java programs to handle sensitive data safely. The important thing is, as always, to know who you are dealing with and what kind of software and security you have in place before sending any kind of confidential information over the Net. Don't become paranoid, just keep yourself informed so that you can weigh the risks and the benefits.
Safety of Implementation
http://localhost/java/javaref/exp/ch01_06.htm (3 of 3) [20/12/2001 11:01:53]
Java and the World Wide Web
[Chapter 1] 1.7 Java and the World Wide Web
Chapter 1 Yet Another Language?
1.7 Java and the World Wide Web Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice, "without pictures or conversations?" --Alice in Wonderland The application-level safety features of Java make it possible to develop new kinds of applications not necessarily feasible before now. A Web browser that implements the Java run-time system can incorporate Java applets as executable content inside of documents. This means that Web pages can contain not only static hypertext information but also full-fledged interactive applications. The added potential for use of the WWW is enormous. A user can retrieve and use software simply by navigating with a Web browser. Formerly static information can be paired with portable software for interpreting and using the information. Instead of just providing some data for a spreadsheet, for example, a Web document might contain a fully functional spreadsheet application embedded within it that allows users to view and manipulate the information.
Applets The term applet is used to mean a small, subordinate, or embeddable application. By embeddable, I mean it's designed to be run and used within the context of a larger system. In that sense, most programs are embedded within a computer's operating system. An operating system manages its native applications in a variety of ways: it starts, stops, suspends, and synchronizes applications; it provides them with certain standard resources; and it protects them from one another by partitioning their environments. In this book, I'll be describing Java applets, which are Java applications meant to be embedded in and controlled by a larger application, such as a Java-enabled Web browser or an applet viewer. To include an applet as executable content in a Web document, you use a special HTML tag. The tag points to an applet and provides configuration information about the applet. As far as the Web browser model is concerned, an applet is just another type of object to display. Browsers make a distinction between items presented inline and items anchored via hypertext links and made available by external means, such as a viewer or helper application. If you download an MPEG video clip, for instance, and your browser doesn't natively understand MPEG, it will look for a helper http://localhost/java/javaref/exp/ch01_07.htm (1 of 5) [20/12/2001 11:01:55]
[Chapter 1] 1.7 Java and the World Wide Web
application (an MPEG player) to pass the information to. Java-enabled Web browsers generally execute applets inline, in the context of a particular document, as shown in Figure 1.4. However, less capable browsers could initially provide some support for Java applets through an external viewer. Figure 1.4: Applets in a Web document
A Java applet is a compiled Java program, composed of classes just like any Java program. While a simple applet may consist of only a single class, most large applets should be broken into many classes. Each class is stored in a separate class file. The class files for an applet are retrieved from the network as they are needed. A large applet doesn't need to retrieve all its parts or all its data before beginning to interact with the user. Well-designed applets can take advantage of multithreading to wait for certain resources in the background, while performing other activities. An applet has a four-part life cycle. When an applet is initially loaded by a Web browser, it's asked to initialize itself. The applet is then informed each time it's displayed and each time it's no longer visible to the user. Finally, the applet is told when it's no longer needed, so that it can clean up after itself. During its lifetime, an applet may start and suspend itself, do work, communicate with other applications, and interact with the Web browser. Applets are autonomous programs, but they are confined within the walls of a Web browser or applet viewer, and have to play by its rules. I'll be discussing the details of what applets can and can't do as we explore features of the Java language. However, under the most conservative security policies, an applet can interact only with the user and can only communicate over the network with the host from which it originated. Other types of activities, like accessing files or interacting directly with outside applications, are typically prevented by the security manager that is part of the Web browser or applet viewer. But aside from these restrictions, there is no fundamental difference between a Java applet and a standalone Java application. http://localhost/java/javaref/exp/ch01_07.htm (2 of 5) [20/12/2001 11:01:55]
[Chapter 1] 1.7 Java and the World Wide Web
New Kinds of Applications Sun's HotJava Web browser is written entirely in Java. Because it's a Java application, HotJava is immediately available on any platform with the Java run-time system. This goes a long way towards the goal of a Web browser serving as a universal access point for resources on the Net. And where one Web browser leads the way, more will surely follow. In addition to displaying Java applets as executable content in Web pages, the HotJava application dynamically extends itself by loading Java code from the Net. HotJava uses protocol handlers and content handlers to provide this functionality.[7] Protocol handlers and content handlers are classes in the Java API that let an application implement new types of URLs and interpret the objects retrieved from them. A Web browser that supports this functionality can load handlers from a remote location and effectively upgrade itself on the fly to use new protocols and access new kinds of information. [7] Downloadable content and protocol handlers are not supported in HotJava 1.0, but will be supported in a future release. Like applets, content handlers and protocol handlers can be served by a Web site, along with the information they interpret. As an example, consider the new Portable Network Graphics (PNG) format, a freely distributable alternative to GIF. By supplying a PNG content handler along with PNG images on our server, we give users the ability to use the new image format, just as they would a built-in format. We don't have to create a new standard and force every Web browser to support the new format. Instead, the first time a user loads a document referencing a PNG image from our site, the Web browser will realize it doesn't understand the object and will ask the server if it has a content handler for it. Since we've provided a content handler, the browser can load it and then use it to interpret and display the image dynamically. In a similar manner, protocol handlers allow a Web browser to start speaking a new protocol with the server. This is especially useful for things like security protocols. If we invent a revolutionary new cryptographic protocol late one night, all we have to do is implement it in the form of a protocol handler and place it on our server. We can then start using URLs that point through our new protocol at objects on our server, and people can immediately begin using it. These scenarios describe just a few things that safe, transportable code will allow. We will undoubtedly see many other new breeds of application we can't even begin to anticipate.
New Kinds of Media When it was first released, Java quickly achieved a reputation for multimedia capabilities. Frankly, this wasn't really deserved. At that point, Java provided facilities for doing simple animations and playing audio. You could even animate and play audio simultaneously, though you couldn't synchronize the two. Still, this was a significant advance for the Web, and people thought it was pretty impressive. JavaSoft is now working on real media features, which go far beyond anything that has yet been seen on the Web. This includes CD quality sound, 3D animation, media players that synchronize audio and video, speech synthesis and recognition, and more. These new features aren't yet in Java 1.1, but will make their way into Java over the next eighteen months. In short, if you were impressed by Java 1.0, you http://localhost/java/javaref/exp/ch01_07.htm (3 of 5) [20/12/2001 11:01:55]
[Chapter 1] 1.7 Java and the World Wide Web
haven't seen anything yet. Java's multimedia capabilities will be taking shape over the next two years.
New Software Development Models For some time now, people have been using visual development environments to develop user interfaces. These environments let you generate applications by moving components around on the screen, connecting components to each other, and so on. In short, designing a user interface is a lot more like drawing a picture than like writing code. For visual development environments to work well, you need to be able to create reusable software components. That's what Java Beans are all about. The JavaBeans architecture defines a way to package software as reusable building blocks. A graphical development tool can figure out a component's capabilities, customize the component, and connect it to other components to build applications. JavaBeans takes the idea of graphical development a step further. Beans aren't limited to visible, user interface components: you can have Beans that are entirely invisible, and whose job is purely computational. For example, you could have a Bean that did database access; you could connect this to a Bean that let the user request information from the database; and you could use another Bean to display the result. Or you could have a set of Beans that implemented the functions in a mathematical library; you could then do numerical analysis by connecting different functions to each other. In either case, you could "write" programs without writing a single line of code. Granted, someone would have to write the Beans in the first place; but that's a much smaller task, and we expect markets to develop for "off the shelf" Bean collections. Before it can use a Bean, an application builder must find out the Bean's capabilities. There are a few ways it can do this; the simplest is called "reflection". To write a Bean that uses reflection, all you need to do is follow some simple design patterns. Let's say that you're writing a Bean that is capable of changing its color. Then you would write two methods that report the current color and change its value: ... private Color c; public Color getMyColor() { return c; } public void setMyColor( Color c) { this.c = c; } These methods follow some well defined conventions (design patterns) that let the graphical interface builder (or any other tool that wants to do the work) analyze the Bean, and discover that it has a property called MyColor, that the value of this property is a Color object, and that the methods getMyColor() and setMyColor() should be used to change its value. If they need to, Beans can provide additional information using a process called "introspection". But even without introspection, you can see that a graphical development tool can easily analyze a Bean, figure out what it can do, and let a user change the Bean's properties without writing any code. Of course, once a development tool has customized a Bean and connected it to other Beans, it needs a way to save the result. A process called "serialization" lets a tool save the Bean's current state, along with any extra code it has written to stitch Beans together in an application. Visual development tools that support Java Beans include Borland's JBuilder (http://www.borland.com),
http://localhost/java/javaref/exp/ch01_07.htm (4 of 5) [20/12/2001 11:01:55]
[Chapter 1] 1.7 Java and the World Wide Web
Symantec's Visual Cafe (http://www.symantec.com), and SunSoft's Java Workshop. By using a "bridge", Java Beans will be able to interact with other component environments, including ActiveX, OpenDoc, and LiveConnect. A beta version of the ActiveX bridge is currently available.
Application and User Level Security
http://localhost/java/javaref/exp/ch01_07.htm (5 of 5) [20/12/2001 11:01:55]
Java as a General Application Language
[Chapter 1] 1.8 Java as a General Application Language
Chapter 1 Yet Another Language?
1.8 Java as a General Application Language The Java applet API is a framework that allows Java-enabled Web browsers to manage and display embedded Java applications within WWW documents. However, Java is more than just a tool for building transportable multimedia applications. Java is a powerful, general-purpose programming language that just happens to be safe and architecture independent. Standalone Java applications are not subject to the restrictions placed on applets; they can do all activities that software written in a language like C does. Any software that implements the Java run-time system can run Java applications. Applications written in Java can be large or small, standalone or component-like, as in other languages. Java applets are different from other Java applications only in that they expect to be managed by a larger application. In this book, we will build examples of both applets and standalone Java applications. With the exception of the few things applets can't do, such as access files, all of the tools we examine in this book apply to both applets and standalone Java applications.
Java and the World Wide Web
http://localhost/java/javaref/exp/ch01_08.htm [20/12/2001 11:01:56]
A Java Road Map
[Chapter 1] 1.9 A Java Road Map
Chapter 1 Yet Another Language?
1.9 A Java Road Map With everything that's going on, it's hard to keep track of what's available now, what's promised, and what has been around for some time. Here's a road map that tries to impose some order on Java's past, present, and future.
The Past: Java 1.0 Java 1.0 provided the basic framework for Java development: the language itself, plus packages that let you write applets and simple applications. Java 1.0 is officially obsolete, though it will be some time before vendors catch up with the new release.
The Present: Java 1.1 Java 1.1 is the current version of Java. It incorporates major improvements in the AWT package (Java's windowing facility). It also adds many completely new features, including: JDBC A general facility for interacting with databases. RMI Remote Method Invocation: a facility that lets you call methods that are provided by a server running somewhere else on the network. JavaBeans Java's component architecture, which we discussed earlier. Security A facility for cryptography; this is the basis for signed classes, which we discussed earlier. Internationalization The ability to write programs that adapt themselves to the language the user wants to use; the program automatically displays text in the appropriate language. Java 1.1 incorporates many other improvements and new features, but these are the most important. As of May, 1997, most Web browsers haven't yet incorporated Java 1.1, but they will as soon as possible. In http://localhost/java/javaref/exp/ch01_09.htm (1 of 2) [20/12/2001 11:01:56]
[Chapter 1] 1.9 A Java Road Map
this book, we'll try to give you a taste of as many features as possible; unfortunately for us, the Java environment has become so rich that it's impossible to cover everything in a single book.
The Future We've mentioned a few of the things that are in the pipeline, including high quality audio, advanced 3D rendering, and speech synthesis. Other things to look forward to are class libraries for advanced 2D graphics (Java 2D), electronic commerce (JECF), managing network devices (Java Management), naming and directory services (JNDI), telephony (JTAPI), and writing network servers (Java Server). Beta versions of some of these facilities are available now. We're also starting to see new kinds of computing devices that incorporate Java. Network computers that are based on Java and use the HotJava browser as their user interface are already available, as are "smart cards": credit card-like devices with a Java processor built in. You can expect to see Java incorporated into PDAs, telephones, and many other devices.
Java as a General Application Language
http://localhost/java/javaref/exp/ch01_09.htm (2 of 2) [20/12/2001 11:01:56]
Availability
[Chapter 1] 1.10 Availability
Chapter 1 Yet Another Language?
1.10 Availability By the time you read this book, you should have several choices for Java development environments and run-time systems. As this book goes to press, Sun's Java Development Kit (JDK) 1.1 is available for Solaris, Windows NT, and Windows 95. The JDK provides an interpreter and a compiler for building general-purpose Java applications. A beta version of JDK 1.1 for the Macintosh will be available later in 1997. Visit Sun's Java Web site, http://www.javasoft.com/ for more information about the JDK. There are also a number of JDK ports for various platforms. Some of the most significant platforms are Novell, HP-UX, OSF/1 (including Digital UNIX), Silicon Graphics' IRIX, and Linux. For more information, see the Web pages maintained by the vendor you're interested in. JavaSoft maintains a Web page summarizing porting efforts at http://www.javasoft.com/products/jdk/jdk-ports.html. Another good source for current information is the Java FAQ from the comp.lang.java newsgroup. There are efforts under way to produce a free clone of Java, redistributable in source form. The Java Open Language Toolkit (JOLT) Project is working to assemble a high-quality Java implementation that will pass Sun's validation tests and earn a Java stamp. The JOLT Project Web page is accessible from http://www.redhat.com/. The Netscape Navigator Web browser comes with its own implementation of the Java run-time system that runs Java applets. Netscape also provides a -java switch that lets you execute Java applications (including the Java compiler) and applets and run nongraphical applications. Netscape's Web site is located at http://home.netscape.com/. Check there for information on the latest version of Netscape Navigator.
A Java Road Map
http://localhost/java/javaref/exp/ch01_10.htm [20/12/2001 11:01:57]
A First Applet
[Chapter 2] 2.2 Hello Web! II: The Sequel
Chapter 2 A First Applet
2.2 Hello Web! II: The Sequel Let's make our applet a little more interactive, shall we? The following improvement, HelloWeb2, allows us to drag the message around with the mouse. HelloWeb2 is also customizable. It takes the text of its message from a parameter of the tag of the HTML document. HelloWeb2 is a new applet--another subclass of the Applet class. In that sense, it's a sibling of HelloWeb. Having just seen inheritance at work, you might wonder why we aren't creating a subclass of HelloWeb and exploiting inheritance to build upon our previous example and extend its functionality. Well, in this case, that would not necessarily be an advantage, and for clarity we simply start over.[2] Here is HelloWeb2: [2] You are left to consider whether such a subclassing would even make sense. Should HelloWeb2 really be a kind of HelloWeb? Are we looking for refinement or just code reuse? import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class HelloWeb2 extends Applet implements MouseMotionListener { int messageX = 125, messageY = 95; String theMessage; public void init() { theMessage = getParameter("message"); addMouseMotionListener(this); } public void paint( Graphics graphics ) { graphics.drawString( theMessage, messageX, messageY ); } public void mouseDragged( MouseEvent e ) { messageX = e.getX(); messageY = e.getY(); repaint();
http://localhost/java/javaref/exp/ch02_02.htm (1 of 8) [20/12/2001 11:01:59]
[Chapter 2] 2.2 Hello Web! II: The Sequel
} public void mouseMoved( MouseEvent e ) { } } Place the text of this example in a file called HelloWeb2.java and compile it as before. You should get a new class file, HelloWeb2.class, as a result. We need to create a new tag for HelloWeb2. You can either create another HTML document (copy HelloWeb.html and modify it) or simply add a second tag to the existing HelloWeb.html file. The tag for HelloWeb2 has to use a parameter; it should look like: <param name="message" value="Hello Web!" > Feel free to substitute your own salacious comment for the value of message. Run this applet in your Java-enabled Web browser, and enjoy many hours of fun, dragging the text around with your mouse.
Import So, what have we added? First you may notice that a few lines are now hovering above our class: import import import public ...
java.applet.Applet; java.awt.*; java.awt.event.*; class HelloWeb2 extends Applet implements MouseMotionListener {
The import statement lists external classes to use in this file and tells the compiler where to look for them. In our first HellowWeb example, we designated the Applet class as the superclass of HelloWeb. Applet was not defined by us and the compiler therefore had to look elsewhere for it. In that case, we referred to Applet by its fully qualified name, java.applet.Applet, which told the compiler that Applet belongs to the java.applet package so it knew where to find it. The import statement is really just a convenience; by importing java.applet.Applet in our newer example, we tell the compiler up front we are using this class and, thereafter in this file, we can simply refer to it as Applet. The second import statement makes use of the wildcard "*" to tell the compiler to import all of the classes in the java.awt package. But don't worry, the compiled code doesn't contain any excess baggage. Java doesn't do things like that. In fact, compiled Java classes don't contain other classes at all; they simply note their relationships. Our current example uses only the java.awt.Graphics class. However, we are anticipating using several more classes from this package in the upcoming examples. We also import all the classes from the package java.awt.event; these classes provide the Event objects that we use to communicate with the user. By listening for events, we find out when the user moved the mouse, clicked a button, and so on. Notice that importing java.awt.* doesn't automatically import the event package. The star only imports the classes in a particular package, not other packages.
http://localhost/java/javaref/exp/ch02_02.htm (2 of 8) [20/12/2001 11:01:59]
[Chapter 2] 2.2 Hello Web! II: The Sequel
The import statement may seem a bit like the C or C++ preprocessor #include statement, which injects header files into programs at the appropriate places. This is not true; there are no header files in Java. Unlike compiled C or C++ libraries, Java binary class files contain all necessary type information about the classes, methods, and variables they contain, obviating the need for prototyping.
Instance Variables We have added some variables to our example: public class HelloWeb2 extends Applet { int messageX = 125, messageY = 95; String theMessage; ... messageX and messageY are integers that hold the current coordinates of our movable message. They are initialized to default values, which should place a message of our length somewhere near the center of the applet. Java integers are always 32-bit signed numbers. There is no fretting about what architecture your code is running on; numeric types in Java are precisely defined. The variable theMessage is of type String and can hold instances of the String class. You should note that these three variables are declared inside the braces of the class definition, but not inside any particular method in that class. These variables are called instance variables because they belong to the entire class, and copies of them appear in each separate instance of the class. Instance variables are always visible (usable) in any of the methods inside their class. Depending on their modifiers, they may also be accessible from outside the class. Unless otherwise initialized, instance variables are set to a default value of 0 (zero), false, or null. Numeric types are set to zero, boolean variables are set to false, and class type variables always have their value set to null, which means "no value." Attempting to use an object with a null value results in a run-time error. Instance variables differ from method arguments and other variables that are declared inside of a single method. The latter are called local variables. They are effectively private variables that can be seen only by code inside the method. Java doesn't initialize local variables, so you must assign values yourself. If you try to use a local variable that has not yet been assigned a value, your code will generate a compile-time error. Local variables live only as long as the method is executing and then disappear (which is fine since nothing outside of the method can see them anyway). Each time the method is invoked, its local variables are recreated and must be assigned values.
Methods We have made some changes to our previously stodgy paint() method. All of the arguments in the call to drawString() are now variables. Several new methods have appeared in our class. Like paint(), these are methods of the base Applet class we override to add our own functionality. init() is an important method of the Applet class. It's called once, when our applet is created, to give us an opportunity to do any work needed to set up shop.
http://localhost/java/javaref/exp/ch02_02.htm (3 of 8) [20/12/2001 11:01:59]
[Chapter 2] 2.2 Hello Web! II: The Sequel
init() is a good place to allocate resources and perform other activities that need happen only once in the lifetime of the applet. A Java-enabled Web browser calls init() when it prepares to place the Applet on a page. Our overridden init() method does two things; it sets the text of the theMessage instance variable, and it tells the system "Hey, I'm interested in anything that happens involving the mouse": public void init() { theMessage = getParameter("message"); addMouseMotionListener(this); } When an applet is instantiated, the parameters given in the tag of the HTML document are stored in a table and made available through the getParameter() method. Given the name of a parameter, this method returns the value as a String object. If the name is not found, it returns a null value. So what, you may ask, is the type of the argument to the getParameter() method? It, too, is a String. With a little magic from the Java compiler, quoted strings in Java source code are turned into String objects. A bit of funny-business is going on here, but it's simply for convenience. (See Chapter 7, Basic Utility Classes for a complete discussion of the String class.) getParameter() is a public method we inherited from the Applet class. We can use it from any of our methods. Note that the getParameter() method is invoked directly by name; there is no object name prepended to it with a dot. If a method exists in our class, or is inherited from a superclass, we can call it directly by name. In addition, we can use a special read-only variable, called this, to explicitly refer to our object. A method can use this to refer to the instance of the object that holds it. The following two statements are therefore equivalent: theMessage = getParameter("message"); or theMessage = this.getParameter("message"); I'll always use the shorter form. We will need the this variable later when we have to pass a reference to our object to a method in another class. We often do this so that methods in another class can give us a call back later or can watch our public variables. The other method that we call in init() is addMouseMotionListener(). This method is part of the event mechanism, which we discuss next.
http://localhost/java/javaref/exp/ch02_02.htm (4 of 8) [20/12/2001 11:01:59]
[Chapter 2] 2.2 Hello Web! II: The Sequel
Events The last two methods of HelloWeb2 let us get information from the mouse. Each time the user performs an action, such as hitting a key on the keyboard, moving the mouse, or perhaps banging his or her head against a touch-sensitive screen, Java generates an event. An event represents an action that has occurred; it contains information about the action, such as its time and location. Most events are associated with a particular graphical user interface (GUI) component in an application. A keystroke, for instance, could correspond to a character being typed into a particular text entry field. Pressing a mouse button could cause a certain graphical button on the screen to activate. Even just moving the mouse within a certain area of the screen could be intended to trigger effects such as highlighting or changing the cursor to a special mouse cursor. The way events work is one of the biggest changes between Java 1.0 and Java 1.1. We're going to talk about the Java 1.1 events only; they're a big improvement, and there's no sense in learning yesterday's news. In Java 1.1, there are many different event classes: MouseEvent, KeyEvent, ActionEvent, and many others. For the most part, the meaning of these events is fairly intuitive. A MouseEvent occurs when the user does something with the mouse, a KeyEvent occurs when the user types a key, and so on. ActionEvent is a little special; we'll see it at work in our third applet. For now, we'll focus on dealing with a MouseEvent. The various GUI components in Java generate events. For example, if you click the mouse inside an applet, the applet generates a mouse event. (In the future, we will probably see events as a general purpose way to communicate between Java objects; for the moment, let's limit ourselves to the simplest case.) In Java 1.1, any object can ask to receive the events generated by some other component. We call the object that wants to receive events a "listener." To declare that it wants to receive some component's mouse motion events, you call that component's addMouseMotionListener() method. That's what our applet is doing in init(). In this case, the applet is calling its own addMouseMotionListener() method, with the argument this, meaning "I want to receive my own mouse motion events." (For the time being, we're ignoring a minor distinction between "mouse events" and "mouse motion events." Suffice it to say that in this example, we only care about mouse motions.) That's how we register to receive events. But how do we actually get them? That's what the two remaining methods in our applet are for. The mouseDragged() method is called automatically whenever the user drags the mouse--that is, moves the mouse with any button pressed. The mouseMoved() method is called whenever the user moves the mouse without pressing a button. Our mouseMoved() method is simple: it doesn't do anything. We're ignoring simple mouse motions. mouseDragged() has a bit more meat to it. It is called repeatedly to give us updates on the position of the mouse. Here it is: public void mouseDragged( MouseEvent e ) { messageX = e.getX(); messageY = e.getY(); repaint(); }
http://localhost/java/javaref/exp/ch02_02.htm (5 of 8) [20/12/2001 11:01:59]
[Chapter 2] 2.2 Hello Web! II: The Sequel
The first argument to mouseDragged() is a MouseEvent object, e, that contains all the information we need to know about this event. We ask the MouseEvent to tell us the x and y coordinates of the mouse's current position by calling its getX() and getY() methods. These are saved in the messageX and messageY instance variables. Now, having changed the coordinates for the message, we would like HelloWeb2 to redraw itself. We do this by calling repaint(), which asks the system to redraw the screen at a later time. We can't call paint() directly because we don't have a graphics context to pass to it. The real beauty of this event model is that you only have to handle the kinds of events you want. If you don't care about keyboard events, you just don't register a listener for them; the user can type all he or she wants, and you won't be bothered. Java doesn't go around asking potential recipients whether they might be interested in some event, as it did in older versions. If there are no listeners for a particular kind of event, Java won't even generate it. The result is that event handling in Java 1.1 is quite efficient. I've danced around one question that should be bothering you by now: how does the system know to call mouseDragged() and mouseMoved()? And why do we have to supply a mouseMoved() method that doesn't do anything? The answer to these questions has to do with "interfaces." We'll discuss interfaces after clearing up some unfinished business with repaint().
The repaint() Method We can use the repaint() method of the Applet class to request our applet be redrawn. repaint() causes the Java windowing system to schedule a call to our paint() method at the next possible time; Java supplies the necessary Graphics object, as shown in Figure 2.5. Figure 2.5: Invoking the repaint() method
This mode of operation isn't just an inconvenience brought about by not having the right graphics context handy at the moment. The foremost advantage to this mode of operation is that the repainting is handled by someone else, while we are free to go about our business. The Java system has a separate, dedicated thread of execution that handles all repaint() requests. It can schedule and consolidate repaint() requests as necessary, which helps to prevent the windowing system from being overwhelmed during painting-intensive situations like scrolling. Another advantage is that all of the painting functionality can be kept in our paint() method; we aren't tempted to spread it throughout the application.
http://localhost/java/javaref/exp/ch02_02.htm (6 of 8) [20/12/2001 11:01:59]
[Chapter 2] 2.2 Hello Web! II: The Sequel
Interfaces Now it's time to face up to the question I avoided earlier: how does the system know to call mouseDragged() when a mouse event occurs? Is it simply a matter of knowing that mouseDragged() is some magic name that our event handling method must have? No; the answer to the question lies in the discussion of interfaces, which are one of the most important features of the Java language. The first sign of an interface comes on the line of code that introduces the HelloWeb2 applet: we say that the applet implements MouseMotionListener. MouseMotionListener is an interface that the applet implements. Essentially, it's a list of methods that the applet must have; this particular interface requires our applet to have methods called mouseDragged() and mouseMoved(). The interface doesn't say what these methods have to do--and indeed, mouseMoved() doesn't do anything. It does say that the methods must take a MouseEvent as an argument and return void (i.e., no return value). Another way of looking at an interface is as a contract between you, the code developer, and the compiler. By saying that your applet implements the MouseMotionListener interface, you're saying that these methods will be available for other parts of the system to call. If you don't provide them, the compiler will notice and give you an error message. But that's not the only impact interfaces have on this program. An interface also acts like a class. For example, a method could return a MouseMotionListener, or take a MouseMotionListener as an argument. This means that you don't care about the object's class; the only requirement is that the object implement the given interface. In fact, that's exactly what the method addMouseMotionListener() does. If you look up the documentation for this method, you'll find that it takes a MouseMotionListener as an argument. The argument we pass is this, the applet itself. The fact that it's an applet is irrelevant, it could be a Cookie, an Aardvark, or any other class we dream up. What is important is that it implements MouseMotionListener, and thus declares that it will have the two named methods. That's why we need a mouseMoved() method, even though the one we supplied doesn't do anything: the MouseMotionListener interface says we have to have one. In other languages, you'd handle this problem by passing a function pointer; for example, in C, the argument to addMouseMotionListener() might be a pointer to the function you want to have called when an event occurs. This technique is called a "callback." For security reasons, the Java language has eliminated function pointers. Instead, we use interfaces to make contracts between classes and the compiler. (Some new features of the language make it easier to do something similar to a callback, but that's beyond the present discussion.) The Java distribution comes with many interfaces that define what classes have to do in various situations. Furthermore, in Chapter 5, Objects in Java, you'll see how to define your own interfaces. It turns out that this idea of a contract between the compiler and a class is very important. There are many situations like the one we just saw, where you don't care what class something is, you just care that it has some capability, like listening for mouse events. Interfaces give you a way of acting on objects based on their capabilities, without knowing or caring about their actual type. Furthermore, interfaces provide an important escape clause to the rule that any new class can only extend a single class (formally called "single inheritance"). They provide most of the advantages of multiple inheritance (a feature of languages like C++) without the confusion. A class in Java can only extend one http://localhost/java/javaref/exp/ch02_02.htm (7 of 8) [20/12/2001 11:01:59]
[Chapter 2] 2.2 Hello Web! II: The Sequel
class, but can implement as many interfaces as it wants; our next applet will implement two interfaces, and the final example in this chapter will implement three. In many ways, interfaces are almost like classes, but not quite. They can be used as data types, they can even extend other interfaces (but not classes), and can be inherited by classes (if class A implements interface B, subclasses of A also implement B). The crucial difference is that applets don't actually inherit methods from interfaces; the interfaces only specify the methods the applet must have.
Hello Web!
http://localhost/java/javaref/exp/ch02_02.htm (8 of 8) [20/12/2001 11:01:59]
Hello Web! III: The Button Strikes!
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
Chapter 2 A First Applet
2.3 Hello Web! III: The Button Strikes! Well, now that we have those concepts under control, we can move on to some fun stuff. HelloWeb3 brings us a new graphical interface component: the Button. We add a Button component to our applet that changes the color of our text each time the button is pressed. Our new example is shown below. import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class HelloWeb3 extends Applet implements MouseMotionListener, ActionListener { int messageX = 125, messageY = 95; String theMessage; Button theButton; int colorIndex = 0; static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; public void init() { theMessage = getParameter("message"); theButton = new Button("Change Color"); add(theButton); addMouseMotionListener(this); theButton.addActionListener(this); } public void paint( Graphics gc ) { gc.drawString( theMessage, messageX, } public void mouseDragged( MouseEvent e ) messageX = e.getX(); messageY = e.getY(); repaint(); } public void mouseMoved( MouseEvent e ) { public void actionPerformed( ActionEvent http://localhost/java/javaref/exp/ch02_03.htm (1 of 10) [20/12/2001 11:02:02]
messageY ); {
} e ) {
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
if ( e.getSource() == theButton ) { changeColor(); } } synchronized private void changeColor() { if ( ++colorIndex == someColors.length ) colorIndex = 0; setForeground( currentColor() ); repaint(); } synchronized private Color currentColor() { return someColors[ colorIndex ]; } } Create HelloWeb3 just as the other applets and put an tag referencing it in an HTML document. An tag just like the one for HelloWeb2 will do nicely. Run the example, and you should see the display shown in Figure 2.6. Drag the text. Each time you press the button the color should change. Call your friends! They should be duly impressed. Figure 2.6: Hello Web! III
The New Operator So what have we added this time? Well, for starters we have a new variable: Button theButton; The theButton variable is of type Button and is going to hold an instance of the java.awt.Button class. The Button class, as you might expect, represents a graphical button, which should look like other http://localhost/java/javaref/exp/ch02_03.htm (2 of 10) [20/12/2001 11:02:02]
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
buttons in your windowing system. Two additional lines in init() actually create the button and cause it to be displayed in our applet: theButton = new Button("Change Color"); add(theButton); The first line brings us to something new. The new keyword is used to create an instance of a class. Recall that the variable we have declared is just an empty reference and doesn't yet point to a real object--in this case, an instance of the Button class. This is a fundamental and important concept. We have dealt with objects previously in our examples. We have assigned them to variables, and we have called methods in them. So far, however, these objects have always been handed to us ready to go, and we have not had to explicitly create them ourselves. In the case of our paint() method, we were given a Graphics object with which to draw. The system created this instance of the Graphics class for our area of the screen and passed it to us in the parameter variable gc. Our theMessage variable is of type String, and we used it to hold a String that was returned by the getParameter() method. In each case, some other method instantiated (created a new instance of) the class for us. The closest we came to actually instantiating an object was when we passed the name of the HTML parameter as an argument to the getParameter() method. In that case, we created a String object and passed it as the argument, but we did it in a rather sneaky fashion. As I mentioned previously, String objects have special status in the Java language. Because strings are used so frequently, the Java compiler creates an instance of the String class for us whenever it comes across quoted text in our source code. String objects are, in all other respects, normal objects. (See Chapter 7, Basic Utility Classes.) The new operator provides the general mechanism for instantiating objects. It's the feature of the Java language that creates a new instance of a specified class. It arranges for Java to allocate storage for the object and then calls the constructor method of the objects' class to initialize it.
Constructors A constructor is a special method that is called to set up a new instance of a class. When a new object is created, Java allocates storage for it, sets variables to their default values, and then calls the constructor method for the class to do whatever application-level setup is required. A constructor method looks like a method with the same name as its class. For example, the constructor for the Button class is called Button(). Constructors don't have a return type; by definition they return an object of that class. But like other methods, constructors can take arguments. Their sole mission in life is to configure and initialize newly born class instances, possibly using whatever information is passed to them in parameters. It's important to understand the difference between a constructor and a method like our init() method. Constructors are special methods of a class that help set up and initialize an instance of a class when it's first created. The init() method of the Applet class serves a very similar purpose; however, it's quite different. Constructors are a feature of the Java language. Every class, including Applet, has constructors. init(), however, is just a method of the Applet class like any other. It's an application-level phenomenon that happens to perform initialization.
http://localhost/java/javaref/exp/ch02_03.htm (3 of 10) [20/12/2001 11:02:02]
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
An object is created by using the new operator with the constructor for the class and any necessary arguments. The resulting object instance is returned as a value. In our example, we create a new instance of Button and assign it to our theButton variable: theButton = new Button("Change Color"); This Button constructor takes a String as an argument and, as it turns out, uses it to set the label of the button on the screen. A class could also, of course, provide methods that allow us to configure an object manually after it's created or to change its configuration at a later time. Many classes do both; the constructor simply takes its arguments and passes them to the appropriate methods. The Button class, for example, has a public method, setLabel(), that allows us to set a Button's label at any time. Constructors with parameters are therefore a convenience that allows a sort of short hand to set up a new object.
Method Overloading I said this Button constructor because there could be more than one. A class can have multiple constructors, each taking different parameters and possibly using them to do different kinds of setup. When there are multiple constructors for a class, Java chooses the correct one based on the types of arguments that are passed to it. We call the Button constructor and pass it a String argument, so Java locates the constructor method of the Button class that takes a single String argument and uses it to set up the object. This is called method overloading. All methods in Java, not just constructors, can be overloaded; this is one aspect of the object-oriented programming principle of polymorphism. A constructor method that takes no arguments is called the default constructor. As you'll see in Chapter 7, Basic Utility Classes, default constructors play a special role in the initialization of inherited class members.
Garbage Collection I've told you how to create a new object with the new operator, but I haven't said anything about how to get rid of an object when you are done with it. If you are a C programmer, you're probably wondering why not. The reason is that you don't have to do anything to get rid of objects when you are done with them. The Java run-time system uses a garbage collection mechanism to deal with objects no longer in use. The garbage collector sweeps up objects not referenced by any variables and removes them from memory. Garbage collection is one of the most important features of Java. It frees you from the error-prone task of having to worry about details of memory allocation and deallocation.
Components I have used the terms component and container somewhat loosely to describe graphical elements of Java applications. However, you may recall from Figure 2.3 that these terms are the names of actual classes in the java.awt package. Component is a base class from which all of Java's GUI components are derived. It contains variables that represent the location, shape, general appearance, and status of the object, as well as methods for basic painting and event handling. The familiar paint() method we have been using in our example is actually inherited from the Component class. Applet is, of course, a kind of Component and inherits all of its public members, just as other (perhaps simpler) types of GUI components do. http://localhost/java/javaref/exp/ch02_03.htm (4 of 10) [20/12/2001 11:02:02]
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
The Button class is also derived from Component and therefore shares this functionality. This means that the developer of the Button class had methods like paint() available with which to implement the behavior of the Button object, just as we did when creating our applet. What's exciting is that we are perfectly free to further subclass components like Button and override their behavior to create our own special types of user-interface components. Both Button and Applet are, in this respect, equivalent types of things. However, the Applet class is further derived from a class called Container, which gives it the added ability to hold other components and manage them.
Containers A Button object is a simple GUI component. It makes sense only in the context of some larger application. The Container class is an extended type of Component that maintains a list of child components and helps to group them. The Container causes its children to be displayed and arranges them on the screen according to a particular scheme. A Container may also receive events related to its child components. As I mentioned earlier, if a component doesn't respond to a particular type of event by overriding the appropriate event-handling method and handling the event, the event is passed to the parent Container of the component. This is the default behavior for the standard Java AWT components, which gives us a great deal of flexibility in managing interface components. We could, for example, create a smart button by subclassing the Button class and overriding certain methods to deal with the action of being pressed. Alternatively, we could simply have the Button's container note which Button is pressed and handle the event appropriately. In the interest of keeping our examples contained in a single class, I am using the gestalt view and letting our Button's container, HelloWeb3, deal with its events. Remember that a Container is a Component too and, as such, can be placed alongside other Component objects in other Containers, in a hierarchical fashion, as shown in Figure 2.7. Our HelloWeb3 applet is a kind of Container and can therefore hold and manage other Java AWT components and containers like buttons, sliders, text fields, and panels. Figure 2.7: A hypothetical layout of Java containers and components
In Figure 2.7, the italicized items are components, and the bold items are containers. The keypad is http://localhost/java/javaref/exp/ch02_03.htm (5 of 10) [20/12/2001 11:02:02]
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
implemented as a container object that manages a number of keys. The keypad itself is contained in the GizmoTool container object.
Layout After creating the Button object, we'd like to stick it in our applet. To do so, we invoke the add() method of Applet, passing the Button object as a parameter: add(theButton); add() is a method inherited by our Applet from the Container class. It appends our Button to the list of components HelloWeb3 manages. Thereafter, HelloWeb3 is responsible for the Button: the applet causes the button to be displayed, it determines where in our part of the screen the button should be placed, and it receives events when the button is pushed. Java uses an object called a LayoutManager to determine the precise location in HelloWeb3's screen area the Button is displayed. A LayoutManager object embodies a particular scheme for arranging components on the screen and adjusting their sizes. You'll learn more about layout managers in Chapter 12, Layout Managers. There are several standard layout managers to choose from, and we can, of course, create new ones. In our case, we have not specified a layout manager, so we get the default one, which means our button appears centered at the top of the applet.
Subclassing and Subtypes If you look up the add() method of the Container class, you'll see that it takes a Component object as an argument. But in our example we've given it a Button object. What's going on? Well, if you check the inheritance diagram in Figure 2.3 again, you'll see that Button is a subclass of the Component class. Because a subclass is a kind of its superclass and has, at minimum, the same public methods and variables, we can use an instance of a subclass anywhere we use an instance of its superclass. This is a very important concept, and it's a second aspect of the object-oriented principle of polymorphism. Button is a kind of Component, and any method that expects a Component as an argument will accept a Button.
More Events and Interfaces Now that we have a Button, we need some way to communicate with it: that is, to get the events it generates. We could just listen for mouse clicks, figure out whether they were close enough to the button, and act accordingly. But that would take a lot of work, and would give up the advantages of using a pre-built component. Buttons generate a special kind of event called an ActionEvent when someone clicks on them. To receive these events, we have added another method to our class: public void actionPerformed( ActionEvent e ) { if ( e.getSource() == theButton ) { changeColor(); } }
http://localhost/java/javaref/exp/ch02_03.htm (6 of 10) [20/12/2001 11:02:02]
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
If you understood the previous applet, you shouldn't be surprised to see that HelloWeb3 now declares that it implements the ActionListener interface, in addition to MouseMotionListener. ActionListener requires us to implement an actionPerformed() method, which is called whenever an ActionEvent occurs. You also shouldn't be surprised to see that we added a line to init(), registering the applet as a listener for the button's action events: this is the call to theButton.addActionListener(this). The actionPerformed() method takes care of any action events that arise. First, it checks to make sure that the event's source (the component generating the event) is what we think it should be: theButton, the only button we've put in the applet. This may seem superfluous; after all, what else could possibly generate an action event? In this applet, nothing. But it's a good idea to check, because another applet may have several buttons, and you may need to figure out which one is meant. Or you may add a second button to this applet later, and you don't want the applet to break something. To make this check, we call the getSource() method of the ActionEvent object, e. Then we use the "==" operator to make sure that the event source matches theButton. Remember that in Java, == is a test for identity, not equality; it is true if the event source and theButton are the same object. The distinction between equality and identity is important. We would consider two String objects to be equal if they have the same characters in the same sequence. However, they might not be the same object. In Chapter 5, Objects in Java, we'll look at the equals() method, which tests for equivalence. Once we establish that the event e comes from the right button, we call our changeColor() method, and we're done. You may be wondering why we don't have to change mouseDragged() now that we have a Button in our applet. The rationale is that the coordinates of the event are all that matter for this method. We are not particularly concerned if the event happens to fall within an area of the screen occupied by another component. This means that you can drag the text right through the Button and even lose it behind the Button if you aren't careful: try it and see!
Color Commentary To support HelloWeb3's colorful side we have added a couple of new variables and two helpful methods. We create and initialize an array of Color objects representing the colors through which we cycle when the button is pressed. We also declare an integer variable that serves as an index to this array, specifying the current color: Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; int colorIndex; A number of things are going on here. First let's look at the Color objects we are putting into the array. Instances of the java.awt.Color class represent colors and are used by all classes in the java.awt package that deal with color graphics. Notice that we are referencing variables such as Color.black and Color.red. These look like normal references to an object's instance variables; however Color is not an object, it's a class. What is the meaning of this?
http://localhost/java/javaref/exp/ch02_03.htm (7 of 10) [20/12/2001 11:02:02]
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
Static Members If you recall our discussion of classes and instances, I hinted then that a class can contain methods and variables that are shared among all instances of the class. These shared members are called static variables and static methods. The most common use of static variables in a class is to hold predefined constants or unchanging objects all of the instances can use. There are two advantages to this approach. The more obvious advantage is that static members take up space only in the class; the members are not replicated in each instance. The second advantage is that static members can be accessed even if no instances of the class exist. A hypothetical Component class might have a static variable called maximumWidth. Some other class that has to deal with this component, such as a layout manager, might want to know the maximum width of such a component, even if there aren't any around at the moment. Since maximumWidth is a static variable, the layout manager can get this information. An instance of the Color class represents a color. For convenience, the Color class contains some static, predefined color objects with friendly names like green, red, and (my favorite) magenta. Color.green is thus a predefined Color object that is set to a green color. In this case, these static members of Color are not changeable, so they are effectively constants and can be optimized as such by the compiler. Constant static members make up for the lack of a #define construct in Java. However, static variables don't, in general, have to be constant. I'll say more about static class members in Chapter 5, Objects in Java. The alternative to using these predefined colors is to create a color manually by specifying its red, green, blue (RGB) components using a Color class constructor.
Arrays Next, we turn our attention to the array. We have declared a variable called someColors, which is an array of Color objects. Arrays are syntactically supported by the Java language; however, they are true, first-class objects. This means that an array is, itself, a type of object that knows how to hold an indexed list of some other type of object. An array is indexed by integers; when you index an array, the resulting value is the object in the corresponding slot in the array. Our code uses the colorIndex variable to index someColors. It's also possible to have an array of simple primitive types, rather than objects. When we declare an array, we can initialize it by using the familiar C-like curly brace construct. Specifying a comma-separated list of elements inside of curly braces is a convenience that instructs the compiler to create an instance of the array with those elements and assign it to our variable. Alternatively, we could have just declared our someColors variable and, later, allocated an array object for it and assigned individual elements to that array's slots. See Chapter 4, The Java Language for a complete discussion of arrays.
Our Color Methods So, we now have an array of Color objects and a variable with which to index them. What do we do with them? Well, we have declared two private methods that do the actual work for us. The private modifier on these methods specifies that they can be called only by other methods in the same instance of the class. They are not visible outside of the object. We declare members to be private to hide the detailed inner workings of a class from the outside world. This is called encapsulation and is another tenet of object-oriented design, as well as good programming practice. Private methods are also often created as helper functions for use solely within the class implementation. http://localhost/java/javaref/exp/ch02_03.htm (8 of 10) [20/12/2001 11:02:02]
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
The first method, currentColor(), is simply a convenience routine that returns the Color object representing the current text color. It returns the Color object in the someColors array at the index specified by our colorIndex variable: synchronized private Color currentColor() { return someColors[ colorIndex ]; } We could just as readily have used the expression someColors[colorIndex] everywhere we use currentColor(); however, creating methods to wrap common tasks is another way of shielding ourselves from the details of our class. In an alternative implementation, we might have shuffled off details of all color-related code into a separate class. We could have created a class that takes an array of colors in its constructor and then provided two methods: one to ask for the current color and one to cycle to the next color (just some food for thought). The second method, changeColor(), is responsible for incrementing the colorIndex variable to point to the next Color in the array. changeColor() is called from our action() method whenever the button is pressed. synchronized private void changeColor() { if ( ++colorIndex == someColors.length ) colorIndex = 0; setForeground( currentColor() ); repaint(); } We increment colorIndex and compare it to the length of the someColors array. All array objects have a variable called length that specifies the number of elements in the array. If we have reached the end of the array, we reset our index to zero and start over. After changing the currently selected color, we do two things. First, we call the applet's setForeground() method, which changes the color used to draw text in the applet and the color of the button's label. Then we call repaint() to cause the applet to be redrawn with the new color for the draggable message. So, what is the synchronized keyword that appears in front of our currentColor() and changeColor() methods? Synchronization has to do with threads, which we'll examine in the next section. For now, all you need know is that the synchronized keyword indicates these two methods can never be running at the same time. They must always run one after the other. The reason is that in changeColor() we increment colorIndex before testing its value. That means that for some brief period of time while Java is running through our code, colorIndex can have a value that is past the end of our array. If our currentColor() method happened to run at that same moment, we would see a run-time "array out of bounds" error. There are, of course, ways in which we could fudge around the problem in this case, but this simple example is representative of more general synchronization issues we need to address. In the next section, you'll see that Java makes dealing with these problems easy through language-level synchronization support.
http://localhost/java/javaref/exp/ch02_03.htm (9 of 10) [20/12/2001 11:02:02]
[Chapter 2] 2.3 Hello Web! III: The Button Strikes!
Hello Web! II: The Sequel
http://localhost/java/javaref/exp/ch02_03.htm (10 of 10) [20/12/2001 11:02:02]
Hello Web! IV: Netscape's Revenge
[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge
Chapter 2 A First Applet
2.4 Hello Web! IV: Netscape's Revenge We have explored quite a few features of Java with the first three versions of the HelloWeb applet. But until now, our applet has been rather passive; it has waited patiently for events to come its way and responded to the whims of the user. Now our applet is going to take some initiative--HelloWeb4 will blink! The code for our latest version is shown below. import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class HelloWeb4 extends Applet implements MouseMotionListener, ActionListener, Runnable { int messageX = 125, messageY = 95; String theMessage; Button theButton; int colorIndex = 0; static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; Thread blinkThread; boolean blinkState; public void init() { theMessage = getParameter("message"); theButton = new Button("Change Color"); add(theButton); addMouseMotionListener(this); theButton.addActionListener(this); } public void paint( Graphics graphics ) { graphics.setColor( blinkState ? Color.white : currentColor() ); graphics.drawString( theMessage, messageX, messageY ); } public void mouseDragged( MouseEvent e ) { messageX = e.getX(); messageY = e.getY(); repaint(); http://localhost/java/javaref/exp/ch02_04.htm (1 of 8) [20/12/2001 11:02:04]
[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge
} public void mouseMoved( MouseEvent e ) { } public void actionPerformed( ActionEvent e ) { if ( e.getSource() == theButton ) { changeColor(); } } synchronized private void changeColor() { if ( ++colorIndex == someColors.length ) colorIndex = 0; theButton.setForeground( currentColor() ); repaint(); } synchronized private Color currentColor() { return someColors[ colorIndex ]; } public void run() { while ( true ) { blinkState = !blinkState; repaint(); try { Thread.sleep(500); } catch (Exception e ) { // Handle error condition here... } } } public void start() { if ( blinkThread == null ) { blinkThread = new Thread(this); blinkThread.start(); } } public void stop() { if ( blinkThread != null ) { blinkThread.stop(); blinkThread = null; } } } If you create HelloWeb4 as you have the other applets and then run it in a Java-enabled Web browser, you'll see that the text does in fact blink. My apologies if you don't like blinking text--I'm not overly fond of it either--but it does make for a simple, instructive example.
http://localhost/java/javaref/exp/ch02_04.htm (2 of 8) [20/12/2001 11:02:04]
[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge
Threads All the changes we've made in HelloWeb4 have to do with setting up a separate thread of execution to make the text of our applet blink. Java is a multithreaded language, which means there can be many threads running at the same time. A thread is a separate flow of control within a program. Conceptually, threads are similar to processes, except that unlike processes, multiple threads share the same address space, which means that they can share variables and methods (but they have their own local variables). Threads are also quite lightweight in comparison to processes, so it's conceivable for a single application to be running hundreds of threads concurrently. Multithreading provides a way for an application to handle many different tasks at the same time. It's easy to imagine multiple things going on at the same time in an application like a Web browser. The user could be listening to an audio clip while scrolling an image, and in the background the browser is downloading an image. Multithreading is especially useful in GUI-based applications, as it can improve the interactive performance of these applications. Unfortunately for us, programming with multiple threads can be quite a headache. The difficulty lies in making sure routines are implemented so they can be run by multiple concurrent threads. If a routine changes the value of a state variable, for example, then only one thread can be executing the routine at a time. Later in this section, we'll examine briefly the issue of coordinating multiple thread's access to shared data. In other languages, synchronization of threads can be an extremely complex and error-prone endeavor. You'll see that Java gives you a few simple tools that help you deal with many of these problems. Java threads can be started, stopped, suspended, and prioritized. Threads are preemptive, so a higher priority thread can interrupt a lower priority thread when vying for processor time. See Chapter 6, Threads for a complete discussion of threads. The Java run-time system creates and manages a number of threads. I've already mentioned the AWT thread, which manages repaint() requests and event processing for GUI components that belong to the java.awt package. A Java-enabled Web browser typically has at least one separate thread of execution it uses to manage the applets it displays. Until now, our example has done most of its work from methods of the Applet class, which means that is has been borrowing time from these threads. Methods like mouseDragged() and actionPerformed() are invoked by the AWT thread and run on its time. Similarly, our init() method is called by a thread in the Web browser. This means we are somewhat limited in the amount of processing we do within these methods. If we were, for instance, to go into an endless loop in our init() method, our applet would never appear, as it would never finish initializing. If we want an applet to perform any extensive processing, such as animation, a lengthy calculation, or communication, we should create separate threads for these tasks.
The Thread Class As you might have guessed, threads are created and controlled as Thread objects. We have added a new instance variable, blinkThread, to our example to hold the Thread that handles our blinking activity: Thread blinkThread; An instance of the Thread class corresponds to a single thread. It contains methods to start, control, and stop the thread's execution. Our basic plan is to create a Thread object to handle our blinking code. We call the Thread's start() method to begin execution. Once the thread starts, it continues to run until we call
http://localhost/java/javaref/exp/ch02_04.htm (3 of 8) [20/12/2001 11:02:04]
[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge
the Thread's stop() method to terminate it. But Java doesn't allow pointers to methods, so how do we tell the thread which method to run? Well, the Thread object is rather picky; it always expects to execute a method called run() to perform the action of the thread. The run() method can, however, with a little persuasion, be located in any class we desire. We specify the location of the run() method in one of two ways. First, the Thread class itself has a method called run(). One way to execute some Java code in a separate thread is to subclass Thread and override its run() method to do our bidding. In this case, we simply create an instance of this subclass and call its start() method. But it's not always desirable or possible to create a subclass of Thread to contain our run() method. In this case, we need to tell the Thread which object contains the run() method it should execute. The Thread class has a constructor that takes an object reference as its argument. If we create a Thread object using this constructor and call its start() method, the Thread executes the run() method of the target object, rather than its own. In order to accomplish this, Java needs to have a guarantee that the object we are passing it does indeed contain a compatible run() method. We already know how to make such a guarantee: we use an interface. Java provides an interface named Runnable that must be implemented by any class that wants to become a Thread.
The Runnable Interface The second technique I described for creating a Thread object involved passing an object that implements the Runnable interface to the Thread constructor. The Runnable interface specifies that the object contains a run() method that takes no arguments and returns no value. This method is called automatically when the system needs to start the thread. Sticking with our technique for implementing our applet in a single class, we have opted to add the run() method for blinkThread to our HelloWeb4 class. This means that HelloWeb4 needs to implement the Runnable interface. We indicate that the class implements the interface in our class declaration: public class HelloWeb4 extends Applet implements MouseMotionListener, ActionListener, Runnable {...} At compile time, the Java compiler checks to make sure we abide by this statement. We have carried through by adding an appropriate run() method to our applet. Our run() method has the task of changing the color of our text a couple of times a second. It's a very short routine, but I'm going to delay looking at it until we tie up some loose ends in dealing with the Thread itself.
start( ) and stop( ) Now that we know how to create a Thread to execute our applet's run() method, we need to figure out where to actually do it. The start() and stop() methods of the Applet class are similar to init(). The start() method is called when an applet is first displayed. If the user then leaves the Web document or scrolls the applet off the screen, the stop() method is invoked. If the user subsequently returns, the start() method is called again, and so on. Unlike init(), start() and stop() can be called repeatedly during the lifetime of an applet. The start() and stop() methods of the Applet class have absolutely nothing to do with the Thread http://localhost/java/javaref/exp/ch02_04.htm (4 of 8) [20/12/2001 11:02:04]
[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge
object, except that they are a good place for an applet to start and stop a thread. An applet is responsible for managing the threads that it creates. It would be considered rude for an applet to continue such tasks as animation, making noise, or performing extensive calculations long after it's no longer visible on the screen. It's common practice, therefore, to start a thread when an applet becomes visible and stop it when the applet is no longer visible. Here's the start() method from HelloWeb4: public void start() { if ( blinkThread == null ) { blinkThread = new Thread(this); blinkThread.start(); } } The method first checks to see if there is an object assigned to blinkThread; recall that an uninitialized instance variable has a default value of null. If not, the method creates a new instance of Thread, passing the target object that contains the run() method to the constructor. Since HelloWeb4 contains our run() method, we pass the special variable this to the constructor to let the thread know where to find the run() method it should run. this always refers to our object. Finally, after creating the new Thread, we call its start() method to begin execution. Our stop() method takes the complimentary position: public void stop() { if ( blinkThread != null ) { blinkThread.stop(); blinkThread = null; } } This method checks to see if blinkThread is empty. If not, it calls the thread's stop() method to terminate its execution. By setting the value of blinkThread back to null, we have eliminated all references to the thread object we created in the start() method, so the garbage collector can dispose of the object.
run( ) Our run() method does its job by setting the value of the variable blinkState. We have added blinkState, a boolean value, to represent whether we are currently blinking on or off: boolean blinkState; The setColor() line of our paint() method has been modified slightly to handle blinking. The call to setColor() now draws the text in white when blinkState is true: gc.setColor( blinkState ? Color.white : currentColor() );
http://localhost/java/javaref/exp/ch02_04.htm (5 of 8) [20/12/2001 11:02:04]
[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge
Here we are being somewhat terse and using the C-like ternary operator to return one of two alternate color values based on the value of blinkState. Finally, we come to the run() method itself: public void run() { while ( true ) { blinkState = !blinkState; repaint(); try { Thread.sleep(500); } catch (InterruptedException e ) { } } } At its outermost level, run() uses an infinite while loop. This means the method will run continuously until the thread is terminated by a call to the controlling Thread object's stop() method. The body of the loop does three things on each pass: ● Flips the value of blinkState to its opposite value using the not operator, !. ● Calls repaint() so that our paint() method can have an opportunity to redraw the text in accordance with blinkState. ● Uses a try/catch statement to trap for an error in our call to the sleep() method of the Thread class. sleep() is a static method of the Thread class. The method can be invoked from anywhere and has the effect of putting the current thread to sleep for the specified number of milliseconds. The effect here is to give us approximately two blinks per second.
Exceptions The try/catch statement in Java is used to handle special conditions called exceptions. An exception is a message that is sent, normally in response to an error, during the execution of a statement or a method. When an exceptional condition arises, an object is created that contains information about the particular problem or condition. Exceptions act somewhat like events. Java stops execution at the place where the exception occurred, and the exception object is said to be thrown by that section of code. Like events, an exception must be delivered somewhere and handled. The section of code that receives the exception object is said to catch the exception. An exception causes the execution of the instigating section of code to abruptly stop and transfers control to the code that receives the exception object. The try/catch construct allows you to catch exceptions for a section of code. If an exception is caused by a statement inside of a try clause, Java attempts to deliver the exception to the appropriate catch clause. A catch clause looks like a method declaration with one argument and no return type. If Java finds a catch clause with an argument type that matches the type of the exception, that catch clause is invoked. A try clause can have multiple catch clauses with different argument types; Java chooses the appropriate one in a way that is analogous to the selection of overloaded methods. If there is no try/catch clause surrounding the code, or a matching catch clause is not found, the http://localhost/java/javaref/exp/ch02_04.htm (6 of 8) [20/12/2001 11:02:04]
[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge
exception is thrown up the call stack to the calling method. If the exception is not caught there, it's thrown up another level, and so on until the exception is handled. This provides a very flexible error-handling mechanism, so that exceptions in deeply nested calls can bubble up to the surface of the call stack for handling. As a programmer, you need to know what exceptions a particular statement can generate, so methods in Java are required to declare the exceptions they can throw. If a method doesn't handle an exception itself, it must specify that it can throw that exception, so that the calling method knows that it may have to handle it. See Chapter 4, The Java Language for a complete discussion of exceptions and the try/catch clause. So, why do we need a try/catch clause around our sleep() call? What kind of exception can Thread's sleep() method throw and why do we care about it, when we don't seem to check for exceptions anywhere else? Under some circumstances, Thread's sleep() method can throw an InterruptedException, indicating that it was interrupted by another thread. Since the run() method specified in the Runnable interface doesn't declare it can throw an InterruptedException, we must catch it ourselves, or the compiler will complain. The try/catch statement in our example has an empty catch clause, which means that it handles the exception by ignoring it. In this case, our thread's functionality is so simple it doesn't matter if it's interrupted. All of the other methods we have used either handle their own exceptions or throw only general-purpose exceptions that are assumed to be possible everywhere and don't need to be explicitly declared.
A Word About Synchronization At any given time, there can be a number of threads running in the Java interpreter. Unless we explicitly coordinate them, these threads will be executing methods without any regard for what the other threads are doing. Problems can arise when these methods share the same data. If one method is changing the value of some variables at the same time that another method is reading these variables, it's possible that the reading thread might catch things in the middle and get some variables with old values and some with new. Depending on the application, this situation could cause a critical error. In our HelloWeb examples, both our paint() and mouseDrag() methods access the messageX and messageY variables. Without knowing the implementation of our particular Java environment, we have to assume that these methods could conceivably be called by different threads and run concurrently. paint() could be called while mouseDrag() is in the midst of updating messageX and messageY. At that point, the data is in an inconsistent state and if paint() gets lucky, it could get the new x value with the old y value. Fortunately, in this case, we probably would not even notice if this were to happen in our application. We did, however, see another case, in our changeColor() and currentColor() methods, where there is the potential for a more serious "out of bounds" error to occur. The synchronized modifier tells Java to acquire a lock for the class that contains the method before executing that method. Only one method can have the lock on a class at any given time, which means that only one synchronized method in that class can be running at a time. This allows a method to alter data and leave it in a consistent state before a concurrently running method is allowed to access it. When the method is done, it releases the lock on the class. Unlike synchronization in other languages, the synchronized keyword in Java provides locking at the language level. This means there is no way that you can forget to unlock a class. Even if the method throws an exception or the thread is terminated, Java will release the lock. This feature makes programming with threads in Java much easier than in other languages. See Chapter 6, Threads for more details on coordinating
http://localhost/java/javaref/exp/ch02_04.htm (7 of 8) [20/12/2001 11:02:04]
[Chapter 2] 2.4 Hello Web! IV: Netscape's Revenge
threads and shared data. Whew! Now it's time to say goodbye to HelloWeb. I hope that you have developed a feel for the major features of the Java language, and that this will help you as you go on to explore the details of programming with Java.
Hello Web! III: The Button Strikes!
http://localhost/java/javaref/exp/ch02_04.htm (8 of 8) [20/12/2001 11:02:04]
Tools of the Trade
[Chapter 3] 3.2 The Class Path
Chapter 3 Tools of the Trade
3.2 The Class Path The concept of a path should be familiar to anyone who has worked on a DOS or UNIX platform. It's a piece of environment information that provides an application with a list of places to look for some resource. The most common example is a path for executable programs. In a UNIX shell, the PATH environment variable is a colon-separated list of directories that are searched, in order, when the user types the name of a command. The Java CLASSPATH environment variable, similarly, is a list of locations that can be searched for packages containing Java class files. Both the Java interpreter and the Java compiler use CLASSPATH when searching for files on the local host platform. Classes loaded from the local host via the class path have special features. For example, the Java interpreter loads classes in the class path just once; after a core class has been loaded, it can't be modified or replaced. The interpreter can also be told to trust classes in the class path and to load them without passing them through the byte-code verification process. This is important because certain kinds of optimizations on Java virtual machine instructions produce valid byte-code that, nonetheless, can't pass the verification process. Byte-code that is precompiled on the native host is an extreme example. The class path is a list of locations where Java class packages are found. A location can be a path such as a directory name or the name of a class archive file. Java supports archives of class files in the uncompressed ZIP format.[1] It automatically looks inside ZIP archives and retrieves classes, which then allows large groups of classes to be distributed in a single archive file. The precise means and format for setting the class path varies from system to system. On a UNIX system, you set the CLASSPATH environment variable with a colon-separated list of directories and class archive files: [1] The ZIP format is an open standard for file archiving and compression. There are ZIP utilities available for most platforms; you'll need to get one if you want to store Java classes in ZIP archives. Use ftp://ftp.uu.net/pub/archiving/zip/ to access an archive of freely available ZIP utilities. CLASSPATH=/usr/lib/java/classes.zip:/home/vicky/Java/classes:\ /home/vicky/.netscape/moz2_0.zip:. On a Windows system, the CLASSPATH environment variable is set with a semicolon-separated list of directories and class archive files:
http://localhost/java/javaref/exp/ch03_02.htm (1 of 2) [20/12/2001 11:02:04]
[Chapter 3] 3.2 The Class Path
CLASSPATH=C:\tools\java\classes.zip;D:\users\vicky\Java\classes;. The class path can also be set with the -classpath option to the Java interpreter java and the Java compiler javac. The above UNIX example specifies a class path with four locations: a ZIP archive in /usr/lib/java, a directory in the user's home, another ZIP file in the user's Netscape collection, and the current directory, which is always specified with a dot (.). The last component of the class path, the current directory, is useful when tinkering with classes, but as a general rule, it's bad practice to put the current directory in any kind of path. The Java interpreter searches each of these four locations in order to find classes. java expects to find class files in a directory hierarchy or in a directory within a ZIP archive that maps to the fully qualified name of the class. The components of a class-package name become the components of a pathname. Given the above class path, the first time we reference a class with the fully qualified name of animals.birds.BigBird, for example, java begins the search with the classes.zip archive in /usr/lib/java. It looks for a class archived under the path animals/birds/BigBird. If java does not find the class there, it looks for the class in /home/vicky/Java/classes/animals/birds/BigBird. If it's not found there, java moves on to the archive file specified next in the class path, and so on. If you don't specify the CLASSPATH environment variable or the -classpath option, java uses the following default class path: .:$JAVA/classes:$JAVA/lib/classes.zip .;$JAVA\classes;$JAVA\lib\classes.zip
UNIX systems Windows systems
In this path, $JAVA is the main Java directory on your system. Notice that the current directory (.) is the first location in the default class path; this means the files in your current directory are always available. If you change the class path and don't include the current directory, these files will no longer be accessible.
The Java Interpreter
http://localhost/java/javaref/exp/ch03_02.htm (2 of 2) [20/12/2001 11:02:04]
The Java Compiler
[Chapter 3] 3.3 The Java Compiler
Chapter 3 Tools of the Trade
3.3 The Java Compiler In this section, I'm going to say a few words about javac, the Java compiler that is supplied as part of Sun's JDK. (If you are happily working in another development environment, you may want to skip ahead to the next section.) The javac compiler is written entirely in Java, so it's available for any platform that supports the Java run-time system. The ability to support its own development environments is an important stage in a language's development. Java makes this bootstrapping automatic by supplying a ready-to-run compiler at the same cost as porting the interpreter. javac turns Java source code into a compiled class that contains Java virtual machine byte-code. By convention, source files are named with a .java extension; the resulting class files have a .class extension. javac considers a file to be a single compilation unit. As you'll see in Chapter 5, Objects in Java, classes in a given compilation unit share certain features like package and import statements. javac allows you one public class per file and insists the file have the same name as the class. If the filename and class name don't match, javac issues a compilation error. A single file can contain multiple classes, as long as only one of the classes is public. You should avoid packing lots of classes into a single file. The compiler lets you include extra non-public classes in a .java file, so that you can implement a class that is tightly coupled to another class without a lot of hassle. But you should have more than one class in a file if the public class in the file is the only one that ever uses additional classes. Now for an example. The source code for the following class should be placed in a file called BigBird.java: package animals.birds public class BigBird extends Bird { ... } We can then compile it with: % javac BigBird.java Unlike the Java interpreter, which takes a class name as its argument, javac requires an actual filename to http://localhost/java/javaref/exp/ch03_03.htm (1 of 2) [20/12/2001 11:02:05]
[Chapter 3] 3.3 The Java Compiler
process. The above command produces the class file BigBird.class and stores it in the same directory as the source file. While it's useful to have the class file in the same directory as the source when you are working on a simple example, for most real applications you'll need to store the class file in an appropriate place in the class path. You can use the -d option to javac to specify an alternate directory for storing the class files it generates. The specified directory is used as the root of the class hierarchy, so .class files are placed in this directory or in a subdirectory below it, depending on the package name of the class. For example, we can use the following command to put our BigBird.class file in an appropriate location: % javac -d /home/vicky/Java/classes BigBird.java When you use the -d option, javac automatically creates any directories needed to store the class file in the appropriate place. In the above command, the BigBird.class file is stored in /home/vicky/Java/classes/animals/birds. You can specify multiple .java files in a single javac command; the compiler simply creates a class file for each source file. But you don't need to list source files for other classes your class references, as long as the other classes have already been compiled. During compilation, Java resolves other class references using the class path. If our class references other classes in animals.birds or other packages, the appropriate paths should be listed in the class path at compile time, so that javac can find the appropriate class files. You either make sure that the CLASSPATH environment variable is set or use the -classpath option to javac. The Java compiler is more intelligent than your average compiler and replaces some of the functionality of a make utility. For example, javac compares the modification times of the source and class files for all referenced classes and recompiles them as necessary. A compiled Java class remembers the source file from which it was compiled, so as long as the source file is in the same directory as the class file, javac can recompile the source if necessary. If, in the above example, class BigBird references another class, animals.furry.Grover, javac looks for the source Grover.java in an animals.furry package and recompiles it if necessary to bring the Grover.class class file up to date. It's important to note that javac can do its job even if only the compiled versions of referenced classes are available. Java class files contain all the data type and method signature information source files do, so compiling against binary class files is as type safe (and exception safe) as compiling with Java source code.
The Class Path
http://localhost/java/javaref/exp/ch03_03.htm (2 of 2) [20/12/2001 11:02:05]
The Netscape Alternative
[Chapter 3] 3.4 The Netscape Alternative
Chapter 3 Tools of the Trade
3.4 The Netscape Alternative If the JDK is not available for your platform, but you have access to a Java-enabled version of Netscape Navigator, you can take advantage of a special Netscape switch to compile and run Java applications. The -java switch provides direct access to Netscape's implementation of the Java run-time system and supports the same command-line options as Sun's java interpreter. Here's the general syntax for using the -java switch: % netscape -java [interpreter options] class name [program arguments] Before you can use Netscape's -java switch, you have to download the JDK; you need the classes.zip file that is part of the JDK distribution. After you have unpacked the distribution, set the CLASSPATH environment variable to point to both Netscape's class archive and the classes.zip file from the JDK: CLASSPATH=/usr/lib/java/classes.zip:/home/vicky/.netscape/moz2_0.zip:. Now you can compile a .java file using Netscape's -java switch as follows: % netscape -java sun.tools.javac.Main source file In this case, you are actually using the -java switch to run the Java compiler, javac, and supplying the source file as an argument to the compiler. Recall that javac is itself a Java program, which is why you can run it using the -java switch. The above command produces a class file and stores it in the same directory as the source file. After you have compiled a Java application with Netscape, you can use Netscape to run it. You can use the -java switch to run nongraphical Java applications. In other words, you can run any application that doesn't use AWT. You can't use the -java switch to run applications that use AWT because Netscape has its own toolkit that employs Netscape native components. However, you can use the -java switch to compile applets (and applications) that use AWT. As always, you can display these applets using Netscape as a Web browser.
The Java Compiler
http://localhost/java/javaref/exp/ch03_04.htm (1 of 2) [20/12/2001 11:02:06]
The Applet Tag
[Chapter 3] 3.4 The Netscape Alternative
http://localhost/java/javaref/exp/ch03_04.htm (2 of 2) [20/12/2001 11:02:06]
[Chapter 3] 3.5 The Applet Tag
Chapter 3 Tools of the Trade
3.5 The Applet Tag Add stuff about 'archive' tag. Applets are embedded in HTML documents with the tag. The tag resembles the HTML image tag.[2] It contains attributes that identify the applet to be displayed and, optionally, give the Web browser hints about how it should be displayed. The standard image tag sizing and alignment attributes, such as height and width, can be used inside the applet tag. Unlike images, however, applets have both an opening and a closing tag. Sandwiched between these can be any number of <param> tags that contain application-specific parameters to be passed to the applet itself: [2] If you are not familiar with HTML or other markup languages, you may want to refer to HTML: The Definitive Guide, from O'Reilly & Associates, for a complete reference on HTML and structured Web documents. ] [<param parameter >] ...
>
Attributes Attributes are name/value pairs that are interpreted by a Web browser or applet viewer. (Many HTML tags besides have attributes.) Attributes of the tag specify general features that apply to all applets, such as size and alignment. The definition of the tag lists a fixed set of recognized attributes; specifying an incorrect or nonexistent attribute should be considered an HTML error. Three attributes, code, width, and height, are always required in the tag. code specifies the name of the applet to be loaded; width and height determine its initial size. Other attributes are optional. The following is an HTML fragment for a hypothetical, simple clock applet that takes no parameters and requires no special HTML layout:
http://localhost/java/javaref/exp/ch03_05.htm (1 of 6) [20/12/2001 11:02:07]
[Chapter 3] 3.5 The Applet Tag
The HTML file that contains this tag needs to be stored in the same directory as the AnalogClock.class class file. The applet tag is not sensitive to spacing, so the above is therefore equivalent to: You can use whatever form seems appropriate.
Parameters Parameters are analogous to command-line arguments; they provide a way to pass information to an applet. Each <param> tag contains a name and a value that are passed as strings to the applet: <param name = parameter_name value = parameter_value> Parameters provide a means of embedding application-specific data and configuration information within an HTML document.[3] Our AnalogClock applet, for example, might accept a parameter that selects between local and universal time: [3] If you are wondering why the applet's parameters are specified in yet another type of tag, here's the reason. In the original alpha release of Java, applet parameters were included inside of a single tag along with formatting attributes. However, this format was not SGML-compliant, so the <param> tag was added. <param name=zone value=GMT> Presumably, this AnalogClock applet is designed to look for a parameter named zone with a possible value of GMT. Parameter names and values can be quoted to contain spaces and other special characters. We could therefore be more verbose and use a parameter value like the following: <param name=zone value="Greenwich Mean Time"> The parameters a given applet expects are determined by the developer of that applet. There is no fixed set of parameter names or values; it's up to the applet to interpret the parameter name/value pairs that are passed to it. Any number of parameters can be specified, and the applet may choose to use or ignore them as it sees fit. The applet might also consider parameters to be either optional or required and act accordingly.
http://localhost/java/javaref/exp/ch03_05.htm (2 of 6) [20/12/2001 11:02:07]
[Chapter 3] 3.5 The Applet Tag
Hablo Applet? Web browsers ignore tags they don't understand; if the Web browser doesn't interpret the or <param> tags, they should disappear and any HTML between the and tags should appear normally. By convention, Java-enabled Web browsers do the opposite and ignore any extra HTML between the and tags. This means we can place some alternate HTML inside the tag, which is then displayed only by Web browsers that can't run the applet. For our AnalogClock example, we could display a small text explanation and an image of the clock applet as a teaser: <param name=zone value=GMT> <strong>If you see this you don't have a Java-enabled Web browser. Here's a picture of what you are missing.
The Complete Applet Tag We can now spell out the full-blown tag:[4] [4] The HTML working group of the IETF is investigating standardization of embedded objects in HTML. A draft document can be found at ftp://ds.internic.net/internet-drafts/draft-ietf-html-cda-00.txt. They would prefer a slightly less application-centric name such as <embed>. However, their discussion, for the most part, parallels the tag. [ <param name = parameter name value = parameter value> ] [ <param name = parameter name value = parameter value> ] ... [ HTML for non Java aware browsers ]
http://localhost/java/javaref/exp/ch03_05.htm (3 of 6) [20/12/2001 11:02:07]
[Chapter 3] 3.5 The Applet Tag
The width, height, align, vspace, and hspace attributes have the same meanings as those of the tag and determine the preferred size, alignment, and padding respectively. The alt attribute specifies alternate text that is displayed by browsers that understand the tag and its attributes, but can't actually run applets. This attribute can also describe the applet, since in this case any alternate HTML between and is ignored. The name attribute specifies an instance name for the executing applet. This is a name specified as a unique label for each copy of an applet on a particular HTML page. For example, if we include our clock twice on the same page (using two applet tags), we could give each instance a unique name to differentiate them: Applets use instance names to recognize and communicate with other applets on the same page. We could, for instance, create a "clock setter" applet that knows how to set the time on a AnalogClock applet and pass it the instance name of a particular target clock on this page as a parameter. This might look something like: <param name=clockToSet value="bigClock">
Loading Class Files The code attribute of the tag should specify the name of an applet. This is either a simple class name, or a package path and class name. For now, let's look at simple class names; I'll discuss packages in a moment. By default, the Java run-time system looks for the class file in the same location as the HTML document that contains it. This location is known as the base URL for the document. Consider an HTML document, clock.html, that contains our clock applet example: Let's say we retrieve the document at the following URL: http://www.time.ch/documents/clock.html Java tries to retrieve the applet class file from the same base location: http://www.time.ch/documents/AnalogClock.class The codebase attribute of the tag can be used to specify an alternative base URL for the class file search. Let's say our HTML document now specifies codebase, as in the following example: Java now looks for the applet class file at: http://www.joes.ch/stuff/AnalogClock.class
Packages Packages are groups of Java classes; see Chapter 5, Objects in Java for more information. A package name is a little like an Internet hostname, in that they both use a hierarchical, dot-separated naming convention. A Java class file can be identified by its full name by prefixing the class name with the package name. We might therefore have a package called time for time-related Java classes, and perhaps a subordinate package called time.clock to hold classes related to one or more clock applications. In addition to providing a naming scheme, packages can be used to locate classes stored at a particular location. Before a class file is retrieved from a server, its package-name component is translated by the client into a relative path name under the base URL of the document. The components of a class package name are simply turned into the components of a path name, just like with classes on your local system. Let's suppose that our AnalogClock has been placed into the time.clock package and now has the fully qualified name of time.clock.AnalogClock. Our simple tag would now look like: Let's say the clock.html document is once again retrieved from: http://www.time.ch/documents/clock.html Java now looks for the class file in the following location: http://www.time.ch/documents/time/clock/AnalogClock.class The same is true when specifying an alternative codebase: Java now tries to find the class in the corresponding path under the new base URL: http://www.joes.ch/stuff/time/clock/AnalogClock.class
http://localhost/java/javaref/exp/ch03_05.htm (5 of 6) [20/12/2001 11:02:07]
[Chapter 3] 3.5 The Applet Tag
One possible package-naming convention proposes that Internet host and domain names be incorporated as part of package names to form a unique identifier for classes produced by a given organization. If a company with the domain name foobar.com produced our AnalogClock class, they might distribute it in a package called com.foobar.time.clock. The fully qualified name of the AnalogClock class would then be com.foo.time.clock.AnalogClock. This would presumably be a unique name stored on an arbitrary server. A future version of the Java class loader might use this to automatically search for classes on remote hosts. Perhaps soon we'll run Sun's latest and greatest Web browser directly from its source with: % java com.sun.java.hotjava.HotJava
Viewing Applets Sun's JDK comes with an applet-viewer program aptly called appletviewer. To use appletviewer, specify the URL of the document on the command line. For example, to view our AnalogClock at the URL shown above, use the following command: % appletviewer http://www.time.ch/documents/clock.html The appletviewer retrieves all applets in the specified document and displays each one in a separate window. appletviewer is not a Web browser; it doesn't attempt to display HTML. It's primarily a convenience for testing and debugging applets. If the document doesn't contain tags, appletviewer does nothing.
The Netscape Alternative
http://localhost/java/javaref/exp/ch03_05.htm (6 of 6) [20/12/2001 11:02:07]
The Java Language
[Chapter 4] 4.2 Comments
Chapter 4 The Java Language
4.2 Comments Java supports both C-style block comments delimited by /* and */ and C++-style line comments indicated by //: /*
This is a multiline comment.
*/
// This is a single line comment // and so // is this As in C, block comments can't be nested. Single-line comments are delimited by the end of a line; extra // indicators inside a single line have no effect. Line comments are useful for short comments within methods because you can still wrap block comments around large chunks of code during development. By convention, a block comment beginning with /** indicates a special "doc comment." A doc comment is commentary that is extracted by automated documentation generators, such as Sun's javadoc program that comes with the Java Development Kit. A doc comment is terminated by the next */, just as with a regular block comment. Leading spacing up to a * on each line is ignored; lines beginning with @ are interpreted as special tags for the documentation generator: /** * I think this class is possibly the most amazing thing you will * ever see. Let me tell you about my own personal vision and * motivation in creating it. *
* It all began when I was a small child, growing up on the * streets of Idaho. Potatoes were the rage, and life was good... * * @see PotatoPeeler * @see PotatoMasher * @author John 'Spuds' Smith * @version 1.00, 19 Dec 1996 */ http://localhost/java/javaref/exp/ch04_02.htm (1 of 2) [20/12/2001 11:02:08]
[Chapter 4] 4.2 Comments
javadoc creates HTML class documentation by reading the source code and the embedded comments. The author and version information is presented in the output and the @see tags make hypertext links to the appropriate class documentation. The compiler also looks at the doc comments; in particular, it is interested in the @deprecated tag, which means that the method has been declared obsolete and should be avoided in new programs. The compiler generates a warning message whenever it sees you use a deprecated feature in your code. Doc comments can appear above class, method, and variable definitions, but some tags may not be applicable to all. For example, a variable declaration can contain only a @see tag. Table 4.1 summarizes the tags used in doc comments. Table 4.1: Doc Comment Tags Tag @see @author
Description Associated class name Author name
Applies to Class, method, or variable Class
@version @param @return @exception @deprecated
Version string Parameter name and description Description of return value Exception name and description Declares an item obsolete
Class Method Method Method Class, method, or variable
Text Encoding
http://localhost/java/javaref/exp/ch04_02.htm (2 of 2) [20/12/2001 11:02:08]
Types
[Chapter 4] 4.3 Types
Chapter 4 The Java Language
4.3 Types The type system of a programming language describes how its data elements (variables and constants) are associated with actual storage. In a statically typed language, such as C or C++, the type of a data element is a simple, unchanging attribute that often corresponds directly to some underlying hardware phenomenon, like a register value or a pointer indirection. In a more dynamic language like Smalltalk or Lisp, variables can be assigned arbitrary elements and can effectively change their type throughout their lifetime. A considerable amount of overhead goes into validating what happens in these languages at run-time. Scripting languages like Tcl and awk achieve ease of use by providing drastically simplified type systems in which only certain data elements can be stored in variables, and values are unified into a common representation such as strings. As I described in Chapter 1, Yet Another Language?, Java combines the best features of both statically and dynamically typed languages. As in a statically typed language, every variable and programming element in Java has a type that is known at compile-time, so the interpreter doesn't normally have to check the type validity of assignments while the code is executing. Unlike C or C++ though, Java also maintains run-time information about objects and uses this to allow safe run-time polymorphism. Java data types fall into two categories. Primitive types represent simple values that have built-in functionality in the language; they are fixed elements like literal constants and numeric expressions. Reference types (or class types) include objects and arrays; they are called reference types because they are passed "by reference" as I'll explain shortly.
Primitive Types Numbers, characters, and boolean values are fundamental elements in Java. Unlike some other (perhaps more pure) object-oriented languages, they are not objects. For those situations where it's desirable to treat a primitive value as an object, Java provides "wrapper" classes (see Chapter 7, Basic Utility Classes). One major advantage of treating primitive values as such is that the Java compiler can more readily optimize their usage. Another advantage of working with the Java virtual-machine architecture is that primitive types are precisely defined. For example, you never have to worry about the size of an int on a particular platform; it's always a 32-bit, signed, two's complement number. Table 4.2 summarizes Java's primitive types. Table 4.2: Java Primitive Data Types
http://localhost/java/javaref/exp/ch04_03.htm (1 of 6) [20/12/2001 11:02:08]
[Chapter 4] 4.3 Types
Type
Definition
boolean true or false 16-bit Unicode character char 8-bit signed two's complement integer byte short
16-bit signed two's complement integer
int long
32-bit signed two's complement integer
float
64-bit signed two's complement integer 32-bit IEEE 754 floating-point value
double 64-bit IEEE 754 floating-point value If you think the primitive types look like an idealization of C scalar types on a byte-oriented 32-bit machine, you're absolutely right. That's how they're supposed to look. The 16-bit characters were forced by Unicode, and generic pointers were deleted for other reasons we'll touch on later, but in general the syntax and semantics of Java primitive types are meant to fit a C programmer's mental habits. If you're like most of this book's readers, you'll probably find this saves you a lot of mental effort in learning the language. Declaration and initialization Variables are declared inside of methods or classes in C style. For example: int foo; double d1, d2; boolean isFun; Variables can optionally be initialized with an appropriate expression when they are declared: int foo = 42; double d1 = 3.14, d2 = 2 * 3.14; boolean isFun = true; Variables that are declared as instance variables in a class are set to default values if they are not initialized. In this case, they act much like static variables in C or C++. Numeric types default to the appropriate flavor of zero, characters are set to the null character "\0," and boolean variables have the value false. Local variables declared in methods, on the other hand, must be explicitly initialized before they can be used. Integer literals Integer literals can be specified in octal (base 8), decimal (base 10), or hexadecimal (base 16). A decimal integer is specified by a sequence of digits beginning with one of the characters 1-9: int i = 1230; Octal numbers are distinguished from decimal by a leading zero:
http://localhost/java/javaref/exp/ch04_03.htm (2 of 6) [20/12/2001 11:02:08]
[Chapter 4] 4.3 Types
int i = 01230;
// i = 664 decimal
(An interesting, but meaningless, observation is that this would make the number 0 an octal value in the eyes of the compiler.) As in C, a hexadecimal number is denoted by the leading characters 0x or 0X (zero "x"), followed by digits and the characters a-f or A-F, which represent the decimal values 10-15 respectively: int i = 0xFFFF;
// i = 65535 decimal
Integer literals are of type int unless they are suffixed with an L, denoting that they are to be produced as a long value: long l = 13L; long l = 13;
// equivalent--13 is converted from type int
(The lowercase character l ("el") is also acceptable, but should be avoided because it often looks like the numeral 1). When a numeric type is used in an assignment or an expression involving a type with a larger range, it can be promoted to the larger type. For example, in the second line of the above example, the number 13 has the default type of int, but it's promoted to type long for assignment to the long variable. Certain other numeric and comparison operations also cause this kind of arithmetic promotion. A numeric value can never be assigned to a type with a smaller range without an explicit (C-style) cast, however: int i = 13; byte b = i; byte b = (byte) i;
// Compile time error--explicit cast needed // Okay
Conversions from floating point to integer types always require an explicit cast because of the potential loss of precision. Floating-point literals Floating-point values can be specified in decimal or scientific notation. Floating-point literals are of type double unless they are suffixed with an f denoting that they are to be produced as a float value: double d = 8.31; double e = 3.00e+8; float f = 8.31F; float g = 3.00e+8F; Character literals A literal character value can be specified either as a single-quoted character or as an escaped ASCII or Unicode sequence:
http://localhost/java/javaref/exp/ch04_03.htm (3 of 6) [20/12/2001 11:02:08]
[Chapter 4] 4.3 Types
char a = 'a'; char newline = '\n'; char octalff = \u00ff;
Reference Types In C, you can make a new, complex data type by creating a structure. In Java (and other object-oriented languages), you instead create a class that defines a new type in the language. For instance, if we create a new class called Foo in Java, we are also implicitly creating a new type called Foo. The type of an item governs how it's used and where it's assigned. An item of type Foo can, in general, be assigned to a variable of type Foo or passed as an argument to a method that accepts a Foo value. In an object-oriented language like Java, a type is not necessarily just a simple attribute. Reference types are related in the same way as the classes they represent. Classes exist in a hierarchy, where a subclass is a specialized kind of its parent class. The corresponding types have a similar relationship, where the type of the child class is considered a subtype of the parent class. Because child classes always extend their parents and have, at a minimum, the same functionality, an object of the child's type can be used in place of an object of the parent's type. For example, if I create a new class, Bar, that extends Foo, there is a new type Bar that is considered a subtype of Foo. Objects of type Bar can then be used anywhere an object of type Foo could be used; An object of type Bar is said to be assignable to a variable of type Foo. This is called subtype polymorphism and is one of the primary features of an object-oriented language. We'll look more closely at classes and objects in Chapter 5, Objects in Java. Primitive types in Java are used and passed "by value." In other words, when a primitive value is assigned or passed as an argument to a method, it's simply copied. Reference types, on the other hand, are always accessed "by reference." A reference is simply a handle or a name for an object. What a variable of a reference type holds is a reference to an object of its type (or of a subtype). A reference is like a pointer in C or C++, except that its type is strictly enforced and the reference value itself is a primitive entity that can't be examined directly. A reference value can't be created or changed other than through assignment to an appropriate object. When references are assigned or passed to methods, they are copied by value. You can think of a reference as a pointer type that is automatically dereferenced whenever it's mentioned. Let's run through an example. We specify a variable of type Foo, called myFoo, and assign it an appropriate object: Foo myFoo = new Foo(); Foo anotherFoo = myFoo; myFoo is a reference type variable that holds a reference to the newly constructed Foo object. For now, don't worry about the details of creating an object; we'll cover that in Chapter 5, Objects in Java. We designate a second Foo type variable, anotherFoo, and assign it to the same object. There are now two identical references: myFoo and anotherFoo. If we change things in the state of the Foo object itself, we will see the same effect by looking at it with either reference. The comparable code in C++ would be: // C++ Foo& myFoo = *(new Foo()); Foo& anotherFoo = myFoo;
http://localhost/java/javaref/exp/ch04_03.htm (4 of 6) [20/12/2001 11:02:08]
[Chapter 4] 4.3 Types
We can pass one of the variables to a method, as in: myMethod( myFoo ); An important, but sometimes confusing distinction to make at this point is that the reference itself is passed by value. That is, the argument passed to the method (a local variable from the method's point of view) is actually a third copy of the reference. The method can alter the state of the Foo object itself through that reference, but it can't change the caller's reference to myFoo. That is, the method can't change the caller's myFoo to point to a different Foo object. For the times we want a method to change a reference for us, we have to pass a reference to the object that contains it, as shown in Chapter 5, Objects in Java. Reference types always point to objects, and objects are always defined by classes. However, there are two special kinds of reference types that specify the type of object they point to in a slightly different way. Arrays in Java have a special place in the type system. They are a special kind of object automatically created to hold a number of some other type of object, known as the base type. Declaring an array-type reference implicitly creates the new class type, as you'll see in the next section. Interfaces are a bit sneakier. An interface defines a set of methods and a corresponding type. Any object that implements all methods of the interface can be treated as an object of that type. Variables and method arguments can be declared to be of interface types, just like class types, and any object that implements the interface can be assigned to them. This allows Java to cross the lines of the class hierarchy in a type safe way, as you'll see in Chapter 5, Objects in Java.
A Word About Strings Strings in Java are objects; they are therefore a reference type. String objects do, however, have some special help from the Java compiler that makes them look more primitive. Literal string values in Java source code are turned into String objects by the compiler. They can be used directly, passed as arguments to methods, or assigned to String type variables: System.out.println( "Hello World..." ); String s = "I am the walrus..."; String t = "John said: \"I am the walrus...\""; The + symbol in Java is overloaded to provide string concatenation; this is the only overloaded operator in Java: String quote = "Four score and " + "seven years ago,"; String more = quote + " our" + " fathers" + " brought..."; Java builds a single String object from the concatenated strings and provides it as the result of the expression. We will discuss the String class in Chapter 7, Basic Utility Classes.
Comments
http://localhost/java/javaref/exp/ch04_03.htm (5 of 6) [20/12/2001 11:02:08]
Statements and Expressions
[Chapter 4] 4.3 Types
http://localhost/java/javaref/exp/ch04_03.htm (6 of 6) [20/12/2001 11:02:08]
[Chapter 4] 4.4 Statements and Expressions
Chapter 4 The Java Language
4.4 Statements and Expressions Although the method declaration syntax of Java is quite different from that of C++, Java statement and expression syntax is very much like that of C. Again, the design intention was to make the low-level details of Java easily accessible to C programmers, so that they can concentrate on learning the parts of the language that are really different. Java statements appear inside of methods and class and variable initializers; they describe all activities of a Java program. Variable declarations and initializations like those in the previous section are statements, as are the basic language structures like conditionals and loops. Expressions are statements that produce a result that can be used as part of another statement. Method calls, object allocations, and, of course, mathematical expressions are examples of expressions. One of the tenets of Java is to keep things simple and consistent. To that end, when there are no other constraints, evaluations and initializations in Java always occur in the order in which they appear in the code--from left to right. We'll see this rule used in the evaluation of assignment expressions, method calls, and array indexes, to name a few cases. In some other languages, the order of evaluation is more complicated or even implementation dependent. Java removes this element of danger by precisely and simply defining how the code is evaluated. This doesn't, however, mean you should start writing obscure and convoluted statements. Relying on the order of evaluation of expressions is a bad programming habit, even when it works. It produces code that is hard to read and harder to modify. Real programmers, however, are not made of stone, and you may catch me doing this once or twice when I can't resist the urge to write terse code.
Statements As in C or C++, statements and expressions in Java appear within a code block. A code block is syntactically just a number of statements surrounded by an open curly brace ({) and a close curly brace (}). The statements in a code block can contain variable declarations: { int size = 5; setName("Max"); ... } Methods, which look like C functions, are in a sense code blocks that take parameters and can be called http://localhost/java/javaref/exp/ch04_04.htm (1 of 9) [20/12/2001 11:02:10]
[Chapter 4] 4.4 Statements and Expressions
by name. setupDog( String name ) { int size = 5; setName( name ); ... } Variable declarations are limited in scope to their enclosing code block. That is, they can't be seen outside of the nearest set of braces: { int i = 5; } i = 6;
// compile time error, no such variable i
In this way, code blocks can be used to arbitrarily group other statements and variables. The most common use of code blocks, however, is to define a group of statements for use in a conditional or iterative statement. Since a code block is itself collectively treated as a statement, we define a conditional like an if/else clause as follows: if ( condition ) statement; [ else statement; ] Thus, if/else in Java has the familiar functionality of taking either of the forms: if ( condition ) statement; or: if ( condition ) { [ statement; ] [ statement; ] [ ... ] } Here the condition is a boolean expression. In the second form, the statement is a code block, and all of its enclosed statements are executed if the conditional succeeds. Any variables declared within that block are visible only to the statements within the successful branch of the condition. Like the if/else conditional, most of the remaining Java statements are concerned with controlling the flow of execution.
http://localhost/java/javaref/exp/ch04_04.htm (2 of 9) [20/12/2001 11:02:10]
[Chapter 4] 4.4 Statements and Expressions
They act for the most part like their namesakes in C or C++. The do and while iterative statements have the familiar functionality, except that their conditional test is also a boolean expression. You can't use an integer expression or a reference type; in other words you must explicitly test your value. In other words, while i==0 is legitimate, i is not, unless i is boolean. Here are the forms of these two statements: while ( conditional ) statement; do statement; while ( conditional ); The for statement also looks like it does in C: for ( initialization; conditional; incrementor ) statement; The variable initialization expression can declare a new variable; this variable is limited to the scope of the for statement: for (int i = 0; i < 100; i++ ) { System.out.println( i ) int j = i; ... } Java doesn't support the C comma operator, which groups multiple expressions into a single expression. However, you can use multiple, comma-separated expressions in the initialization and increment sections of the for loop. For example: for (int i = 0, j = 10; i < j; i++, j-- ) { ... } The Java switch statement takes an integer type (or an argument that can be promoted to an integer type) and selects among a number of alternative case branches[2] : [2] An object-based switch statement is desirable and could find its way into the language someday. switch ( int expression ) { case int expression : statement; [ case int expression statement;
http://localhost/java/javaref/exp/ch04_04.htm (3 of 9) [20/12/2001 11:02:10]
[Chapter 4] 4.4 Statements and Expressions
... default : statement;
]
} No two of the case expressions can evaluate to the same value. As in C, an optional default case can be specified to catch unmatched conditions. Normally, the special statement break is used to terminate a branch of the switch: switch ( retVal ) { case myClass.GOOD : // something good break; case myClass.BAD : // something bad break; default : // neither one break; } The Java break statement and its friend continue perform unconditional jumps out of a loop or conditional statement. They differ from the corresponding statements in C by taking an optional label as an argument. Enclosing statements, like code blocks and iterators, can be labeled with identifier statements: one: while ( condition ) { ... two: while ( condition ) { ... // break or continue point } // after two } // after one In the above example, a break or continue without argument at the indicated position would have the normal, C-style effect. A break would cause processing to resume at the point labeled "after two"; a continue would immediately cause the two loop to return to its condition test. The statement break two at the indicated point would have the same effect as an ordinary break, but break one would break two levels and resume at the point labeled "after one." Similarly, continue two would serve as a normal continue, but continue one would return to the test of the one loop. Multilevel break and continue statements remove much of the need for the evil goto statement in
http://localhost/java/javaref/exp/ch04_04.htm (4 of 9) [20/12/2001 11:02:10]
[Chapter 4] 4.4 Statements and Expressions
C and C++. There are a few Java statements we aren't going to discuss right now. The try, catch, and finally statements are used in exception handling, as we'll discuss later in this chapter. The synchronized statement in Java is used to coordinate access to statements among multiple threads of execution; see Chapter 6, Threads for a discussion of thread synchronization. On a final note, I should mention that the Java compiler flags "unreachable" statements as compile-time errors. Of course, when I say unreachable, I mean those statements the compiler determines won't be called by a static look at compile-time.
Expressions As I said earlier, expressions are statements that produce a result when they are evaluated. The value of an expression can be a numeric type, as in an arithmetic expression; a reference type, as in an object allocation; or the special type void, which results from a call to a method that doesn't return a value. In the last case, the expression is evaluated only for its side effects (i.e., the work it does aside from producing a value). The type of an expression is known at compile-time. The value produced at run-time is either of this type or, in the case of a reference type, a compatible (assignable) type. Operators Java supports almost all standard C operators. These operators also have the same precedence in Java as they do in C, as you can see in Table 4.3.
Precedence 1 1 1 1
Operator
1
++, -+, ~ ! ( type )
2 3 3 4 4 4 5 5 6 6
*, /, % +, + > >>> = instanceof ==, != ==, !=
Table 4.3: Java Operators Operand Type Arithmetic Arithmetic Integral Boolean
Description Increment and decrement Unary plus and minus Bitwise complement Logical complement
Any
Cast
Arithmetic Arithmetic String Integral Integral Integral Arithmetic Object Primitive Object
Multiplication, division, remainder Addition and subtraction String concatenation Left shift Right shift with sign extension Right shift with no extension Numeric comparison Type comparison Equality and inequality of value Equality and inequality of reference
http://localhost/java/javaref/exp/ch04_04.htm (5 of 9) [20/12/2001 11:02:10]
[Chapter 4] 4.4 Statements and Expressions
7 7 8 8 9 9 10 11 12 13 13
& & ^ ^ | | && || ?: = *=, /=, %=, +=, -=, =, >>>=, &=, ^=, |=
Integral Boolean Integral Boolean Integral Boolean Boolean Boolean NA Any
Bitwise AND Boolean AND Bitwise XOR Boolean XOR Bitwise OR Boolean OR Conditional AND Conditional OR Conditional ternary operator Assignment
Any
Assignment with operation
There are a few operators missing from the standard C collection. For example, Java doesn't support the comma operator for combining expressions, although the for statement allows you to use it in the initialization and increment sections. Java doesn't allow direct pointer manipulation, so it does not support the reference (*), dereference (&), and sizeof operators. Java also adds some new operators. As we've seen, the + operator can be used with String values to perform string concatenation. Because all integral types in Java are signed values, the >> operator performs a right-shift operation with sign extension. The >>> operator treats the operand as an unsigned number and performs a right shift with no extension. The new operator is used to create objects; we will discuss it in detail shortly. Assignment While variable initialization (i.e., declaration and assignment together) is considered a statement, variable assignment alone is an expression: int i, j; i = 5;
// expression
Normally, we rely on assignment for its side effects alone, but, as in C, an assignment can be used as a value in another part of an expression: j = ( i = 5 ); Again, relying on order of evaluation extensively (in this case, using compound assignments in complex expressions) can make code very obscure and hard to read. Do so at your own peril. null The expression null can be assigned to any reference type. It has the meaning of "no reference." A
http://localhost/java/javaref/exp/ch04_04.htm (6 of 9) [20/12/2001 11:02:10]
[Chapter 4] 4.4 Statements and Expressions
null reference can't be used to select a method or variable and attempting to do so generates a NullPointerException at run-time. Variable access Using the dot (.) to access a variable in an object is a type of expression that results in the value of the variable accessed. This can be either a numeric type or a reference type: int i; String s; i = myObject.length; s = myObject.name; A reference type expression can be used in further evaluations, by selecting variables or calling methods within it: int len = myObject.name.length(); int initialLen = myObject.name.substring(5, 10).length(); Here we have found the length of our name variable by invoking the length() method of the String object. In the second case, we took an intermediate step and asked for a substring of the name string. The substring method of the String class also returns a String reference, for which we ask the length. (Chapter 7, Basic Utility Classes describes all of these String methods in detail.) Method invocation A method invocation is basically a function call, or in other words, an expression that results in a value, the type of which is the return type of the method. Thus far, we have seen methods invoked via their name in simple cases: System.out.println( "Hello World..." ); int myLength = myString.length(); When we talk about Java's object-oriented features in Chapter 5, Objects in Java, we'll look at some rules that govern the selection of methods. Like the result of any expression, the result of a method invocation can be used in further evaluations, as we saw above. Whether to allocate intermediate variables and make it absolutely clear what your code is doing or to opt for brevity where it's appropriate is a matter of coding style. Object creation Objects in Java are allocated with the new operator: Object o = new Object(); The argument to new is a constructor that specifies the type of object and any required parameters to http://localhost/java/javaref/exp/ch04_04.htm (7 of 9) [20/12/2001 11:02:10]
[Chapter 4] 4.4 Statements and Expressions
create it. The return type of the expression is a reference type for the created object. We'll look at object creation in detail in Chapter 5, Objects in Java. For now, I just want to point out that object creation is a type of expression, and that the resulting object reference can be used in general expressions. In fact, because the binding of new is "tighter" than that of the dot-field selector, you can easily allocate a new object and invoke a method in it for the resulting expression: int hours = new Date().getHours(); The Date class is a utility class that represents the current time. Here we create a new instance of Date with the new operator and call its getHours() method to retrieve the current hour as an integer value. The Date object reference lives long enough to service the method call and is then cut loose and garbage collected at some point in the future. Calling methods in object references in this way is, again, a matter of style. It would certainly be clearer to allocate an intermediate variable of type Date to hold the new object and then call its getHours() method. However, some of us still find the need to be terse in our code. instanceof The instanceof operator can be used to determine the type of an object at run-time. instanceof returns a boolean value that indicates whether an object is an instance of a particular class or a subclass of that class: Boolean b; String str = "foo"; b = ( str instanceof String ); b = ( str instanceof Object ); b = ( str instanceof Date );
// true // also true // false--not a Date or subclass
instanceof also correctly reports if an object is of the type of an arry or a specified interface. if ( foo instanceof byte[] ) ... (See Chapter 5, Objects in Java for a full discussion of interfaces.) It is also important to note that the value null is not considered an instance of any object. So the following test will return false, no matter what the declared type of the variable: String s = null; if ( s istanceof String ) // won't happen
Types
http://localhost/java/javaref/exp/ch04_04.htm (8 of 9) [20/12/2001 11:02:10]
Exceptions
[Chapter 4] 4.4 Statements and Expressions
http://localhost/java/javaref/exp/ch04_04.htm (9 of 9) [20/12/2001 11:02:10]
[Chapter 4] 4.5 Exceptions
Chapter 4 The Java Language
4.5 Exceptions Do, or do not... There is no try. --Yoda (The Empire Strikes Back) Java's roots are in embedded systems--software that runs inside specialized devices like hand-held computers, cellular phones, and fancy toasters. In those kinds of applications, it's especially important that software errors be handled properly. Most users would agree that it's unacceptable for their phone to simply crash or for their toast (and perhaps their house) to burn because their software failed. Given that we can't eliminate the possibility of software errors, a step in the right direction is to at least try to recognize and deal with the application-level errors that we can anticipate in a methodical and systematic way. Dealing with errors in a language like C is the responsibility of the programmer. There is no help from the language itself in identifying error types, and there are no tools for dealing with them easily. In C and C++, a routine generally indicates a failure by returning an "unreasonable" value (e.g., the idiomatic -1 or null). As the programmer, you must know what constitutes a bad result, and what it means. It's often awkward to work around the limitations of passing error values in the normal path of data flow.[3] An even worse problem is that certain types of errors can legitimately occur almost anywhere, and it's prohibitive and unreasonable to explicitly test for them at every point in the software. [3] The somewhat obscure setjmp() and longjmp() statements in C can save a point in the execution of code and later return to it unconditionally from a deeply buried location. In a limited sense, this is the functionality of exceptions in Java. Java offers an elegant solution to these problems with exception handling. (Java exception handling is similar to, but not quite the same as, exception handling in C++.) An exception indicates an unusual condition or an error condition. Program control becomes unconditionally transferred or thrown to a specially designated section of code where it's caught and handled. In this way, error handling is somewhat orthogonal to the normal flow of the program. We don't have to have special return values for all our methods; errors are handled by a separate mechanism. Control can be passed long distance from a deeply nested routine and handled in a single location when that is desirable, or an error can be handled immediately at its source. There are still a few methods that return -1 as a special value, but these are limited to situations in which there isn't really an error.[4] [4] For example, the getHeight() method of the Image class returns -1 if the height http://localhost/java/javaref/exp/ch04_05.htm (1 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
isn't known yet. No error has occurred; the height will be available in the future. In this situation, throwing an exception would be inappropriate. A Java method is required to specify the exceptions it can throw (i.e., the ones that it doesn't catch itself); this means that the compiler can make sure we handle them. In this way, the information about what errors a method can produce is promoted to the same level of importance as its argument and return types. You may still decide to punt and ignore obvious errors, but in Java you must do so explicitly.
Exceptions and Error Classes Exceptions are represented by instances of the class java.lang.Exception and its subclasses. Subclasses of Exception can hold specialized information (and possibly behavior) for different kinds of exceptional conditions. However, more often they are simply "logical" subclasses that exist only to serve as a new exception type (more on that later). Figure 4.1 shows the subclasses of Exception; these classes are defined in various packages in the Java API, as indicated in the diagram. Figure 4.1: Java exception classes
http://localhost/java/javaref/exp/ch04_05.htm (2 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
An Exception object is created by the code at the point where the error condition arises. It can hold whatever information is necessary to describe the exceptional condition, including a full stack trace for debugging. The exception object is passed, along with the flow of control, to the handling block of code. This is where the terms "throw" and "catch" come from: the Exception object is thrown from one point in the code and caught by the other, where execution resumes. The Java API also defines the java.lang.Error class for eggregious or unrecoverable errors. The subclasses of Error are shown in Figure 4.2. You needn't worry about these errors (i.e., you do not have to catch them); they normally indicate linkage problems or virtual machine errors. An error of this kind usually causes the Java interpreter to display a message and exit. Figure 4.2: Java error classes
http://localhost/java/javaref/exp/ch04_05.htm (3 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
Exception Handling The try/catch guarding statements wrap a block of code and catch designated types of exceptions that occur within it: try { readFromFile("foo"); ... } catch ( Exception e ) { // Handle error System.out.println( "Exception while reading file: " + e ); ... } In the above example, exceptions that occur within the body of the try statement are directed to the catch clause for possible handling. The catch clause acts like a method; it specifies an argument of the type of exception it wants to handle, and, if it's invoked, the Exception object is passed into its body as an argument. Here we receive the object in the variable e and print it along with a message.
http://localhost/java/javaref/exp/ch04_05.htm (4 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
A try statement can have multiple catch clauses that specify different specific types (subclasses) of Exception: try { readFromFile("foo"); ... } catch ( FileNotFoundException e ) { // Handle file not found ... } catch ( IOException e ) { // Handle read error ... } catch ( Exception e ) { // Handle all other errors ... } The catch clauses are evaluated in order, and the first possible (assignable) match is taken. At most one catch clause is executed, which means that the exceptions should be listed from most specific to least. In the above example, we'll assume that the hypothetical readFromFile() can throw two different kinds of exceptions: one that indicates the file is not found; the other indicates a more general read error. Any subclass of Exception is assignable to the parent type Exception, so the third catch clause acts like the default clause in a switch statement and handles any remaining possibilities. It should be obvious, but one beauty of the try/catch statement is that any statement in the try block can assume that all previous statements in the block succeeded. A problem won't arise suddenly because a programmer forgot to check the return value from some method. If an earlier statement fails, execution jumps immediately to the catch clause; later statements are never executed.
Bubbling Up What if we hadn't caught the exception? Where would it have gone? Well, if there is no enclosing try/catch statement, the exception pops to the top of the method in which it appeared and is, in turn, thrown from that method. In this way, the exception bubbles up until it's caught, or until it pops out of the top of the program, terminating it with a run-time error message. There's a bit more to it than that because, in this case, the compiler would have reminded us to deal with it, but we'll get back to that in a moment. Let's look at another example. In Figure 4.3, the method getContent() invokes the method openConnection() from within a try/catch statement. openConnection(), in turn, invokes the method sendRequest(), which calls the method write() to send some data. Figure 4.3: Exception propagation
http://localhost/java/javaref/exp/ch04_05.htm (5 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
In this figure, the second call to write() throws an IOException. Since sendRequest() doesn't contain a try/catch statement to handle the exception, it's thrown again, from the point that it was called in the method openConnection(). Since openConnection() doesn't catch the exception either, it's thrown once more. Finally it's caught by the try statement in getContent() and handled by its catch clause. Since an exception can bubble up quite a distance before it is caught and handled, we may need a way to determine exactly where it was thrown. All exceptions can dump a stack trace that lists their method of origin and all of the nested method calls that it took to arrive there, using the printStackTrace() method. try { // complex task } catch ( Exception e ) { // dump information about exactly where the exception ocurred e.printStackTrack( System.err ); ... }
The throws Clause and checked Exceptions I mentioned earlier that Java makes us be explicit about our error handling. But Java is programmer-friendly, and it's not possible to require that every conceivable type of error be handled in every situation. So, Java exceptions are divided into two categories: checked exceptions and unchecked exceptions. Most application level exceptions are checked, which means that any method that throws one, either by generating it itself (as we'll discuss below) or by passively ignoring one that occurs within it, must declare that it can throw that type of exception in a special throws clause in its method declaration. We haven't yet talked in detail about declaring methods; we'll cover that in Chapter 5, Objects in Java. For now all you need know is that methods have to declare the checked exceptions they can throw or allow to be thrown. Again in Figure 4.3, notice that the methods openConnection() and sendRequest() both specify that they can throw an IOException. If we had to throw multiple types of exceptions we could declare them separated with commas:
http://localhost/java/javaref/exp/ch04_05.htm (6 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
void readFile( String s ) throws IOException, InterruptedException { ... } The throws clause tells the compiler that a method is a possible source of that type of checked exception and that anyone calling that method must be prepared to deal with it. The caller may use a try/catch block to catch it, or it may, itself, declare that it can throw the exception. Exceptions that are subclasses of the java.lang.RuntimeException class are unchecked. See Figure 4.1 for the subclasses of RuntimeException. It's not a compile-time error to ignore the possibility of these exceptions being thrown; additionally, methods don't have to declare they can throw them. In all other respects, run-time exceptions behave the same as other exceptions. We are perfectly free to catch them if we wish; we simply aren't required to. Checked exceptions Exceptions a reasonable application should try to handle gracefully. Unchecked exception (Runtime exceptions) Exceptions from which we would not normally expect our software to try to recover. The category of checked exceptions includes application-level problems like missing files and unavailable hosts. As good programmers (and upstanding citizens), we should design software to recover gracefully from these kinds of conditions. The category of unchecked exceptions includes problems such as "out of memory" and "array index out of bounds." While these may indicate application-level programming errors, they can occur almost anywhere and aren't generally easy to recover from. Fortunately, because there are unchecked exceptions, you don't have to wrap every one of your array-index operations in a try/catch statement.
Throwing Exceptions We can throw our own exceptions: either instances of Exception or one of its predefined subclasses, or our own specialized subclasses. All we have to do is create an instance of the Exception and throw it with the throw statement: throw new Exception(); Execution stops and is transferred to the nearest enclosing try/catch statement. (Note that there is little point in keeping a reference to the Exception object we've created here.) An alternative constructor of the Exception class lets us specify a string with an error message: throw new Exception("Something really bad happened"); By convention, all types of Exception have a String constructor like this. Note that the String message above is somewhat facetious and vague. Normally you won't be throwing a plain old Exception, but a more specific subclass. For example: public void checkRead( String s ) { http://localhost/java/javaref/exp/ch04_05.htm (7 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
if ( new File(s).isAbsolute() || (s.indexOf("..") != -1) ) throw new SecurityException( x"Access to file : "+ s +" denied."); } In the above, we partially implement a method to check for an illegal path. If we find one, we throw a SecurityException, with some information about the transgression. Of course, we could include whatever other information is useful in our own specialized subclasses of Exception (or SecurityException). Often though, just having a new type of exception is good enough, because it's sufficient to help direct the flow of control. For example, if we are building a parser, we might want to make our own kind of exception to indicate a particular kind of failure. class ParseException extends Exception { ParseException() { super(); } ParseException( String desc ) { super( desc ) }; } See Chapter 5, Objects in Java for a full description of classes and class constructors. The body of our exception class here simply allows a ParseException to be created in the conventional ways that we have created exceptions above. Now that we have our new exception type, we we might guard for it in the following kind of situation: // Somewhere in our code ... try { parseStream( input ); } catch ( ParseException pe ) { // Bad input... } catch ( IOException ioe ) { // Low level communications problem } As you can see, although our new exception doesn't currently hold any specialized information about the problem (it certainly could), it does let us distinguish a parse error from an arbitrary communications error in the same chunk of code. You might call this kind of specialization of an exception to be making a "logical" exception. Re-throwing exceptions Sometimes you'll want to take some action based on an exception and then turn around and throw a new exception in its place. For example, suppose that we want to handle an IOException by freeing up some resources before allowing the failure to pass on to the rest of the application. You can do this in the obvious way, by simply catching the exception and then throwing it again or throwing a new one.
http://localhost/java/javaref/exp/ch04_05.htm (8 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
*** I was going to say something about fillInStackTrack() here ***
Try Creep The try statement imposes a condition on the statements they guard. It says that if an exception occurs within it, the remaining statements will be abandoned. This has consequences for local variable initialization. If the compiler can't determine whether a local variable assignment we placed inside a try/catch block will happen, it won't let us use the variable: void myMethod() { int foo; try { foo = getResults(); } catch ( Exception e ) { ... } int bar = foo;
// Compile time error--foo may not // have been initialized
In the above example, we can't use foo in the indicated place because there's a chance it was never assigned a value. One obvious option is to move the assignment inside the try statement: try { foo = getResults(); int bar = foo; // Okay because we only get here // if previous assignment succeeds } catch ( Exception e ) { ... } Sometimes this works just fine. However, now we have the same problem if we want to use bar later in myMethod(). If we're not careful, we might end up pulling everything into the try statement. The situation changes if we transfer control out of the method in the catch clause: try { foo = getResults(); } catch ( Exception e ) { ... return;
http://localhost/java/javaref/exp/ch04_05.htm (9 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
} int bar = foo;
// Okay because we only get here // if previous assignment succeeds
Your code will dictate its own needs; you should just be aware of the options.
The finally Clause What if we have some clean up to do before we exit our method from one of the catch clauses? To avoid duplicating the code in each catch branch and to make the cleanup more explicit, Java supplies the finally clause. A finally clause can be added after a try and any associated catch clauses. Any statements in the body of the finally clause are guaranteed to be executed, no matter why control leaves the try body: try { // Do something here } catch ( FileNotFoundException e ) { ... } catch ( IOException e ) { ... } catch ( Exception e ) { ... } finally { // Cleanup here } In the above example the statements at the cleanup point will be executed eventually, no matter how control leaves the try. If control transfers to one of the catch clauses, the statements in finally are executed after the catch completes. If none of the catch clauses handles the exception, the finally statements are executed before the exception propagates to the next level. If the statements in the try execute cleanly, or even if we perform a return, break, or continue, the statements in the finally clause are executed. To perform cleanup operations, we can even use try and finally without any catch clauses: try { // Do something here return; } finally { System.out.println("Whoo-hoo!");
http://localhost/java/javaref/exp/ch04_05.htm (10 of 11) [20/12/2001 11:02:13]
[Chapter 4] 4.5 Exceptions
} Exceptions that occur in a catch or finally clause are handled normally; the search for an enclosing try/catch begins outside the offending try statement.
Statements and Expressions
http://localhost/java/javaref/exp/ch04_05.htm (11 of 11) [20/12/2001 11:02:13]
Arrays
[Chapter 4] 4.6 Arrays
Chapter 4 The Java Language
4.6 Arrays An array is a special type of object that can hold an ordered collection of elements. The type of the elements of the array is called the base type of the array; the number of elements it holds is a fixed attribute called its length. (For a collection with a variable length, see the discussion of Vector objects in Chapter 7, Basic Utility Classes.) Java supports arrays of all numeric and reference types. The basic syntax of arrays looks much like that of C or C++. We create an array of a specified length and access the elements with the special index operator, []. Unlike other languages, however, arrays in Java are true, first-class objects, which means they are real objects within the Java language. An array is an instance of a special Java array class and has a corresponding type in the type system. This means that to use an array, as with any other object, we first declare a variable of the appropriate type and then use the new operator to create an instance of it. Array objects differ from other objects in Java in three respects: ● Java implicitly creates a special array class for us whenever we declare an array type variable. It's not strictly necessary to know about this process in order to use arrays, but it helps in understanding their structure and their relationship to other objects in Java. ● Java lets us use the special [] operator to access array elements, so that arrays look as we expect. We could implement our own classes that act like arrays, but because Java doesn't have user-defined operator overloading, we would have to settle for having methods like get() and put() instead of using the special [] notation. ● Java provides a corresponding special form of the new operator that lets us construct an instance of an array and specify its length with the [] notation.
Array Types An array type variable is denoted by a base type followed by empty brackets []. Alternatively, Java accepts a C-style declaration, with the brackets placed after the array name. The following are equivalent: int [] arrayOfInts; int arrayOfInts [];
http://localhost/java/javaref/exp/ch04_06.htm (1 of 7) [20/12/2001 11:02:15]
[Chapter 4] 4.6 Arrays
In each case, arrayOfInts is declared as an array of integers. The size of the array is not yet an issue, because we are declaring only the array type variable. We have not yet created an actual instance of the array class, with its associated storage. It's not even possible to specify the length of an array as part of its type. An array of objects can be created in the same way: String [] someStrings; Button someButtons [];
Array Creation and Initialization Having declared an array type variable, we can now use the new operator to create an instance of the array. After the new operator, we specify the base type of the array and its length, with a bracketed integer expression: arrayOfInts = new int [42]; someStrings = new String [ number + 2 ]; We can, of course, combine the steps of declaring and allocating the array: double [] someNumbers = new double [20]; Component widgets [] = new Component [12]; As in C, array indices start with zero. Thus, the first element of someNumbers [] is 0 and the last element is 19. After creation, the array elements are initialized to the default values for their type. For numeric types, this means the elements are initially zero: int [] grades = new int [30]; grades[0] = 99; grades[1] = 72; // grades[2] == 0 The elements of an array of objects are references to the objects, not actual instances of the objects. The default value of each element is therefore null, until we assign instances of appropriate objects: String names [] = new String [4]; names [0] = new String(); names [1] = "Boofa"; names [2] = someObject.toString(); // names[3] == null This is an important distinction that can cause confusion. In many other languages, the act of creating an array is the same as allocating storage for its elements. In Java, an array of objects actually contains only reference variables and those variables, have the value null until they are assigned to real objects.[5] Figure 4.4 illustrates the names array of the previous example:
http://localhost/java/javaref/exp/ch04_06.htm (2 of 7) [20/12/2001 11:02:15]
[Chapter 4] 4.6 Arrays
[5] The analog in C or C++ would be an array of pointers to objects. However, pointers in C or C++ are themselves two- or four-byte values. Allocating an array of pointers is, in actuality, allocating the storage for some number of those pointer objects. An array of references is conceptually similar, although references are not themselves objects. We can't manipulate references or parts of references other than by assignment, and their storage requirements (or lack thereof) are not part of the high-level language specification. Figure 4.4: The names array
names is a variable of type String[] (i.e., a string array). The String[] object can be thought of as containing four String type variables. We have assigned String objects to the first three array elements. The fourth has the default value null. Java supports the C-style curly braces {} construct for creating an array and initializing its elements when it is declared: int [] primes = { 1, 2, 3, 5, 7, 7+4 };
// primes[2] == 3
An array object of the proper type and length is implicitly created and the values of the comma-separated list of expressions are assigned to its elements. We can use the {} syntax with an array of objects. In this case, each of the expressions must evaluate to an object that can be assigned to a variable of the base type of the array, or the value null. Here are some examples: String [] verbs = { "run", "jump", someWord.toString() }; Button [] controls = { stopButton, new Button("Forwards"), new Button("Backwards") }; // all types are subtypes of Object Object [] objects = { stopButton, "A word", null }; You should create and initialize arrays in whatever manner is appropriate for your application. The following are equivalent: http://localhost/java/javaref/exp/ch04_06.htm (3 of 7) [20/12/2001 11:02:15]
[Chapter 4] 4.6 Arrays
Button [] threeButtons = new Button [3]; Button [] threeButtons = { null, null, null };
Using Arrays The size of an array object is available in the public variable length: char [] alphabet = new char [26]; int alphaLen = alphabet.length;
// alphaLen == 26
String [] musketeers = { "one", "two", "three" }; int num = musketeers.length; // num == 3 length is the only accessible field of an array; it is a variable, not a method. Array access in Java is just like array access in C; you access an element by putting an integer-valued expression between brackets after the name of the array. The following example creates an array of Button objects called keyPad and then fills the array with Button objects: Button [] keyPad = new Button [ 10 ]; for ( int i=0; i < keyPad.length; i++ ) Integer.toString( i ) );
keyPad[ i ] = new Button(
Attempting to access an element that is outside the range of the array generates an ArrayIndexOutOfBoundsException. This is a type of RuntimeException, so you can either catch it and handle it yourself, or ignore it, as we already discussed: String [] states = new String [50]; try { states[0] = "California"; states[1] = "Oregon"; ... states[50] = "McDonald's Land"; // Error--array out of bounds } catch ( ArrayIndexOutOfBoundsException err ) { System.out.println( "Handled error: " + err.getMessage() ); } It's a common task to copy a range of elements from one array into another. Java supplies the arraycopy() method for this purpose; it's a utility method of the System class: System.arraycopy( source, sourceStart, destination, destStart, length );
http://localhost/java/javaref/exp/ch04_06.htm (4 of 7) [20/12/2001 11:02:15]
[Chapter 4] 4.6 Arrays
The following example doubles the size of the names array from an earlier example: String [] tmpVar = new String [ 2 * names.length ]; System.arraycopy( names, 0, tmpVar, 0, names.length ); names = tmpVar; A new array, twice the size of names, is allocated and assigned to a temporary variable tmpVar. arraycopy() is used to copy the elements of names to the new array. Finally, the new array is assigned to names. If there are no remaining references to the old array object after names has been copied, it will be garbage collected on the next pass.
Anonymous Arrays You often want to create "throw-away" arrays: arrays that are only used in one place, and never referenced anywhere else. Such arrays don't need to have a name, because you never need to refer to them again in that context. For example, you may want to create a collection of objects to pass as an argument to some method. It's easy enough to create a normal, named array--but if you don't actually work with the array (if you use the array only as a holder for some collection), you shouldn't have to. Java makes it easy to create "anonymous" (i.e., unnamed) arrays. Let's say you need to call a method named setPets(), which takes an array of Animal objects as arguments. Cat and Dog are subclasses of Animal. Here's how to call setPets() using an anonymous array: Dog pokey = new Dog ("gray"); Cat squiggles = new Cat ("black"); Cat jasmine = new Cat ("orange"); setPets ( new Animal [] { pokey, squiggles, jasmine }); The syntax looks just like the initialization of an array in a variable declaration. We implicitly define the size of the array and fill in its elements using the curly brace notation. However, since this is not a variable declaration we have to explicitly use the new operator to create the array object. You can use anonymous arrays to simulate variable length argument lists (often called VARARGS), a feature of many programming languages that Java doesn't provide. The advantage of anonymous arrays over variable length argument lists is that it allows stricter type checking; the compiler always knows exactly what arguments are expected, and therefore can verify that method calls are correct.
Multidimensional Arrays Java supports multidimensional arrays in the form of arrays of array type objects. You create a multidimensional array with C-like syntax, using multiple bracket pairs, one for each dimension. You also use this syntax to access elements at various positions within the array. Here's an example of a multidimensional array that represents a chess board: ChessPiece [][] chessBoard;
http://localhost/java/javaref/exp/ch04_06.htm (5 of 7) [20/12/2001 11:02:15]
[Chapter 4] 4.6 Arrays
chessBoard = new ChessPiece [8][8]; chessBoard[0][0] = new ChessPiece( "Rook" ); chessBoard[1][0] = new ChessPiece( "Pawn" ); ... Here chessBoard is declared as a variable of type ChessPiece[][] (i.e., an array of ChessPiece arrays). This declaration implicitly creates the type ChessPiece[] as well. The example illustrates the special form of the new operator used to create a multidimensional array. It creates an array of ChessPiece[] objects and then, in turn, creates each array of ChessPiece objects. We then index chessBoard to specify values for particular ChessPiece elements. (We'll neglect the color of the pieces here.) Of course, you can create arrays of with more than two dimensions. Here's a slightly impractical example: Color [][][] rgbCube = new Color [256][256][256]; rgbCube[0][0][0] = Color.black; rgbCube[255][255][0] = Color.yellow; ... As in C, we can specify the initial index of a multidimensional array to get an array type object with fewer dimensions. In our example, the variable chessBoard is of type ChessPiece[][]. The expression chessBoard[0] is valid and refers to the first element of chessBoard, which is of type ChessPiece[]. For example, we can create a row for our chess board: ChessPiece [] startRow = { new ChessPiece("Rook"), new ChessPiece("Knight"), new ChessPiece("Bishop"), new ChessPiece("King"), new ChessPiece("Queen"), new ChessPiece("Bishop"), new ChessPiece("Knight"), new ChessPiece("Rook") }; chessBoard[0] = startRow; We don't necessarily have to specify the dimension sizes of a multidimensional array with a single new operation. The syntax of the new operator lets us leave the sizes of some dimensions unspecified. The size of at least the first dimension (the most significant dimension of the array) has to be specified, but the sizes of any number of the less significant array dimensions may be left undefined. We can assign appropriate array type values later. We can create a checkerboard of boolean values (which is not quite sufficient for a real game of checkers) using this technique: boolean [][] checkerBoard; checkerBoard = new boolean [8][]; Here, checkerBoard is declared and created, but its elements, the eight boolean[] objects of the http://localhost/java/javaref/exp/ch04_06.htm (6 of 7) [20/12/2001 11:02:15]
[Chapter 4] 4.6 Arrays
next level, are left empty. Thus, for example, checkerBoard[0] is null until we explicitly create an array and assign it, as follows: checkerBoard[0] = new boolean [8]; checkerBoard[1] = new boolean [8]; ... checkerBoard[7] = new boolean [8]; The code of the previous two examples is equivalent to: boolean [][] checkerBoard = new boolean [8][8]; One reason we might want to leave dimensions of an array unspecified is so that we can store arrays given to us by another method. Note that since the length of the array is not part of its type, the arrays in the checkerboard do not necessarily have to be of the same length. Here's a defective (but perfectly legal) checkerboard: checkerBoard[2] = new boolean [3]; checkerBoard[3] = new boolean [10]; Since Java implements multidimensional arrays as arrays of arrays, multidimensional arrays do not have to be rectangular. For example, here's how you could create and initialize a triangular array: int []][] triangle = new int [5][]; for (int i = 0; i < triangle.length; i++) { triangle[i] = new int [i + 1]; for (int j = 0; j < i + 1; j++) triangle[i][j] = i + j; }
Inside Arrays I said earlier that arrays are instances of special array classes in the Java language. If arrays have classes, where do they fit into the class hierarchy and how are they related? These are good questions; however, we need to talk more about the object-oriented aspects of Java before I can answer them. For now, take it on faith that arrays fit into the class hierarchy; details are in Chapter 5, Objects in Java.
Exceptions
http://localhost/java/javaref/exp/ch04_06.htm (7 of 7) [20/12/2001 11:02:15]
Objects in Java
[Chapter 5] 5.2 Methods
Chapter 5 Objects in Java
5.2 Methods Methods appear inside class bodies. They contain local variable declarations and other Java statements that are executed by a calling thread when the method is invoked. Method declarations in Java look like ANSI C-style function declarations with two restrictions: ● A method in Java always specifies a return type (there's no default). The returned value can be a primitive numeric type, a reference type, or the type void, which indicates no returned value. ● A method always has a fixed number of arguments. The combination of method overloading and true arrays removes most of the need for a variable number of arguments. These techniques are type-safe and easier to use than C's variable argument list mechanism. Here's a simple example: class Bird { int xPos, yPos; double fly ( int x, int y ) { double distance = Math.sqrt( x*x + y*y ); flap( distance ); xPos = x; yPos = y; return distance; } ... } In this example, the class Bird defines a method, fly(), that takes as arguments two integers: x and y. It returns a double type value as a result.
Local Variables The fly() method declares a local variable called distance that it uses to compute the distance flown. A local variable is temporary; it exists only within the scope of its method. Local variables are allocated and initialized when a method is invoked; they are normally destroyed when the method
http://localhost/java/javaref/exp/ch05_02.htm (1 of 8) [20/12/2001 11:02:17]
[Chapter 5] 5.2 Methods
returns. They can't be referenced from outside the method itself. If the method is executing concurrently in different threads, each thread has its own copies of the method's local variables. A method's arguments also serve as local variables within the scope of the method. An object created within a method and assigned to a local variable may or may not persist after the method has returned. As with all objects in Java, it depends on whether any references to the object remain. If an object is created, assigned to a local variable, and never used anywhere else, that object will no longer be referenced when the local variable is destroyed, so garbage collection will remove the object. If, however, we assign the object to an instance variable, pass it as an argument to another method, or pass it back as a return value, it may be saved by another variable holding its reference. We'll discuss object creation and garbage collection in more detail shortly.
Shadowing If a local variable and an instance variable have the same name, the local variable shadows or hides the name of the instance variable within the scope of the method. In the following example, the local variables xPos and yPos hide the instance variables of the same name: class Bird { int xPos, yPos; int xNest, yNest; ... double flyToNest() { int xPos = xNest; int yPos = yNest: return ( fly( xPos, yPos ) ); } ... } When we set the values of the local variables in flyToNest(), it has no effect on the values of the instance variables. this The special reference this refers to the current object. You can use it any time you need to refer explicitly to the current object instance. Often, you don't need to use this because the reference to the current object is implicit; this is the case with using instance variables and methods inside of a class. But we can use this to refer explicitly to instance variables in the object, even if they are shadowed. The subsequent example shows how we can use this to allow us argument names that shadow instance variable names. This is a fairly common technique, as it saves your having to deliberately make up alternate names (as we'll try to emphasize in this book, names are important). Here's how we could implement our fly() method with shadowed variables: class Bird {
http://localhost/java/javaref/exp/ch05_02.htm (2 of 8) [20/12/2001 11:02:17]
[Chapter 5] 5.2 Methods
int xPos, yPos; double fly ( int xPos, int yPos ) { double distance = Math.sqrt( xPos*xPos + yPos*yPos ); flap( distance ); this.xPos = xPos; this.yPos = yPos; return distance; } ... } In this example, the expression this.xPos refers to the instance variable xPos and assigns it the value of the local variable xPos, which would otherwise hide its name. The only reason we need to use this in the above example is because we've used argument names that hide our instance variables, and we want to refer to the instance variables.
Static Methods Static methods (class methods), like static variables, belong to the class and not to an individual instance of the class. What does this mean? Well, foremost, a static method lives outside of any particular class instance. It can be invoked by name, through the class name, without any objects around. Because it is not bound to a particular object instance, a static method can only directly access other static members of classes. It can't directly see any instance variables or call any instance methods, because to do so we'd have to ask: "on which instance?" Static methods can be called from instances, just like instance methods, but the important thing is that they can also be used independently. Our fly() method uses a static method: Math.sqrt(). This method is defined by the java.lang.Math class; we'll explore this class in detail in Chapter 7, Basic Utility Classes. For now, the important thing to note is that Math is the name of a class and not an instance of a Math object (you can't even make an instance of Math). Because static methods can be invoked wherever the class name is available, class methods are closer to normal C-style functions. Static methods are particularly useful for utility methods that perform work that might be useful either independently of instances of the class or in creating instances of the class. For example, in our Bird class we can enumerate all types of birds that can be created: class Bird { ... static String [] getBirdTypes( ) { String [] types; // Create list... return types; } ... }
http://localhost/java/javaref/exp/ch05_02.htm (3 of 8) [20/12/2001 11:02:17]
[Chapter 5] 5.2 Methods
Here we've defined a static method getBirdTypes() that returns an array of strings containing bird names. We can use getBirdTypes() from within an instance of Bird, just like an instance method. However, we can also call it from other classes, using the Bird class name as a reference: String [] names = Bird.getBirdTypes(); Perhaps a special version of the Bird class constructor accepts the name of a bird type. We could use this list to decide what kind of bird to create.
Local Variable Initialization In the flyToNest() example, we made a point of initializing the local variables xPos and yPos. Unlike instance variables, local variables must be initialized before they can be used. It's a compile-time error to try to access a local variable without first assigning it a value: void myMethod() { int foo = 42; int bar; // bar += 1; bar = 99; bar += 1;
// Compile time error, bar uninitialized
// ok here
} Notice that this doesn't imply local variables have to be initialized when declared, just that the first time they are referenced must be in an assignment. More subtle possibilities arise when making assignments inside of conditionals: void myMethod { int foo; if ( someCondition ) { foo = 42; ... } foo += 1;
// Compile time error // foo may not have been initialized
In the above example, foo is initialized only if someCondition is true. The compiler doesn't let you make this wager, so it flags the use of foo as an error. We could correct this situation in several ways. We could initialize the variable to a default value in advance or move the usage inside of the conditional. We could also make sure the path of execution doesn't reach the uninitialized variable through some other means, depending on what makes sense for our particular application. For example, we could return from the method abruptly: http://localhost/java/javaref/exp/ch05_02.htm (4 of 8) [20/12/2001 11:02:17]
[Chapter 5] 5.2 Methods
int foo; ... if ( someCondition ) { foo = 42; ... } else return; foo += 1; In this case, there's no chance of reaching foo in an unused state and the compiler allows the use of foo after the conditional. Why is Java so picky about local variables? One of the most common (and insidious) sources of error in C or C++ is forgetting to initialize local variables, so Java tries to help us out. If it didn't, Java would suffer the same potential irregularities as C or C++.[2] [2] As with malloc'ed storage in C or C++, Java objects and their instance variables are allocated on a heap, which allows them default values once, when they are created. Local variables, however, are allocated on the Java virtual machine stack. As with the stack in C and C++, failing to initialize these could mean successive method calls could receive garbage values, and program execution might be inconsistent or implementation dependent.
Argument Passing and References Let's consider what happens when you pass arguments to a method. All primitive data types (e.g., int, char, float) are passed by value. Now you're probably used to the idea that reference types (i.e., any kind of object, including arrays and strings) are used through references. An important distinction (that we discussed briefly in Chapter 4) is that the references themselves (the pointers to these objects) are actually primitive types, and are passed by value too. Consider the following piece of code: // somewhere int i = 0; SomeKindOfObject obj = new SomeKindOfObject(); myMethod( i, obj ); ... void myMethod(int j, SomeKindOfObject o) { ... } The first chunk of code calls myMethod(), passing it two arguments. The first argument, i, is passed by value; when the method is called, the value of i is copied into the method's parameter j. If myMethod() changes the value of i, it's changing only its copy of the local variable.
http://localhost/java/javaref/exp/ch05_02.htm (5 of 8) [20/12/2001 11:02:17]
[Chapter 5] 5.2 Methods
In the same way, a copy of the reference to obj is placed into the reference variable o of myMethod(). Both references refer to the same object, of course, and any changes made through either reference affect the actual (single) object instance, but there are two copies of the pointer. If we change the value of, say, o.size, the change is visible through either reference. However, if myMethod() changes the reference o itself--to point to another object--it's affecting only its copy. In this sense, passing the reference is like passing a pointer in C and unlike passing by reference in C++. What if myMethod() needs to modify the calling method's notion of the obj reference as well (i.e., make obj point to a different object)? The easy way to do that is to wrap obj inside some kind of object. A good candidate would be to wrap the object up as the lone element in an array: SomeKindOfObject [] wrapper = { obj }; All parties could then refer to the object as wrapper[0] and would have the ability to change the reference. This is not very asthetically pleasing, but it does illustrate that what is needed is the level of indirection. Another possibility is to use this to pass a reference to the calling object. Let's look at another piece of code that could be from an implementation of a linked list: class Element { public Element nextElement; void addToList( List list ) { list.addToList( this ); } } class List { void addToList( Element element ) { ... element.nextElement = getNextElement(); } } Every element in a linked list contains a pointer to the next element in the list. In this code, the Element class represents one element; it includes a method for adding itself to the list. The List class itself contains a method for adding an arbitrary Element to the list. The method addToList() calls addToList() with the argument this (which is, of course, an Element). addToList() can use the this reference to modify the Element's nextElement instance variable. The same technique can be used in conjunction with interfaces to implement callbacks for arbitrary method invocations.
Method Overloading Method overloading is the ability to define multiple methods with the same name in a class; when the method is invoked, the compiler picks the correct one based on the arguments passed to the method. This implies, of course, that overloaded methods must have different numbers or types of arguments. In a later
http://localhost/java/javaref/exp/ch05_02.htm (6 of 8) [20/12/2001 11:02:17]
[Chapter 5] 5.2 Methods
section we'll look at method overriding, which occurs when we declare methods with identical signatures in different classes. Method overloading is a powerful and useful feature. It's another form of polymorphism (ad-hoc polymorphism). The idea is to create methods that act in the same way on different types of arguments and have what appears to be a single method that operates on any of the types. The Java PrintStream's print() method is a good example of method overloading in action. As you've probably deduced by now, you can print a string representation of just about anything using the expression: System.out.print( argument ) The variable out is a reference to an object (a PrintStream) that defines nine different versions of the print() method. They take, respectively, arguments of the following types: Object, String, char[], char, int, long, float, double, and boolean. class PrintStream { void print( Object arg ) { ... } void print( String arg ) { ... } void print( char [] arg ) { ... } ... } You can invoke the print() method with any of these types as an argument, and it's printed in an appropriate way. In a language without method overloading, this would require something more cumbersome, such as a separate method for printing each type of object. Then it would be your responsibility to remember what method to use for each data type. In the above example, print() has been overloaded to support two reference types: Object and String. What if we try to call print() with some other reference type? Say, perhaps, a Date object? The answer is that since Date is a subclass of Object, the Object method is selected. When there's not an exact type match, the compiler searches for an acceptable, assignable match. Since Date, like all classes, is a subclass of Object, a Date object can be assigned to a variable of type Object. It's therefore an acceptable match, and the Object method is selected. But what if there's more than one possible match? Say, for example, we tried to print a subclass of String called MyString. (Of course, the String class is final, so it can't be subclassed, but allow me this brief transgression for purposes of explanation.) MyString is assignable to either String or to Object. Here the compiler makes a determination as to which match is "better" and selects that method. In this case it's the String method. The intuitive explanation is that the String class is closer to MyString in the inheritance hierarchy. It is a more specific match. A more rigorous way of specifying it would be to say that a given method is more specific than another method with respect to some arguments it wants to accept if the argument types of the first method are all assignable to the argument types of the second method. In this case, the String method is more specific to a subclass of String than the Object method because type String is assignable to type Object. The reverse is obviously not true.
http://localhost/java/javaref/exp/ch05_02.htm (7 of 8) [20/12/2001 11:02:17]
[Chapter 5] 5.2 Methods
If you're paying close attention, you may have noticed I said that the compiler resolves overloaded methods. Method overloading is not something that happens at run-time; this is an important distinction. It means that the selected method is chosen once, when the code is compiled. Once the overloaded method is selected, the choice is fixed until the code is recompiled, even if the class containing the called method is later revised and an even more specific overloaded method is added. This is in contrast to overridden (virtual) methods, which are located at run-time and can be found even if they didn't exist when the calling class was compiled. We'll talk about method overriding later in the chapter. One last note about overloading. In earlier chapters, we've pointed out that Java doesn't support programmer-defined overloaded operators, and that + is the only system-defined overloaded operator. If you've been wondering what an overloaded operator is, I can finally clear up that mystery. In a language like C++, you can customize operators such as + and * to work with objects that you create. For example, you could create a class Complex that implements complex numbers, and then overload methods corresponding to + and * to add and multiply Complex objects. Some people argue that operator overloading makes for elegant and readable programs, while others say it's just "syntactic sugar" that makes for obfuscated code. The Java designers clearly espoused the later opinion when they chose not to support programmer-defined overloaded operators.
Classes
http://localhost/java/javaref/exp/ch05_02.htm (8 of 8) [20/12/2001 11:02:17]
Object Creation
[Chapter 5] 5.3 Object Creation
Chapter 5 Objects in Java
5.3 Object Creation Objects in Java are allocated from a system heap space, much like malloc'ed storage in C or C++. Unlike C or C++, however, we needn't manage that memory ourselves. Java takes care of memory allocation and deallocation for you. Java explicitly allocates storage for an object when you create it with the new keyword. More importantly, objects are removed by garbage collection when they're no longer referenced.
Constructors You allocate an object by specifying the new operator with an object constructor. A constructor is a special method with the same name as its class and no return type. It's called when a new class instance is created, which gives the class an opportunity to set up the object for use. Constructors, like other methods, can accept arguments and can be overloaded (they are not, however, inherited like other methods; we'll discuss inheritance later). class Date { long time; Date() { time = currentTime(); } Date( String date ) { time = parseDate( date ); } ... } In the above example, the class Date has two constructors. The first takes no arguments; it's known as the default constructor. Default constructors play a special role in that, if we don't define any constructors for a class, an empty default constructor is supplied for us. The default constructor is what gets called whenever you create an object by calling its constructor with no arguments. Here we have implemented the default constructor so that it sets the instance variable time by calling a hypothetical method: currentTime(), which resembles the functionality of the real java.util.Date class. The second constructor takes a String argument. Presumably, this String contains a string http://localhost/java/javaref/exp/ch05_03.htm (1 of 5) [20/12/2001 11:02:19]
[Chapter 5] 5.3 Object Creation
representation of the time that can be parsed to set the time variable. Given the constructors above, we create a Date object in the following ways: Date now = new Date(); Date christmas = new Date("Dec 25, 1997"); In each case, Java chooses the appropriate constructor at compile-time based on the rules for overloaded method selection. If we later remove all references to an allocated object, it'll be garbage collected, as we'll discuss shortly: christmas = null;
// fair game for the garbage collector
Setting the above reference to null means it's no longer pointing to the "Dec 25, 1997" object. Unless that object is referenced by another variable, it's now inaccessible and can be garbage collected. Actually, setting christmas to any other value would have the same results, but using the value null is a clear way to indicate that christmas no longer has a useful value. A few more notes about constructors. Constructors can't be abstract, synchronized, or final. Constructors can, however, be declared with the visibility modifiers public, private, or protected, to control their accessibility. We'll talk in detail about visibility modifiers later in the chapter.
Working with Overloaded Constructors A constructor can refer to another constructor in the same class or the immediate superclass using special forms of the this and super references. We'll discuss the first case here, and return to that of the superclass constructor again after we have talked more about subclassing and inheritance. A constructor can invoke another, overloaded constructor in its class using the reference this() with appropriate arguments to select the desired constructor. If a constructor calls another constructor, it must do so as its first statement (we'll explain why in a bit): class Car { String model; int doors; Car( String m, int d ) { model = m; doors = d; // other, complicated setup ... } Car( String m ) { this( m, 4 ); } ... http://localhost/java/javaref/exp/ch05_03.htm (2 of 5) [20/12/2001 11:02:19]
[Chapter 5] 5.3 Object Creation
} In the example above, the class Car has two overloaded constructors. The first, more explicit one, accepts arguments specifying the car's model and its number of doors and uses them to set up the object. We have also provided a simpler constructor that takes just the model as an argument and, in turn, calls the first constructor with a default value of four doors. The advantage of this approach is that you can have a single constructor do all the complicated setup work; other auxiliary constructors simply feed the appropriate arguments to that constructor. The important point is the call to this(), which must appear as the first statement our second constructor. The syntax is restricted in this way because there's a need to identify a clear chain of command in the calling of constructors. At one end of the chain, Java invokes the constructor of the superclass (if we don't do it explicitly) to ensure that inherited members are initialized properly before we proceed. There's also a point in the chain, just after the constructor of the superclass is invoked, where the initializers of the current class's instance variables are evaluated. Before that point, we can't even reference the instance variables of our class. We'll explain this situation again in complete detail after we have talked about inheritance. For now, all you need to know is that you can invoke a second constructor only as the first statement of another constructor. In addition, you can't do anything at that point other than pass along arguments of the current constructor. For example, the following is illegal and causes a compile-time error: Car( String m ) { int doors = determineDoors(); this( m, doors ); // Error } // Constructor call must be first statement The simple model name constructor can't do any additional setup before calling the more explicit constructor. It can't even refer to an instance member for a constant value: class Car { ... final int default_doors = 4; ... Car( String m ) { this( m, default_doors ); // Error // Referencing uninitialized variable } ... } The instance variable defaultDoors above is not initialized until a later point in the chain of constructor calls, so the compiler doesn't let us access it yet. Fortunately, we can solve this particular problem by making the identifier static as well: class Car { ... static final int DEFAULT_DOORS = 4; http://localhost/java/javaref/exp/ch05_03.htm (3 of 5) [20/12/2001 11:02:19]
[Chapter 5] 5.3 Object Creation
... Car( String m ) { this( m, DEFAULT_DOORS ); } ...
// Okay now
} The static members of our class have been initialized for some time (since the class was first loaded), so it's safe to access them.
Static and Nonstatic Code Blocks It's possible to declare a code block (some statements within curly braces) directly within the scope of a class. This code block doesn't belong to any method; instead, it's executed just once, at the time the object is constructed, or, in the case of a code block marked static, at the time the class is loaded. Nonstatic code blocks can be thought of as just an extension of instance variable initialization. They are called at the time the instance variable's initializers are evaluated (after superclass construction), in the textual order in which they appear in the class source. class MyClass { Properties myProps = new Properties(); // set up myProps { myProps.put("foo", "bar); myProps.put("boo", "gee); } int a = 5; ... You can use static code blocks to initialize static class members in this way. So the static members of a class can have complex initialization just like objects: class ColorWheel { static Hashtable colors = new Hashtable(); // set up colors static { colors.put("Red", Color.red ); colors.put("Green", Color.green ); colors.put("Blue", Color.blue ); ... } ... }
http://localhost/java/javaref/exp/ch05_03.htm (4 of 5) [20/12/2001 11:02:19]
[Chapter 5] 5.3 Object Creation
In the above example, the class ColorWheel provides a variable colors that maps the names of colors to Color objects in a Hashtable. The first time the class ColorWheel is referenced and loaded, the static components of ColorWheel are evaluated, in the order they appear in the source. In this case, the static code block simply adds elements to the colors Hashtable.
Methods
http://localhost/java/javaref/exp/ch05_03.htm (5 of 5) [20/12/2001 11:02:19]
Object Destruction
[Chapter 5] 5.4 Object Destruction
Chapter 5 Objects in Java
5.4 Object Destruction Now that we've seen how to create objects, it's time to talk about their destruction. If you're accustomed to programming in C or C++, you've probably spent time hunting down memory leaks in your code. Java takes care of object destruction for you; you don't have to worry about memory leaks, and you can concentrate on more important programming tasks.
Garbage Collection Java uses a technique known as garbage collection to remove objects that are no longer needed. The garbage collector is Java's grim reaper. It lingers, usually in a low priority thread, stalking objects and awaiting their demise. It finds them, watches them, and periodically counts references to them to see when their time has come. When all references to an object are gone, and it's no longer accessible, the garbage-collection mechanism reclaims it and returns the space to the available pool of resources. There are many different algorithms for garbage collection; the Java virtual machine architecture doesn't specify a particular scheme. It's worth noting, though, that current implementations of Java use a conservative mark and sweep system. Under this scheme, Java first walks through the tree of all accessible object references and marks them as alive. Then Java scans the heap looking for identifiable objects that aren't so marked. Java finds objects on the heap because they are stored in a characteristic way and have a particular signature of bits in their handles unlikely to be reproduced naturally. This kind of algorithm doesn't suffer from the problem of cyclic references, where detached objects can mutually reference each other and appear alive. By default, the Java virtual machine is configured to run the garbage collector in a low-priority thread, so that the garbage collector runs periodically to collect stray objects. With the java interpreter that comes with the JDK, you can turn off garbage collection by using the -noasyncgc command-line option. If you do this, the garbage collector will be run only if it's requested explicitly or if the Java virtual machine runs out of memory. A Java application can prompt the garbage collector to make a sweep explicitly by invoking the System.gc() method. An extremely time-sensitive Java application might use this to its advantage by running in an interpreter with asynchronous garbage collection deactivated and scheduling its own cleanup periods. This issue is necessarily implementation dependent, however, because on different platforms, garbage collection may be implemented in different ways. On some systems it may be continuously running in hardware. http://localhost/java/javaref/exp/ch05_04.htm (1 of 2) [20/12/2001 11:02:19]
[Chapter 5] 5.4 Object Destruction
Finalization Before a method is removed by garbage collection, its finalize() method is invoked to give it a last opportunity to clean up its act and free other kinds of resources it may be holding. While the garbage collector can reclaim memory resources, it may not take care of things like closing files and terminating network connections very gracefully or efficiently. That's what the finalize() method is for. An object's finalize() method is guaranteed to be called once and only once before the object is garbage collected. However there's no guarantee as to if or when that will happen. Garbage collection may never run on a system that is not short of memory. It is also interesting to note that finalization and collection occur in two distinct phases of the garbage-collection process. First items are finalized, then they are collected. It is therefore possible that finalization could (intentionally or unintentionally) create a lingering reference to the object in question, postponing its garbage collection. The object could, of course, be subject to collection later, if the reference goes away, but its finalize() method would not be called again. Lastly, unlike constructors, the finalize() methods of superclasses are not invoked automatically for you. If you need to chain together the finalization of your parent classes, you should invoke the finalize() method of your superclass, using super().finalize(). See the following sections on inheritance and overridden methods.
Object Creation
http://localhost/java/javaref/exp/ch05_04.htm (2 of 2) [20/12/2001 11:02:19]
Subclassing and Inheritance
[Chapter 5] 5.5 Subclassing and Inheritance
Chapter 5 Objects in Java
5.5 Subclassing and Inheritance Classes in Java exist in a class hierarchy. A class in Java can be declared as a subclass of another class using the extends keyword. A subclass inherits variables and methods from its superclass and uses them as if they're declared within the subclass itself: class Animal { float weight; ... void eat() { ... } ... } class Mammal extends Animal { int heartRate; // inherits weight ... void breathe() { ... } // inherits eat() } In the above example, an object of type Mammal has both the instance variable weight and the method eat(). They are inherited from Animal. A class can extend only one other class. To use the proper terminology, Java allows single inheritance of class implementation. Later we'll talk about interfaces, which take the place of multiple inheritance as it's primarily used in C++. A subclass can, of course, be further subclassed. Normally, subclassing specializes or refines a class by adding variables and methods:
http://localhost/java/javaref/exp/ch05_05.htm (1 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
class Cat extends Mammal { boolean longHair; // inherits weight and heartRate ... void purr() { ... } // inherits eat() and breathe() } The Cat class is a type of Mammal that is ultimately a type of Animal. Cat objects inherit all the characteristics of Mammal objects and, in turn, Animal objects. Cat also provides additional behavior in the form of the purr() method and the longHair variable. We can denote the class relationship in a diagram, as shown in Figure 5.3. Figure 5.3: A class hierarchy
A subclass inherits all members of its superclass not designated as private. As we'll discuss shortly, other levels of visibility affect what inherited members of the class can be seen from outside of the class and its subclasses, but at a minimum, a subclass always has the same set of visible members as its parent. For this reason, the type of a subclass can be considered a subtype of its parent, and instances of the subtype can be used anywhere instances of the supertype are allowed. For example: Cat simon = new Cat(); Animal creature = simon; The Cat simon in the above example can be assigned to the Animal type variable creature because Cat is a subtype of Animal.
Shadowed Variables In the previous section on methods, we saw that a local variable of the same name as an instance variable hides the instance variable. Similarly, an instance variable in a subclass can shadow an instance variable of the same name in its parent class, as shown in Figure 5.4.
http://localhost/java/javaref/exp/ch05_05.htm (2 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
Figure 5.4: The scope of shadowed variables
In Figure 5.4, the variable weight is declared in three places: as a local variable in the method foodConsumption() of the class Mammal, as an instance variable of the class Mammal, and as an instance variable of the class Animal. The actual variable selected depends on the scope in which we are working. In the above example, all variables were of the same type. About the only reason for declaring a variable with the same type in a subclass is to provide an alternate initializer. A more important use of shadowed variables involves changing their types. We could, for example, shadow an int variable with a double variable in a subclass that needs decimal values instead of integer values. We do this without changing the existing code because, as its name suggests, when we shadow variables, we don't replace them but instead mask them. Both variables still exist; methods of the superclass see the original variable, and methods of the subclass see the new version. The determination of what variables the various methods see is static and happens at compile-time. Here's a simple example: class IntegerCalculator { int sum; ... } class DecimalCalculator extends IntegerCalculator { double sum; ... } In this example, we override the instance variable sum to change its type from int to double.[3] Methods defined in the class IntegerCalculator see the integer variable sum, while methods
http://localhost/java/javaref/exp/ch05_05.htm (3 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
defined in DecimalCalculator see the decimal variable sum. However, both variables actually exist for a given instance of DecimalCalculator, and they can have independent values. In fact, any methods that DecimalCalculator inherits from IntegerCalculator actually see the integer variable sum. [3] Note that a better way to design our calculators would be to have an abstract Calculator class with two subclasses: IntegerCalculator and DecimalCalculator. Since both variables exist in DecimalCalculator, we need to reference the variable inherited from IntegerCalculator. We do that using the super reference: int s = super.sum Inside of DecimalCalculator, the super keyword used in this manner refers to the sum variable defined in the superclass. I'll explain the use of super more fully in a bit. Another important point about shadowed variables has to do with how they work when we refer to an object by way of a less derived type. For example, we can refer to a DecimalCalculator object as an IntegerCalculator. If we do so and then access the variable sum, we get the integer variable, not the decimal one: DecimalCalculator dc = new DecimalCalculator(); IntegerCalculator ic = dc; int s = ic.sum;
// Accesses IntegerCalculator sum
After this detailed explanation, you may still be wondering what shadowed variables are good for. Well, to be honest, the usefulness of shadowed variables is limited, but it's important to understand the concepts before we talk about doing the same thing with methods. We'll see a different and more dynamic type of behavior with method shadowing, or more correctly, method overriding.
Overriding Methods In a previous section, we saw we could declare overloaded methods (i.e., methods with the same name but a different number or type of arguments) within a class. Overloaded method selection works the way I described on all methods available to a class, including inherited ones. This means that a subclass can define some overloaded methods that augment the overloaded methods provided by a superclass. But a subclass does more than that; it can define a method that has exactly the same method signature (arguments and return type) as a method in its superclass. In that case, the method in the subclass overrides the method in the superclass and effectively replaces its implementation, as shown in Figure 5.5. Overriding methods to change the behavior of objects is another form of polymorphism (sub-type polymorphism): the one most people think of when they talk about the power of object-oriented languages. Figure 5.5: Method overriding http://localhost/java/javaref/exp/ch05_05.htm (4 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
In Figure 5.5, Mammal overrides the reproduce() method of Animal, perhaps to specialize the method for the peculiar behavior of Mammals giving live birth.[4] The Cat object's sleeping behavior is overridden to be different from that of a general Animal, perhaps to accommodate cat naps. The Cat class also adds the more unique behaviors of purring and hunting mice. [4] We'll ignore the platypus, which is an obscure nonovoviviparous mammal. From what you've seen so far, overridden methods probably look like they shadow methods in superclasses, just as variables do. But overridden methods are actually more powerful than that. An overridden method in Java acts like a virtual method in C++. When there are multiple implementations of a method in the inheritance hierarchy of an object, the one in the most derived class always overrides the others, even if we refer to the object by way of a less derived type. In other words, if we have a Cat instance assigned to a variable of the more general type Animal and we call its sleep() method, we get the sleep() method implemented in the Cat class, not the one in Animal: Cat simon = new Cat(); Animal creature = simon; creature.sleep();
// Accesses Cat sleep();
In other respects, the variable creature looks like an Animal. For example, access to a shadowed variable would find the implementation in the Animal class, not the Cat class. However, because methods are virtual, the appropriate method in the Cat class can be located, even though we are dealing with an Animal object. This means we can deal with specialized objects as if they were more general types of objects and still take advantage of their specialized implementations of behavior. Much of what you'll be doing when you're writing a Java applet or application is overriding methods defined by various classes in the Java API. For example, think back to the applets we developed in the tutorial in Chapter 2, A First Applet. Almost all of the methods we implemented for those applets were overridden methods. Recall that we created a subclass of Applet for each of the examples. Then we overrode various methods: init() set up our applet, mouseDrag() to handle mouse movement, and http://localhost/java/javaref/exp/ch05_05.htm (5 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
paint() to draw our applet. A common programming error in Java (at least for me) is to miss and accidentally overload a method when trying to override it. Any difference in the number or type of arguments or the return type of a method produces two overloaded methods instead of a single, overridden method. Make it a habit to look twice when overriding methods. Overridden methods and dynamic binding In a previous section, I mentioned that overloaded methods are selected by the compiler at compile-time. Overridden methods, on the other hand, are selected dynamically at run-time. Even if we create an instance of a subclass our code has never seen before (perhaps a new object type loaded from the network), any overridden methods that it contains will be located and invoked at run-time to replace those that existed when we last compiled our code. In contrast, if we load a new class that implements an additional, more specific overloaded method, our code will continue to use the implementation it discovered at compile-time. Another effect of this is that casting (i.e., explicitly telling the compiler to treat an object as one of its assignable types) affects the selection of overloaded methods, but not overridden methods. Static method binding Static methods do not belong to any object instance, they are accessed directly through a class name, so they are not dynamically selected at run-time like instance methods. That is why static methods are called "static"--they are always bound at compile time. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass. Dynamic method selection and peformance When Java has to dynamically search for overridden methods in subclasses, there's a small performance penalty. In languages like C++, the default is for methods to act like shadowed variables, so you have to explicitly declare the methods you want to be virtual. Java is more dynamic, and the default is for all instance methods to be virtual. In Java you can, however, go the other direction and explicitly declare that an instance method can't be overridden, so that it will not be subject to dynamic binding and will not suffer in terms of performance. This is done with the final modifier. We have seen final used with variables to effectively make them constants. When final is applied to a method, it means that that method can't be overridden (in some sense, its implementation is constant). final can also be applied to an entire class, which means the class can't be subclassed. Compiler optimiziations When javac, the Java compiler, is run with the -O switch, it performs certain optimizations. It can inline final methods to improve performance (while slightly increasing the size of the resulting class file). private methods, which are effectively final, can also be inlined, and final classes may also http://localhost/java/javaref/exp/ch05_05.htm (6 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
benefit from more powerful optimizations. Another kind of optimization allows you to include debugging code in your Java source without penalty. Java doesn't have a pre-processor, to explicitly control what source is included, but you can get some of the same effects by making a block of code conditional on a constant (i.e., static and final) variable. The Java compiler is smart enough to remove this code when it determines that it won't be called. For example: static final boolean DEBUG = false; ... static void debug (String message) { if (DEBUG) { System.err.println(message); // do other stuff ... } } If we compile the above code using the -O switch, the compiler will recognize that the condition on the DEBUG variable is always false, and the body of the debug() method will be optimized away. But that's not all--since debug() itself is also final it can be inlined, and an empty inlined method generates no code at all. So, when we compile with DEBUG set to false, calls to the debug() method will generate no residual code at all. Method selection revisited By now you should have a good, intuitive idea as to how methods are selected from the pool of potentially overloaded and overridden method names of a class. If, however, you are dying for a dry definition, I'll provide one now. If you are satisfied with your understanding, you may wish to skip this little exercise in logic. In a previous section, I offered an inductive rule for overloaded method resolution. It said that a method is considered more specific than another if its arguments are polymorphically assignable to the arguments of the second method. We can now expand this rule to include the resolution of overridden methods by adding the following condition: to be more specific than another method, the type of the class containing the method must also be assignable to the type of the class holding the second method. What does that mean? Well, the only classes whose types are assignable are classes in the same inheritance hierarchy. So, what we're talking about now is the set of all methods of the same name in a class or any of its parent or child classes. Since subclass types are assignable to superclass types, but not vice versa, the resolution is pushed, in the way that we expect, down the chain, towards the subclasses. This effectively adds a second dimension to the search, in which resolution is pushed down the inheritance tree towards more refined classes and, simultaneously, towards the most specific overloaded method within a given class. Exceptions and overridden methods
http://localhost/java/javaref/exp/ch05_05.htm (7 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
When we talked about exception handling in Chapter 4, The Java Language, there's one thing I didn't mention because it wouldn't have made sense then. An important restriction on overridden methods is that they must adhere to the throws clause of the parent method's signature. If an overridden method throws an exception, the exception must be of the type specified by the parent or a subtype of that exception. Because the exception can be a subtype of the one specified by the parent, the overridden method can refine the type of exception thrown to go along with its new behavior. For example: // A more refined exception class MeatInedibleException extends InedibleException { ... } class Animal { void eat( Food f ) throws InedibleException { ... } class Herbivore extends Animal { void eat( Food f ) throws InedibleException { if ( f instanceof Meat ) throw new MeatInedibleException(); .... } } In the example above, Animal specifies that it can throw an InedibleException from its eat() method. Herbivore is a subclass Animal, so it must be able to do this too. However, Herbivore's eat() method actually throws a more specific exception: MeatInedibleException. It can do this because MeatInedibleException is a subtype of InedibleException (remember that Exceptions are classes too). Our calling code's catch clause can therefore be more specific: Animal creature = ... try { creature.eat( food ); } catch ( MeatInedibleException ) { // creature can't eat this food because it's meat } catch ( InedibleException ) { // creature can't eat this food }
this and super The special references this and super allow you to refer to the members of the current object instance or those of the superclass, respectively. We have seen this used elsewhere to pass a reference to the current object and to refer to shadowed instance variables. The reference super does the same for the parents of a class. You can use it to refer to members of a superclass that have been shadowed or overridden. A common arrangement is for an overridden method in a subclass to do some preliminary work and then defer to the method of the superclass to finish the job.
http://localhost/java/javaref/exp/ch05_05.htm (8 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
class Animal { void eat( Food f ) throws InedibleException { // consume food } } class Herbivore extends Animal { void eat( Food f ) throws InedibleException { // check if edible ... super.eat( f ); } } In the above example, our Herbivore class overrides the Animal eat() method to first do some checking on the food object. After doing its job it simply calls the (otherwise overridden) implementation of eat() in its superclass, using super. super prompts a search for the method or variable to begin in the scope of the immediate superclass rather than the current class. The inherited method or variable found may reside in the immediate superclass, or in a more distant one. The usage of the super reference when applied to overridden methods of a superclass is special; it tells the method resolution system to stop the dynamic method search at the superclass, instead of in the most derived class (as it otherwise does). Without super, there would be no way to access overridden methods.
Casting As in C++, a cast explicitly tells the compiler to change the apparent type of an object reference. Unlike in C++, casts in Java are checked both at compile- and at run-time to make sure they are legal. Attempting to cast an object to an incompatible type at run-time results in a ClassCastException. Only casts between objects in the same inheritance hierarchy (and as we'll see later, to appropriate interfaces) are legal in Java and pass the scrutiny of the compiler and the run-time system. Casts in Java affect only the treatment of references; they never change the form of the actual object. This is an important rule to keep in mind. You never change the object pointed to by a reference by casting it; you change only the compiler's (or run-time system's) notion of it. A cast can be used to narrow the type of a reference--to make it more specific. Often, we'll do this when we have to retrieve an object from a more general type of collection or when it has been previously used as a less derived type. (The prototypical example is using an object in a Vector or Hashtable, as you'll see in Chapter 7, Basic Utility Classes.) Continuing with our Cat example: Animal creature = ... Cat simon = ... creature = simon;
// Okay
http://localhost/java/javaref/exp/ch05_05.htm (9 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
// simon = creature; simon = (Cat)creature;
// Compile time error, incompatible type // Okay
We can't reassign the reference in creature to the variable simon even though we know it holds an instance of a Cat (Simon). We have to perform the indicated cast. This is also called downcasting the reference. Note that an implicit cast was performed when we went the other way to widen the reference simon to type Animal during the first assignment. In this case, an explicit cast would have been legal, but superfluous. If casting seems complicated, here's a simple way to think about it. Basically, you can't lie about what an object is. If you have a Cat object, you can cast it to a less derived type (i.e., a type above it in the class hierarchy) such as Animal or even Object, since all Java classes are a subclass of Object. If you have an Object you know is a Cat, you can downcast the Object to be an Animal or a Cat. However, if you aren't sure if the Object is a Cat or a Dog at run-time, you should check it with instanceof before you perform the cast. If you get the cast wrong, Java throws a ClassCastException. As I mentioned earlier, casting can affect the selection of compile-time items like variables and overloaded methods, but not the selection of overridden methods. Figure 5.6 shows the difference. As shown in the top half of the diagram, casting the reference simon to type Animal (widening it) affects the selection of the shadowed variable weight within it. However, as the lower half of the diagram indicates, the cast doesn't affect the selection of the overridden method sleep(). Figure 5.6: Casting and its effect on method and variable selection
http://localhost/java/javaref/exp/ch05_05.htm (10 of 13) [20/12/2001 11:02:23]
[Chapter 5] 5.5 Subclassing and Inheritance
Using superclass constructors When we talked earlier about constructors, we discussed how the special statement this() invokes an overloaded constructor upon entry to another constructor. Similarly, the statement super() explicitly invokes the constructor of a superclass. Of course, we also talked about how Java makes a chain of constructor calls that includes the superclass's constructor, so why use super() explicitly? When Java makes an implicit call to the superclass constructor, it calls the default constructor. So, if we want to invoke a superclass constructor that takes arguments, we have to do so explicitly using super(). If we are going to call a superclass constructor with super(), it must be the first statement of our constructor, just as this() must be the first call we make in an overloaded constructor. Here's a simple example: class Person { Person ( String name ) { // setup based on name ... } ... } class Doctor extends Person { Doctor ( String name, String specialty ) { super( name ); // setup based on specialty ... } ... } In this example, we use super() to take advantage of the implementation of the superclass constructor and avoid duplicating the code to set up the object based on its name. In fact, because the class Person doesn't define a default (no arguments) constructor, we have no choice but to call super() explicitly. Otherwise, the compiler would complain that it couldn't find an appropriate default constructor to call. Said another way, if you subclass a class that has only constructors that take arguments, you have to invoke one of the superclass's constructors explicitly from your subclass constructor. Instance variables of the class are initialized upon return from the superclass constructor, whether that's due to an explicit call via super() or an implicit call to the default superclass constructor. We can now give the full story of how constructors are chained together and when instance variable initialization occurs. The rule has three parts and is applied repeatedly for each successive constructor invoked. ● If the first statement of a constructor is an ordinary statement--i.e., not a call to this() or super()--Java inserts an implicit call to super() to invoke the default constructor of the superclass. Upon returning from that call, Java initializes the instance variables of the current class
http://localhost/java/javaref/exp/ch05_05.htm (11 of 13) [20/12/2001 11:02:24]
[Chapter 5] 5.5 Subclassing and Inheritance
●
●
and proceeds to execute the statements of the current constructor. If the first statement of a constructor is a call to a superclass constructor via super(), Java invokes the selected superclass constructor. Upon its return, Java initializes the current class's instance variables and proceeds with the statements of the current constructor. If the first statement of a constructor is a call to an overloaded constructor via this(), Java invokes the selected constructor and upon its return simply proceeds with the statements of the current constructor. The call to the superclass's constructor has happened within the overloaded constructor, either explicitly or implicitly, so the initialization of instance variables has already occurred.
Abstract Methods and Classes As in C++, a method can be declared with the abstract modifier to indicate that it's just a prototype. An abstract method has no body; it's simply a signature definition followed by a semicolon. You can't directly use a class that contains an abstract method; you must instead create a subclass that implements the abstract method's body. abstract vaporMethod( String name ); In Java, a class that contains one or more abstract methods must be explicitly declared as an abstract class, also using the abstract modifier : abstract class vaporClass { ... abstract vaporMethod( String name ); ... } An abstract class can contain other, nonabstract methods and ordinary variable declarations; however, it can't be instantiated. To be used, it must be subclassed and its abstract methods must be overridden with methods that implement a body. Not all abstract methods have to be implemented in a single subclass, but a subclass that doesn't override all its superclass's abstract methods with actual, concrete implementations must also be declared abstract. Abstract classes provide a framework for classes that are to be "filled in" by the implementor. The java.io.InputStream class, for example, has a single abstract method called read(). Various subclasses of InputStream implement read() in their own ways to read from their own sources. The rest of the InputStream class, however, provides extended functionality built on the simple read() method. A subclass of InputStream inherits these nonabstract methods that provide functionality based on the simple read() method that the subclass implements. It's often desirable to specify only the prototypes for a whole set of methods and provide no implementation. In C++, this would be a purely abstract class. In Java, you should instead use an interface. An interface is like a purely abstract class; it defines a set of methods a class must implement (i.e., the behavior of a class). However, unlike in C++, a class in Java can simply say that it implements an interface and go about implementing those methods. As we'll discuss later, a class that http://localhost/java/javaref/exp/ch05_05.htm (12 of 13) [20/12/2001 11:02:24]
[Chapter 5] 5.5 Subclassing and Inheritance
implements an interface doesn't have to inherit from any particular part of the inheritance hierarchy or use a particular implementation.
Object Destruction
http://localhost/java/javaref/exp/ch05_05.htm (13 of 13) [20/12/2001 11:02:24]
Packages and Compilation Units
[Chapter 5] 5.6 Packages and Compilation Units
Chapter 5 Objects in Java
5.6 Packages and Compilation Units A package is a name for a group of related classes. In Chapter 3, Tools of the Trade, we discussed how Java uses package names to locate classes during compilation and at run-time. In this sense, packages are somewhat like libraries; they organize and manage sets of classes. Packages provide more than just source code-level organization though. They also create an additional level of scope for their classes and the variables and methods within them. We'll talk about the visibility of classes in this section. In the next section, we'll discuss the effect that packages have on access to variables and methods between classes.
Compilation Units The source code for a Java class is called a compilation unit. A compilation unit normally contains a single class definition and is named for that class. The definition of a class named MyClass, for instance, should appear in a file named MyClass.java. For most of us, a compilation unit is just a file with a .java extension, but in an integrated development environment, it could be an arbitrary entity. For brevity here, we'll refer to a compilation unit simply as a file. The division of classes into their own compilation units is important because, as described in Chapter 3, Tools of the Trade, the Java compiler assumes much of the responsibility of a make utility. The compiler relies on the names of source files to find and compile dependent classes. It's possible (and common) to put more than one class definition into a single file, but there are some restrictions we'll discuss shortly. A class is declared to belong to a particular package with the package statement. The package statement must appear as the first statement in a compilation unit. There can be only one package statement, and it applies to the entire file: package mytools.text; class TextComponent { ... } In the above example, the class TextComponent is placed in the package mytools.text.
http://localhost/java/javaref/exp/ch05_06.htm (1 of 4) [20/12/2001 11:02:24]
[Chapter 5] 5.6 Packages and Compilation Units
A Word About Package Names You should recall from Chapter 3, Tools of the Trade that package names are constructed in a hierarchical way, using a dot-separated naming convention. Package-name components construct a unique path for the compiler and run-time systems to locate files; however, they don't affect the contents directly in any other way. There is no such thing as a subpackage (the package name space is really flat, not hierarchical) and packages under a particular part of a package hierarchy are related only by association. For example, if we create another package called mytools.text.poetry (presumably for text classes specialized in some way to work with poetry), those classes would not be considered part of the mytools.text package and would have no special access to its members. In this sense, the package-naming convention can be misleading.
Class Visibility By default, a class is accessible only to other classes within its package. This means that the class TextComponent is available only to other classes in the mytools.text package. To be visible elsewhere, a class must be declared as public: package mytools.text; public class TextEditor { ... } The class TextEditor can now be referenced anywhere. There can be only a single public class defined in a compilation unit; the file must be named for that class. By hiding unimportant or extraneous classes, a package builds a subsystem that has a well-defined interface to the rest of the world. Public classes provide a facade for the operation of the system and the details of its inner workings can remain hidden, as shown in Figure 5.7. In this sense, packages hide classes in the way classes hide private members. Figure 5.7: Class visibility and packages
Figure 5.7 shows part of the the hypothetical mytools.text package. The classes TextArea and TextEditor are declared public and can be used elsewhere in an application. The class http://localhost/java/javaref/exp/ch05_06.htm (2 of 4) [20/12/2001 11:02:24]
[Chapter 5] 5.6 Packages and Compilation Units
TextComponent is part of the implementation of TextArea and is not accessible from outside of the package.
Importing Classes Classes within a package can refer to each other by their simple names. However, to locate a class in another package, we have to supply a qualifier. Continuing with the above example, an application refers directly to our editor class by its fully qualified name of mytools.text.TextEditor. But we'd quickly grow tired of typing such long class names, so Java gives us the import statement. One or more import statements can appear at the top of a compilation unit, beneath the package statement. The import statements list the full names of classes to be used within the file. Like a package statement, import statements apply to the entire compilation unit. Here's how you might use an import statement: package somewhere.else; import mytools.text.TextEditor; class MyClass { TextEditor editBoy; ... } As shown in the example above, once a class is imported, it can be referenced by its simple name throughout the code. It's also possible to import all of the classes in a package using the * notation: import mytools.text.*; Now we can refer to all public classes in the mytools.text package by their simple names. Obviously, there can be a problem with importing classes that have conflicting names. If two different packages contain classes that use the same name, you just have to fall back to using fully qualified names to refer to those classes. Other than the potential for naming conflicts, there's no penalty for importing classes. Java doesn't carry extra baggage into the compiled class files. In other words, Java class files don't contain other class definitions, they only reference them.
The Unnamed Package A class that is defined in a compilation unit that doesn't specify a package falls into the large, amorphous unnamed package. Classes in this nameless package can refer to each other by their simple names. Their path at compile- and run-time is considered to be the current directory, so package-less classes are useful for experimentation, testing, and brevity in providing examples for books about Java.
http://localhost/java/javaref/exp/ch05_06.htm (3 of 4) [20/12/2001 11:02:24]
[Chapter 5] 5.6 Packages and Compilation Units
Subclassing and Inheritance
http://localhost/java/javaref/exp/ch05_06.htm (4 of 4) [20/12/2001 11:02:24]
Variable and Method Visibility
[Chapter 5] 5.7 Variable and Method Visibility
Chapter 5 Objects in Java
5.7 Variable and Method Visibility One of the most important aspects of object-oriented design is data hiding, or encapsulation. By treating an object in some respects as a "black box" and ignoring the details of its implementation, we can write stronger, simpler code with components that can be easily reused.
Basic Access Modifiers By default, the variables and methods of a class are accessible to members of the class itself and other classes in the same package. To borrow from C++ terminology, classes in the same package are friendly. We'll call this the default level of visibility. As you'll see as we go on, the default visibility lies in the middle of the range of restrictiveness that can be specified. The modifiers public and private, on the other hand, define the extremes. As we mentioned earlier, methods and variables declared as private are accessible only within their class. At the other end of the spectrum, members declared as public are always accessible, from any class in any package. Of course, the class that contains the methods must also be public, as we just discussed. The public members of a class should define its most general functionality--what the black box is supposed to do. Figure 5.8 illustrates the three simplest levels of visibility. Figure 5.8: Private, default, protected, and public visibility
http://localhost/java/javaref/exp/ch05_07.htm (1 of 3) [20/12/2001 11:02:26]
[Chapter 5] 5.7 Variable and Method Visibility
Figure 5.8 continues with the example from the previous section. Public members in TextArea are accessible from anywhere. Private members are not visible from outside the class. The default visibility allows access by other classes in the package. The protected modifier allows special access permissions for subclasses. Contrary to how it might sound, protected is slightly less restrictive than the default level of accessibility. In addition to the default access afforded classes in the same package, protected members are visible to subclasses of the class, even if they are defined in a different package. If you are a C++ programmer and so used to more restrictive meanings for both the default and protected levels of access, this may rub you the wrong way. What was private protected? Early on, the Java language allowed for certain combinations of modifiers, one of which was private protected. The meaning of private protected was to limit visibility strictly to subclasses (and remove package access). This was later deemed somewhat inconsistent and overly complex and is no longer supported.[5] [5] The meaning of the protected modifier changed in the Beta2 release of Java, and the private protected combination appeared at the same time. They patched some potential security holes, but confused many people. Table 5.1 summarizes the levels of visibility available in Java; it runs generally from most restrictive to least. Methods and variables are always visible within a class, so the table doesn't address those: Table 5.1: Visibility Modifiers Modifier
Visibility None private none (default) Classes in the package protected Classes in package and subclasses inside or outside the package All classes public
Subclasses and Visibility There are two important (but unrelated) notes we need to add to the discussion of visibility with regards to class members in subclasses. First, when you override methods of a class in a subclass, it's not possible to reduce their visibility. While it is possible to take a private method of a class and override it to be public in a subclass, the reverse is not possible. This makes sense when you think about the fact that subtypes have to be usable as instances of their supertype (e.g., a Mammal is a type of Animal). If we could reduce the visibility of an overridden method, this would be a problem. However, we can reduce the visibility of a variable because it simply results in a shadowed variable. As with all shadowed variables, the two variables are distinct and can have separate visibilities in their different class forms. The second point is that protected variables of a class are visible to its subclasses, but unlike C++, http://localhost/java/javaref/exp/ch05_07.htm (2 of 3) [20/12/2001 11:02:26]
[Chapter 5] 5.7 Variable and Method Visibility
only in objects of the subclass's type or its subtypes. In other words, a subclass can see a protected variable from its superclass as an inherited variable, but it can't access the variable in a separate instance of the superclass itself. This can be confusing because often we forget that visibility modifiers don't resrtict between multiple instances of the same class in the same way that they do instances of different classes. Two instances of the same type of object can normally access all of each other's members, including private ones. Said another way: two instances of Cat can access all of each other's variables and methods (including private ones), but a Cat can't access a protected member in an instance of Animal, unless it can prove that the Animal is a Cat.
Packages and Compilation Units
http://localhost/java/javaref/exp/ch05_07.htm (3 of 3) [20/12/2001 11:02:26]
Interfaces
[Chapter 5] 5.8 Interfaces
Chapter 5 Objects in Java
5.8 Interfaces Interfaces are kind of like Boy Scout (or Girl Scout) merit badges. When a scout has learned to build a bird house, he can walk around wearing a little patch with a picture of one on his sleeve. This says to the world, "I know how to build a bird house." Similarly, an interface is a list of methods that define some set of behavior for an object. Any class that implements each of the methods listed in the interface can declare that it implements the interface and wear, as its merit badge, an extra type--the interface's type. Interface types act like class types. You can declare variables to be of an interface type, you can declare arguments of methods to accept interface types, and you can even specify that the return type of a method is an interface type. In each of these cases, what is meant is that any object that implements the interface (i.e., wears the right merit badge) can fill that spot. In this sense, interfaces are orthogonal to the class hierarchy. They cut across the boundaries of what kind of object an item is and deal with it only in terms of what it can do. A class implements as many interfaces as it desires. In this way, interfaces in Java replace the need for multiple inheritance (and all of its messy side effects). An interface looks like a purely abstract class (i.e., a class with only abstract methods). You define an interface with the interface keyword and list its methods with no bodies: interface Driveable { boolean startEngine(); void stopEngine(); float accelerate( float acc ); boolean turn( Direction dir ); } The example above defines an interface called Driveable with four methods. It's acceptable, but not necessary, to declare the methods in an interface with the abstract modifier, so we haven't used it here. Interfaces define capabilities, so it's common to name interfaces after their capabilities in a passive sense. "Driveable" is a good example; "runnable" and "updateable" would be two more. Any class that implements all the methods can then declare it implements the interface by using a special implements clause in its class definition: class Automobile implements Driveable { ... boolean startEngine() {
http://localhost/java/javaref/exp/ch05_08.htm (1 of 8) [20/12/2001 11:02:28]
[Chapter 5] 5.8 Interfaces
if ( notTooCold ) engineRunning = true; ... } void stopEngine() { engineRunning = false; } float accelerate( float acc ) { ... } boolean turn( Direction dir ) { ... } ... } The class Automobile implements the methods of the Driveable interface and declares itself Driveable using an implements clause. As shown in Figure 5.9, another class, such as LawnMower, can also implement the Driveable interface. The figure illustrates the Driveable interface being implemented by two different classes. While it's possible that both Automobile and Lawnmower could derive from some primitive kind of vehicle, they don't have to in this scenario. This is a significant advantage of interfaces over standard multiple inheritance as implemented in C++. Figure 5.9: Implementing the Driveable interface
http://localhost/java/javaref/exp/ch05_08.htm (2 of 8) [20/12/2001 11:02:28]
[Chapter 5] 5.8 Interfaces
After declaring the interface, we have a new type, Driveable. We can declare variables of type Driveable and assign them any instance of a Driveable object: Automobile auto = new Automobile(); Lawnmower mower = new Lawnmower(); Driveable vehicle; vehicle = auto; vehicle.startEngine(); vehicle.stopEngine(); ... vehicle = mower; vehicle.startEngine(); vehicle.stopEngine(); Both Automobile and Lawnmower implement Driveable and can be considered of that type.
Interfaces as Callbacks Interfaces can be used to implement callbacks in Java. A callback is a situation where you'd like to pass a reference to some behavior and have another object invoke it later. In C or C++, this is prime territory for function pointers; in Java, we'll use interfaces instead. Consider two classes: a TickerTape class that displays data and a TextSource class that provides an information feed. We'd like our TextSource to send any new text data. We could have TextSource store a reference to a TickerTape object, but then we could never use our TextSource to send data to any other kind of object. Instead, we'd have to proliferate subclasses of TextSource that dealt with different types. A more elegant solution is to have TextSource store a reference to an interface type, http://localhost/java/javaref/exp/ch05_08.htm (3 of 8) [20/12/2001 11:02:28]
[Chapter 5] 5.8 Interfaces
TextUpdateable: interface TextUpdateable { receiveText( String text ); } class TickerTape implements TextUpdateable { TextSource source; init() { source = new TextSource( this ); ... } public receiveText( String text ) { scrollText( text ): } ... } class TextSource { TextUpdateable receiver; TextSource( TextUpdateable r ) { receiver = r; } private sendText( String s ) { receiver.receiveText( s ); } ... } The only thing TextSource really cares about is finding the right method to invoke to send text. Thus, we can list that method in an interface called TextUpdateable and have our TickerTape implement the interface. A TickerTape object can then be used anywhere we need something of the type TextUpdateable. In this case, the TextSource constructor takes a TextUpdateable object and stores the reference in an instance variable of type TextUpdateable. Our TickerTape object simply passes a reference to itself as the callback for text updates, and the source can invoke its receiveText() method as necessary.
Interface Variables Although interfaces allow us to specify behavior without implementation, there's one exception. An interface can contain constant variable identifiers; these identifiers appear in any class that implements the interface. This functionality allows for predefined parameters that can be used with the methods:
http://localhost/java/javaref/exp/ch05_08.htm (4 of 8) [20/12/2001 11:02:28]
[Chapter 5] 5.8 Interfaces
interface Scaleable { static final int BIG = 0, MEDIUM = 1, SMALL = 2; void setScale( int size ); } The Scaleable interface defines three integers: BIG, MEDIUM, and SMALL. All variables defined in interfaces are implicitly final and static; we don't have to use the modifiers here but, for clarity, we recommend you do so. A class that implements Scaleable sees these variables: class Box implements Scaleable { void setScale( int size ) { switch( size ) { case BIG: ... case MEDIUM: ... case SMALL: ... } } ... } Empty Interfaces Sometimes, interfaces are created just to hold constants; anyone who implements the interfaces can see the constant names, much as if they were included by a C/C++ include file. This is a somewhat degenerate, but acceptable use of interfaces. Sometimes completely empty interfaces will be used to serve as a marker that a class has some special property. The java.io.Serializeable interface is a good example (See Chapter 8). Classes that implement Serializable don't add any methods or variables. Their additional type simply identifies them to Java as classes that want to be able to be serialized.
Interfaces and Packages Interfaces behave like classes within packages. An interface can be declared public to make it visible outside of its package. Under the default visibility, an interface is visible only inside of its package. There can be only one public interface declared in a compilation unit.
http://localhost/java/javaref/exp/ch05_08.htm (5 of 8) [20/12/2001 11:02:28]
[Chapter 5] 5.8 Interfaces
Subinterfaces An interface can extend another interface, just as a class can extend another class. Such an interface is called a subinterface: interface DynamicallyScaleable extends Scaleable { void changeScale( int size ); } The interface DynamicallyScaleable extends our previous Scaleable interface and adds an additional method. A class that implements DynamicallyScaleable must implement all methods of both interfaces. Interfaces can't specify that they implement other interfaces, instead they are allowed to extend more than one interface. (This is multiple inheritence for interfaces). More than one superinterface can be specified with the comma operator: interface DynamicallyScaleable extends Scaleable, SomethingElseable { ...
Inside Arrays At the end of Chapter 4, The Java Language, I mentioned that arrays have a place in the Java class hierarchy, but I didn't give you any details. Now that we've discussed the object-oriented aspects of Java, I can give you the whole story. Array classes live in a parallel Java class hierarchy under the Object class. If a class is a direct subclass of Object, then an array class for that base type also exists as a direct subclass of Object. Arrays of more derived classes are subclasses of the corresponding array classes. For example, consider the following class types: class Animal { ... } class Bird extends Animal { ... } class Penguin extends Bird { ... } Figure 5.10 illustrates the class hierarchy for arrays of these classes. Figure 5.10: Arrays in the Java class hierarchy
http://localhost/java/javaref/exp/ch05_08.htm (6 of 8) [20/12/2001 11:02:28]
[Chapter 5] 5.8 Interfaces
Arrays of the same dimension are related to one another in the same manner as their base type classes. In our example, Bird is a subclass of Animal, which means that the Bird[] type is a subtype of Animal[]. In the same way a Bird object can be used in place of an Animal object, a Bird[] array can be assigned to an Animal[] array: Animal [][] animals; Bird [][] birds = new Bird [10][10]; birds[0][0] = new Bird(); // make animals and birds reference the same array object animals = birds; System.out.println( animals[0][0] ); // prints Bird Because arrays are part of the class hierarchy, we can use instanceof to check the type of an array: if ( birds instanceof Animal[][] )
// yes
An array is a subtype of Object and can therefore be assigned to Object type variables: Object something; something = animals; Since Java knows the actual type of all objects, you can also cast back if appropriate: animals = (Animal [][])something; Under unusual circumstances, Java may not be able to check the types of objects you place into arrays at compile-time. In those cases, it's possible to receive an ArrayStoreException if you try to assign the wrong type of object to an array element. Consider the following: class Dog { ... } class Poodle extends Dog { ... } http://localhost/java/javaref/exp/ch05_08.htm (7 of 8) [20/12/2001 11:02:28]
[Chapter 5] 5.8 Interfaces
class Chihuahua extends Dog { ... } Dog [] dogs; Poodle [] poodles = new Poodle [10]; dogs = poodles; dogs[3] = new Chihuahua();
// Run-time error, ArrayStoreException
Both Poodle and Chihuahua are subclasses of Dog, so an array of Poodle objects can therefore be assigned to an array of Dog objects, as I described previously. The problem is that an object assignable to an element of an array of type Dog[] may not be assignable to an element of an array of type Poodle. A Chihuahua object, for instance, can be assigned to a Dog element because it's a subtype of Dog, but not to a Poodle element.[6] [6] In some sense this could be considered a tiny hole in the Java type system. It doesn't occur elsewhere in Java, only with arrays. This is because array objects exhibit covariance in overriding their assignment and extraction methods. Covariance allows array subclasses to override methods with arguments or return values that are subtypes of the overridden methods, where the methods would normally be overloaded or prohibited. This allows array subclasses to operate on their base types with type safety, but also means that subclasses have different capabilities than their parents, leading to the problem shown above.
Variable and Method Visibility
http://localhost/java/javaref/exp/ch05_08.htm (8 of 8) [20/12/2001 11:02:28]
Inner Classes
[Chapter 5] 5.9 Inner Classes
Chapter 5 Objects in Java
5.9 Inner Classes We've left out something important in our discussion of Java classes so far: a large and relatively recent heap of syntactic sugar called inner classes. Simply put, classes in Java can be declared at any level of scope. That is, you can declare a class within any set of curly braces (that is, almost anywhere that you could put any other Java statement) and its visibility is limited to that scope in the same way that the name of a variable or method would be. Inner classes are a powerful and aesthetically pleasing facility for structuring code.[7] Their even sweeter cousins, anonymous inner classes, are another powerful shorthand that make it seem like you can create classes dynamically within Java's statically typed environment. [7] The implementation of Java's inner classes draws on experience from the language Beta, and other block structured languages such as Pascal, and Scheme. However, if you delve into the inner workings of Java, inner classes are not quite as aesthetically pleasing or dynamic. We said that they are syntactic sugar; by this we mean that they let you leverage the compiler by writing a few lines of code that trigger a lot of behind-the-scenes work somewhere between the compiler's front end and the byte-code. Inner classes rely on code-generation; they are a feature of the Java language, but not of the Java virtual machine. As a programmer you may never need be aware of this; you can simply rely on inner classes like any other language construct. However, you should know a little about how inner classes work, to better understand the results and a few potential side effects. To this point, all of our classes have been top level classes. We have declared them, free standing, at the package level. Inner classes are essentially nested classes, like this: Class Animal { Class Brain { ... } } Here the class Brain is an inner class: it is a class declared inside the scope of class Animal. Although the details of what that means require a fair bit of explanation, we'll start by saying that the Java language tries to make the meaning, as much as possible, the same as for the other Java entities (methods and variables) living at that level of scope. For example, let's add a method to the Animal class: Class Animal { Class Brain { ... } void performBehavior() { ... }
http://localhost/java/javaref/exp/ch05_09.htm (1 of 8) [20/12/2001 11:02:30]
[Chapter 5] 5.9 Inner Classes
} Both the inner class Brain and the method performBehavior() are within the scope of Animal. Therefore, anywhere within Animal we can refer to Brain and performBehavior() directly, by name. Within Animal we can call the constructor for Brain (new Brain()) to get a Brain object, or invoke performBehavior() to carry out that method's function. But neither Brain nor performBehavior() are accessible outside of the class Animal without some additional qualification. Within the body of the Brain class and the body of the performBehavior() method, we have direct access to all of the other methods and variables of the Animal class. So, just as the performBehavior() method could work with the Brain class and create instances of Brain, code within the Brain class can invoke the performBehavior() method of Animal as well as work with any other methods and variables declared in Animal. That last bit has important consequences. From within Brain we can invoke the method performBehavior(); that is--from within an instance of Brain we can invoke the performBehavior() method of an instance of Animal. Well, which instance of Animal? If we have several Animal objects around (say, a few Cats and Dogs), we need to know whose performBehavior() method we are calling. What does it mean for a class definition to be "inside" another class definition? The answer is that a Brain object always lives within a single instance of Animal: the one that it was told about when it was created. We'll call the object that contains any instance of Brain its enclosing instance. A Brain object cannot live outside of an enclosing instance of an Animal object. Anywhere you see an instance of Brain, it will be tethered to an instance of Animal. Although it is possible to construct a Brain object from elsewhere (i.e., another class), Brain always requires an enclosing instance of Animal to "hold" it. We'll also say now that if Brain is to be referred to from outside of Animal it acts something like an Animal.Brain class. And just as with the performBehavior() method, modifiers can be applied to restrict its visibility. There is even an interpretation of the static modifier, which we'll talk about a bit later. However, the details are somewhat boring and not immediately useful, so you should consult a full language reference for more info (like O'Reilly's Java Language Reference, Second Edition). So before we get too far afield, let's turn to a more compelling example. A particularly important use of inner classes is to make adapter classes. An adapter class is a "helper" class that ties one class to another in a very specific way. Using adapter classes you can write your classes more naturally, without having to anticipate every conceivable user's needs in advance. Instead, you provide adapter classes that marry your class to a particular interface. As an example, let's say that we have an EmployeeList object: public class EmployeeList { private Employee [] employees = ... ; ... } EmployeeList holds information about a set of employees, representing some view of our database. Let's say that we would like to have EmployeeList provide its elements as an enumeration (see Chapter 7, Basic Utility Classes). An enumeration is a simple interface to a set of objects that looks like this: // the java.util.Enumeration interface public interface Enumeration { boolean hasMoreElements(); Object nextElement(); }
http://localhost/java/javaref/exp/ch05_09.htm (2 of 8) [20/12/2001 11:02:30]
[Chapter 5] 5.9 Inner Classes
It lets us iterate through its elements, asking for the next one and testing to see if more remain. The enumeration is a good candidate for an adapter class because it is an interface that our EmployeeList can't readily implement itself. That's because an enumeration is a "one way", disposable view of our data. It isn't intended to be reset and used again, and therefore should be kept separate from the EmployeeList itself. This is crying out for a simple class to provide the enumeration capability. But what should that class look like? Well, before we knew about inner classes, our only recourse would have been to make a new "top level" class. We would probably feel obliged to call it EmployeeListEnumeration: class EmployeeListEnumeration implements Enumeration { // lots of knowledge about EmployeeList ... } Here we have a comment representing the machinery that the EmployeeListEnumeration requires. Think for just a second about what you'd have to do to implement that machinery. The resulting class would be completely coupled to the EmployeeList, and unusable in other situations. Worse, to function it must have access to the inner workings of EmployeeList. We would have to allow EmployeeListEnumeration access to the private array in EmployeeList, exposing this data more widely than it should be. This is less than ideal. This sounds like a job for inner classes. We already said that EmployeeListEnumeration was useless without the EmployeeList; this sounds a lot like the "lives inside" relationship we described earlier. Furthermore, an inner class lets us avoid the encapsulation problem, because it can access all the members of its enclosing instance. Therefore, if we use an inner class to implement the enumeration, the array employees can remain private, invisible outside the EmployeeList. So let's just shove that helper class inside the scope of our EmployeeList: public class EmployeeList { private Employee [] employees = ... ; // ... class Enumerator implements java.util.Enumeration { int element = 0; boolean hasMoreElements() { return element < employees.length ; } Object nextElement() { if ( hasMoreElements() ) return employees[ element++ ]; else throw NoSuchElementException(); } } } Now EmployeeList can provide an accessor method like the following to let other classes work with the list: ... Enumeration getEnumeration() { http://localhost/java/javaref/exp/ch05_09.htm (3 of 8) [20/12/2001 11:02:30]
[Chapter 5] 5.9 Inner Classes
return new Enumerator(); } One effect of the move is that we are free to be a little more familiar in the naming of our enumeration class. Since it is no longer a top level class, we can give it a name that is only appropriate within the EmployeeList. In this case, we've named it Enumerator to emphasize what it does--but we don't need a name like EmployeeEnumerator that shows the relationship to the EmployeeList class, because that's implicit. We've also filled in the guts of the Enumerator class. As you can see, now that it is inside the scope of EmployeeList, Enumerator has direct access to its private members, so it can directly access the employees array. This greatly simplifies the code and maintains the compile-time safety. Before we move on, we should note that inner classes can have constructors, even though we didn't need one in this example. They are in all respects real classes.
Inner Classes within methods Inner classes may also be declared withing the body of a method. Returning to the Animal class, we could put Brain inside the performBehavior() method if we decided that the class was only useful inside of that method. Class Animal { void performBehavior() { Class Brain { ... } } } In this situation, the rules governing what Brain can see are the same as in our earlier example. The body of Brain can see anything in the scope of performBehavior() and, of course, above it. This includes local variables of performBehavior(), and its arguments. This raises a few questions. performBehavior() is a method, and methods have limited lifetimes. When they exit their local variables normally disappear into the stacky abyss. But an instance of Brain (like any object) lives on as long as it is referenced. So Java makes sure that any local variables used by instances of Brain created within an invocation of performBehavior() also live on. Furthermore, all of the instances of Brain that we make within a single invocation of performBehavior() will see the same local variables. Static Inner Classes We mentioned earlier that the inner class Brain of the class Animal could in some ways be considered an Animal.Brain class. That is, it is possible to work with a Brain from outside the Animal class, using just such a qualified name: Animal.Brain. But given that our Animal.Brain class always requires an instance of an Animal as its enclosing instance, some explicit setup is needed.[8] [8] Specifically, we would have to follow a design pattern and pass a reference to the enclosing instance of Animal into the Animal.Brain constructor. See a language reference for more information. We don't expect you to run into this situation very often. But there is another situation where we might use inner classes by name. An inner class that lives within the body of a top level class (not within a method or another inner class) can be declared static. For example:
http://localhost/java/javaref/exp/ch05_09.htm (4 of 8) [20/12/2001 11:02:30]
[Chapter 5] 5.9 Inner Classes
class Animal { static class MigrationPattern { ... } ... } A static inner class such as this acts just like a new top level class called Animal.MigrationPattern; we can use it without regard to any enclosing instances. Although this seems strange, it is not inconsistent since a static member never has an object instance associated with it. The requirement that the inner class be defined directly inside a top level class ensures that an enclosing instance won't be needed. If we have permission, we can create an instance of the class using the qualified name: Animal.MigrationPattern stlToSanFrancisco = new Animal.MigrationPattern(); As you see, the effect is that Animal acts something like a mini-package, holding the MigrationPattern class. We can use all of the standard visibility modifiers on inner classes, so a static inner class could be private, protected, default, or publicly visible. Anonymous Inner Classes Now we get to the best part. As a general rule, the more deeply encapsulated and limited in scope our classes are, the more freedom we have in naming them. We saw this in our enumeration example. This is not just a purely aesthetic issue. Naming is an important part of writing readable and maintainable code. We generally want to give things the most concise and meaningful names possible. A corollary to this is that we prefer to avoid doling out names for purely ephemeral objects that are only going to be used once. Anonymous inner classes are an extension of the syntax of the new operation. When you create an anonymous inner class, you combine the class's declaration with the allocation of an instance of that class (much like the way you can declare a variable of the type of an un-named structure in C). After the new operator, you specify either the name of a class or an interface, followed by a class body. The class body becomes an inner class, which either extends the specified class or, in the case of an interface, is expected to implement the specified interface. A single instance of the class is created and returned as the value. For example, we could do away with the declaration of the Enumerator class in the EmployeeList example by using an anonymous inner class in the getEnumeration() method: ... Enumeration getEnumeration() { return new Enumeration() { int element = 0; boolean hasMoreElements() { return element < employees.length ; } Object nextElement() { if ( hasMoreElements() ) return employees[ element++ ]; else
http://localhost/java/javaref/exp/ch05_09.htm (5 of 8) [20/12/2001 11:02:30]
[Chapter 5] 5.9 Inner Classes
throw NoSuchElementException(); } }; } Here we have simply moved the guts of Enumerator into the body of an anonymous inner class. The call to new implicitly constructs the class and returns an instance of the class as its result. Note the extent of the curly braces, and the semi-colon at the end. It is a single statement. But the code above certainly does not improve readability. Inner classes are best used when you want to implement a few lines of code, where the verbiage and conspicuousness of declaring a separate class detracts from the task at hand. Here's a better example: Suppose that we want to start a new thread to execute the performBehavior() method of our Animal: new Thread ( new Runnable() { public void run() { performBehavior(); } ).start();
}
Here we have gone over to the terse side. We've allocated and started a new Thread, providing an anonymous inner class that implements the Runnable interface by calling our performBehavior() method. The effect is similar to using a method pointer in some other language; the inner class effectively substitutes the method we want called (performBehavior()) for the method the system wants to call (run()). However, the inner class allows the compiler to check type consistency, which would be difficult (if not impossible) with a true method pointer. At the same time, our anonymous adapter class with its three lines of code is much more efficient and readable than creating a new, top level adapter class named AnimalBehaviorThreadAdapter. While we're getting a bit ahead of the story, anonymous adapter classes are a perfect fit for event handling (which we'll cover fully in Chapter 10, Understand the Abstract Windowing Toolkit). Skipping a lot of explanation, let's say you want the method handleClicks() to be called whenever the user clicks the mouse. You would write code like this: addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { handleClicks(e); } }); In this case, the anonymous class extends the AWT's MouseAdapter class, by overriding its mouseClicked() method to call our method. A lot is going on in a very small space, but the result is clean, readable code. You get to assign method names that are meaningful to you, while allowing Java to do its job of type checking.
this and scoping Sometimes an inner class may want to get a handle on its "parent" enclosing instance. It might want to pass a reference to its parent, or to refer to one of the parent's variables or methods that has been hidden by one of its own. For example: class Animal { int size; class Brain { int size; }
http://localhost/java/javaref/exp/ch05_09.htm (6 of 8) [20/12/2001 11:02:30]
[Chapter 5] 5.9 Inner Classes
} Here, as far as Brain is concerned, the variable size in Animal is hidden by its own version. Normally an object refers to itself using the special this reference (implicitly or explicitly). But what is the meaning of this for an object with one or more enclosing instances? The answer is that an inner class has multiple this references. You can specify which this you want by prepending the name of the class. So, for instance (no pun intended), we can get a reference to our Animal from within Brain like so: ... class Brain { Animal ourAnimal = Animal.this; ... Similarly, we could refer to the size variable in Animal: ... class Brain { int animalSize = Animal.this.size; ...
How do inner classes really work? Finally, we'll get our hands dirty and take a look at what's really going on when we use an inner class. We've said that the compiler is doing all of the things that we had hoped to forget about. Let's see what's actually happening. Try compiling our simple example: class Animal { class Brain { } } (Oh, come on, do it...) What you'll find is that the compiler generates two .class files: Animal.class Animal$Brain.class The second file is the class file for our inner class. Yes, as we feared, inner classes are really just compiler magic. The compiler has created the inner class for us as a normal, top level class and named it by combining the class names with a dollar sign. The dollar sign is a valid character in class names, but is intended for use only by automated tools in this way. (Please don't start naming your classes with dollar signs). Had our class been more deeply nested, the intervening inner class names would have been attached in the same way to generate a unique top level name. Now take a look at it using the javap utility: # javap 'Animal$Brain' class Animal$Brain extends java.lang.Object { Animal$Brain(Animal);
http://localhost/java/javaref/exp/ch05_09.htm (7 of 8) [20/12/2001 11:02:30]
[Chapter 5] 5.9 Inner Classes
} You'll see that the compiler has given our inner class a constructor that takes a reference to an Animal as an argument. This is how the real inner class gets the handle on its enclosing instance. The worst thing about these additional class files is that you need to know they are there. Utilities like jar don't automatically find them; when you are invoking a utility like jar, you need to specify these files explicitly, or use a wild card that finds them.
Security Implications Given what we just saw above--that the inner class really does exist as an automatically generated top level class--how does it get access to private variables? The answer, unfortunately, is that the compiler is forced to break the encapsulation of your object and insert accessor methods so that the inner class can reach them. The accessor methods will be given package level access, so your object is still safe within its package walls, but it is conceivable that this difference could be meaningful if people were allowed to create new classes within your package. The visibility modifiers on inner classes also have some problems. Current implementations of the virtual machine do not implement the notion of a private or protected class within a package, so giving your inner class anything other than public or default visibility is only a compile-time guarantee. It is difficult to conceive of how these security issues could be abused, but it is interesting to note that Java is straining a bit to stay within its original design.
Interfaces
http://localhost/java/javaref/exp/ch05_09.htm (8 of 8) [20/12/2001 11:02:30]
The Object and Class Classes
[Chapter 5] 5.10 The Object and Class Classes
Chapter 5 Objects in Java
5.10 The Object and Class Classes java.lang.Object is the mother of all objects; it's the primordial class from which all other classes are ultimately derived. Methods defined in Object are therefore very important because they appear in every instance of any class, throughout all of Java. At last count, there were nine public methods in Object. Five of these are versions of wait() and notify() that are used to synchronize threads on object instances, as we'll discuss in Chapter 6, Threads. The remaining four methods are used for basic comparison, conversion, and administration. Every object has a toString() method that is called when it's to be represented as a text value. PrintStream objects use toString() to print data, as discussed in Chapter 8, Input/Output Facilities. toString() is also used when an object is referenced in a string concatenation. Here are some examples: MyObj myObject = new MyObj(); Answer theAnswer = new Answer(); System.out.println( myObject ); String s = "The answer is: " + theAnswer ; To be friendly, a new kind of object should override toString() and implement its own version that provides appropriate printing functionality. Two other methods, equals() and hashCode(), may also require specialization when you create a new class.
Equality equals() compares whether two objects are equivalent. Precisely what that means for a particular class is something that you'll have to decide for yourself. Two String objects, for example, are considered equivalent if they hold precisely the same characters in the same sequence: String userName = "Joe"; ... if ( userName.equals( suspectName ) ) arrest( userName );
http://localhost/java/javaref/exp/ch05_10.htm (1 of 4) [20/12/2001 11:02:31]
[Chapter 5] 5.10 The Object and Class Classes
Note that using equals() is *not* the same as: // if ( userName == suspectName )
// Wrong!
The above code tests to see if the two String objects are the same object, which is sufficient but not necessary for them to be equivalent objects. A class should override the equals() method if it needs to implement its own notion of equality. If you have no need to compare objects of a particular class, you don't need to override equals(). Watch out for accidentally overloading equals() when you mean to override it. equals() takes an Object as an argument and returns a boolean value. While you'll probably want to check only if an object is equivalent to an object of its own type, in order to properly override equals(), the method should accept a generic Object as its argument. Here's an example of implementing equals(): class Sneakers extends Shoes { public boolean equals( Object arg ) { if ( (arg != null) && (arg instanceof Sneakers) ) { // compare arg with this object to check equivalence // If comparison is okay... return true; } return false; } ... } A Sneakers object can now be properly compared by any current or future Java classes. If we had instead used a Sneakers type object as the argument to equals(), all would be well for classes that reference our objects as Sneakers, but methods that simply use Shoes would not see the overloaded method and would compare Sneakers against other Sneakers improperly.
Hashcodes The hashCode() method returns an integer that is a hashcode for a class instance. A hashcode is like a signature for an object; it's an arbitrary-looking identifying number that is (with important exceptions) generally different for different instances of the class. Hashcodes are used in the process of storing objects in a Hashtable, or a similar kind of collection. The hashcode is essentially an index into the collection. See Chapter 7, Basic Utility Classes for a complete discussion of Hashtable objects and hashcodes. The default implementation of hashCode() in Object assigns each object instance a unique number to be used as a hashcode. If you don't override this method when you create a new class, each instance of the class will have a unique hashcode. This is sufficient for most objects. However, if the class has a notion of equivalent objects, then you should probably override hashCode() so that equivalent objects are given the same hashcode.
http://localhost/java/javaref/exp/ch05_10.htm (2 of 4) [20/12/2001 11:02:31]
[Chapter 5] 5.10 The Object and Class Classes
java.lang.Class The last method of Object we need to discuss is getClass(). This method returns a reference to the Class object that produced the object instance. A good measure of the complexity of an object-oriented language is the degree of abstraction of its class structures. We know that every object in Java is an instance of a class, but what exactly is a class? In C++, objects are formulated by and instantiated from classes, but classes are really just artifacts of the compiler. Thus, you see only classes mentioned in C++ source code, not at run-time. By comparison, classes in Smalltalk are real, run-time entities in the language that are themselves described by "meta-classes" and "meta-class classes." Java strikes a happy medium between these two languages with what is, effectively, a two-tiered system that uses Class objects. Classes in Java source code are represented at run-time by instances of the java.lang.Class class. There's a Class object for every class you use; this Class object is responsible for producing instances for its class. This may sound overwhelming, but you don't have to worry about any of it unless you are interested in loading new kinds of classes dynamically at run-time. We can get the Class associated with a particular object with the getClass() method: String myString = "Foo!" Class c = myString.getClass(); We can also get the Class reference for a particular class statically, using the special .class notation: Class c = String.class; The .class reference looks like a static field that exists in every class. However, it is really resolved by the compiler. One thing we can do with the Class object is to ask for the name of the object's class: String s = "Boofa!"; Class strClass = s.getClass(); System.out.println( strClass.getName() ); // prints "java.lang.String" Another thing that we can do with a Class is to ask it to produce a new instance of its type of object. Continuing with the above example: try { String s2 = (String)strClass.newInstance(); } catch ( InstantiationException e ) { ... } catch ( IllegalAccessException e ) { ... } newInstance() has a return type of Object, so we have to cast it to a reference of the appropriate type. A couple of problems can occur here. An InstantiationException indicates we're trying to instantiate an abstract class or an interface. IllegalAccessException is a more general http://localhost/java/javaref/exp/ch05_10.htm (3 of 4) [20/12/2001 11:02:31]
[Chapter 5] 5.10 The Object and Class Classes
exception that indicates we can't access a constructor for the object. Note that newInstance() can create only an instance of a class that has an accessible default constructor. There's no way for us to pass any arguments to a constructor. All this becomes more meaningful when we add the capability to look up a Class by name. forName() is a static method of Class that returns a Class object given its name as a String: try { Class sneakersClass = Class.forName("Sneakers"); } catch ( ClassNotFoundException e ) { ... } A ClassNotFoundException is thrown if the class can't be located. Combining the above tools, we have the power to load new kinds of classes dynamically. When combined with the power of interfaces, we can use new data types by name in our applications: interface Typewriter { void typeLine( String s ); ... } class Printer implements Typewriter { ... } class MyApplication { ... String outputDeviceName = "Printer"; try { Class newClass = Class.forName( outputDeviceName ); Typewriter device = (Typewriter)newClass.newInstance(); ... device.typeLine("Hello..."); } catch ( Exception e ) { }
Inner Classes
http://localhost/java/javaref/exp/ch05_10.htm (4 of 4) [20/12/2001 11:02:31]
Reflection
[Chapter 5] 5.11 Reflection
Chapter 5 Objects in Java
5.11 Reflection In this section we'll take a look at the Java reflection API, supported by the classes in the java.lang.reflect package. As its name suggests, reflection is the ability for a programming language to examine itself. The Java reflection API lets Java code look at an object (more precisely, the class of the object) and determine its structure. Within the limits imposed by the security manager, you can find out what constructors, methods, fields a class has, and their attributes. You can even change the value of fields, dynamically invoke methods, and construct new objects, much as if Java had primitive pointers to variables and methods. We don't have room here to cover the full reflection API. As you might expect, the reflect package is complex and rich in details. But reflection has been designed so that you can do a lot with relatively little effort; 20% of the effort will give you 80% of the fun. The reflection API is used by Java Beans to determine the capabilities of objects at runtime. It's also used at a lower level by object serialization (see Chapter 8) to tear apart and build objects for transport over streams or into persistent storage. Obviously, the power to pick apart objects and see their internals must be zealously watched by the security manager. Your code is not allowed to do anything with the reflection API that it couldn't do with static Java code. In short, reflection is a powerful tool, but it isn't a loophole. An object can't use it to find out about data fields that it wouldn't normally be able to access (for example, another object's private fields), and you can't use it to modify any data inappropriately. The three primary features of a class are its fields (variables), its methods, and its constructors. For purposes of describing or accessing an object, these three features are represented by the classes in the reflection API: the java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor classes represent the fields, methods, and constructors of a class. To get one of these objects, we use the class's Class. Field[] getFields() Field getField(String name) Field[] getDeclaredFields()
Field getDeclaredField(String name) Method[] getMethods() Method getMethod(String name, Class [] argumentTypes)
http://localhost/java/javaref/exp/ch05_11.htm (1 of 6) [20/12/2001 11:02:34]
Get the public variables, including inherited ones. Get the specified public variable, which may be inherited. Get all, public and nonpublic, variables declared in this class (not including those inherited from superclasses). Get the specified variable, public or nonpublic, declared in this class (inherited variables not considered). Get the public methods, including inherited ones. Get the specified public method, who's arguments match the types listed in argumentTypes. The method may be inherited.
[Chapter 5] 5.11 Reflection
Get all, public and nonpublic, methods declared in this class (not including those inherited from superclasses). Get the specified method, public or nonpublic, who's arguments match the types listed in Method getDeclaredMethod(String name, Class[] argumentTypes) argumentTypes, and which is declared in this class (inherited methods not considered). Constructor[] getConstructors() Get the public constructors of this class. Get the specified public constructor of this class, Constructor getConstructor(Class[] argumentTypes) who's arguments match the types listed in argumentTypes. Get all, public and nonpublic, constructors of this Constructor[] getDeclaredConstructors() class. Get the specified constructor, public or nonpublic, Constructor getDeclaredConstructor(Class[] argumentTypes) who's arguments match the types listed in argumentTypes. Method[] getDeclaredMethods()
The table above shows that the Class class provides two pairs of methods for getting at each type of feature. One pair allows access to a class's public features (including those inherited from its superclases), while the other pair allows access to any public or nonpublic item declared within the class (but not features that are inherited), subject to security considerations. For example, getFields() returns an array of Field objects representing all of a class's public variables, including those it inherits. getDeclaredFields() returns an array representing all the variables declared in the class, regardless of their access modifiers (not including variables the security manager won't let you see), but not including inherited variables. (For constructors, the distinction between "all constructors" and "declared constructors" is meaningful, so getConstructors() and getDeclaredConstructors() differ only in that the former returns public constructors, while the latter returns all the class's constructors.) Each pair of methods includes a method for listing all of the items at once (for example, getFields()), and a method for looking up a particular item by name and (for methods and constructors) signature (for example, getField(), which takes the field name as an argument). As a quick example, we'll show how easy it is to list all of the public methods of the java.util.Calendar class: Method [] methods = Calendar.class.getMethods(); for (int i=0; i < methods.length; i++) System.out.println( methods[i] ); Here we have used the .class notation to get a reference the Class of Calendar. Remember the discussion of the Class class--the reflection methods don't belong to the Calendar class itself; they belong to the java.lang.Class object that describes the Calendar class. If we wanted to start from an instance of Calendar (or, say, an unknown object) we could have used the getClass() method of the object instead: Method [] methods = myUnknownObject.getClass().getMethods();
Security Access to the reflection API is governed by a security manager. A fully trusted application has access to all of the above functionality--it can gain access to members of classes at the level of restriction normally granted code within its scope. There is currently no "special" access granted by the reflection API. It is possible that in the future, the full power of the reflection API will be available to completely trusted code such as debuggers; right now, user code can only see what it could have seen at compile-time. Untrusted code (for example, an unsigned applet) has the normal
http://localhost/java/javaref/exp/ch05_11.htm (2 of 6) [20/12/2001 11:02:34]
[Chapter 5] 5.11 Reflection
level of access to classes loaded from its own origin (classes sharing its classloader), but can only rely on the ability to access the public members of public classes coming from the rest of the system.
Accessing Fields The class java.lang.reflect.Field is used to represent static variables and instance variables. Field has a full set of accessor methods for all of the base types (for example, getInt() and setInt(), getBoolean() and setBoolean()), and get() and set() methods for accessing members that are object references. For example, given the following class: class BankAccount { public int balance; } With the reflection API we can read and modify the value of the public integer field balance: BankAccount myBankAccount = ...; ... try { Field balanceField = BankAccount.class.getField("balance"); int balance = balanceField.getInt( myBankAccount ); // read it balanceField.setInt( myBankAccount, 42 ); // change it } catch ( NoSuchFieldException e ) { // There is no "balance" field in this class } catch ( IllegalAccessException e2) { // We don't have permission to access the field. } The various methods of Field take a reference to the particular object instance that we want to access. In the code above, the getField() method returns a Field object that represents the balance of the BankAccount class; this object doesn't refer to any specific BankAccount. Therefore, to read or modify any specific BankAccount, we call getInt() and setInt() with a reference to myBankAccount, which is the account we want to work with. As you can see, an exception occurs if we ask for access to a field that doesn't exist, or if we don't have the proper permission to read or write the field. If we make balance a private field, we can still look up the Field object that describes it, but we won't be able to read or write its value. Therefore, we aren't doing anything that we couldn't have done with static code at compile-time; as long as balance is a public member of a class that we can access, we can write code to read and modify its value. What's important is that we're accessing balance at run-time, and could use this technique to examine the balance field in a class that was dynamically loaded.
Accessing Methods The class java.lang.reflect.Method represents a static or instance method. Subject to the normal security rules, a Method object's invoke() method can be used to call the underlying object's method with specified arguments. Yes, Java has something like a method pointer! As an example, we'll write a Java application called invoke that takes as command line arguments the name of a Java class and the name of a method to invoke. For simplicity, we'll assume that the method is static and takes no arguments:
http://localhost/java/javaref/exp/ch05_11.htm (3 of 6) [20/12/2001 11:02:34]
[Chapter 5] 5.11 Reflection
import java.lang.reflect.*; class invoke { public static void main( String [] args ) { try { Class c = Class.forName( args[0] ); Method m = c.getMethod( args[1], new Class [] { } ); Object ret = m.invoke( null, null ); System.out.println( "Invoked static method: " + args[1] + " of class: " + args[0] + " with no args\nResults: " + ret ); } catch ( ClassNotFoundException e ) { // Class.forName() can't find the class } catch ( NoSuchMethodException e2 ) { // that method doesn't exist } catch ( IllegalAccessException e3 ) { // we don't have permission to invoke that method } catch ( InvocationTargetException e4 ) { // an exception ocurred while invoking that method System.out.println("Method threw an: " + e4.getTargetException() ); } } } We can run invoke to fetch the value of the system clock: % java invoke java.lang.System currentTimeMillis Invoked static method: currentTimeMillis of class: java.lang.System with no args Results: 861129235818 Cool, eh? Maybe you'll consider this the first step towards writing a full blown scripting language for Java, in Java. If you do, please let me know. Turning to the code, our first task is to look up the specified Class by name. To do so, we call the forName() method with the name of the desired class (the first command line argument). We then ask for the specified method by its name. getMethod() has two arguments: the first is the method name (the second command line argument) and the second is an array of Class objects that specifies the method's signature. (Remember that any method may be overloaded; you must specify the signature to make it clear which version you want.) Since our simple program only calls methods with no arguments, we create an anonymous empty array of Class objects. Had we wanted to invoke a method that takes arguments, we would have passed an array of the classes of their respective types, in the proper order. (An IllegalArgumentException can be thrown at run-time if they are wrong). The classes of primitive types can be found in the static TYPE fields of their respective wrappers; for example, use Integer.TYPE for the class of a primitive integer. Once we have the Method object, we call its invoke() method. This calls our target method, and returns the result as an Object. (To do anything nontrivial with this object, you have to cast it to something more specific. Presumably, since you're calling the method, you know what kind of object to expect.) If the returned value is a primitive type like int or boolean, it will be wrapped in the standard wrapper class for its type. (Wrappers for primitive types are discussed in Chapter 7, Basic Utility Classes.) If the method returns void, invoke() returns a Void object. (This is why a wrapper class is needed for void; we need a class to represent void return values.) The first argument to invoke() is the object on which we would like to invoke the method. If the method is static, there is no object, so we set the first argument to null. That's the case in our example. The second argument is an
http://localhost/java/javaref/exp/ch05_11.htm (4 of 6) [20/12/2001 11:02:34]
[Chapter 5] 5.11 Reflection
array of objects to be passed as arguments to the methods. The types of these should match the types specified in the getMethod() call. Because we're calling a method with no arguments, we can pass null for the second argument to invoke(). As with the return value, the types of primitive arguments are expected to be wrapped in wrapper classes. The reflection API automatically unpacks them for the method invocation. The exceptions shown in the code above occur if we cannot find or don't have permission to access the method. Additionally, an InvocationTargetException occurs if the method being invoked throws some kind of exception itself. You can find out what it threw by calling the getTargetException() method of InvocationTargetException.
Accessing Constructors The java.lang.reflect.Constructor class represents an object constructor. Subject to the security manager, you can use it to create a new instance of an object, with arguments. Although you can load new classes dynamically and create instances of them with Class.forName() and Class.newInstance(), you cannot specify arguments with those methods. Here we'll create an instance of java.util.Date, passing a string argument to the constructor: try { Constructor c = Date.class.getConstructor( new Class [] { String.class } ); Object o = c.newInstance( new Object [] { "Jan 1, 1997" } ); Date d = (Date)o; System.out.println(d); } catch ( NoSuchMethodException e ) { // getConstructor() couldn't find the constructor we described } catch ( InstantiationException e2 ) { // the class is abstract } catch ( IllegalAccessException e3 ) { // we don't have permission to create an instance } catch ( InvocationTargetException e4 ) { // the construct threw an exception } The story is much the same as with a method invocation; after all, a constructor is really no more than a method with some strange properties. We look up the appropriate constructor for our Date class--the one that takes a single String as its argument--by passing getConstructor() an array containing the String class as its only element. (If the constructor required more arguments, we would put additional objects in the array, representing the classes of each argument.) We can then invoke newInstance(), passing it a corresponding array of argument objects. Again, to pass primitive types we would wrap them in their wrapper types first. Finally, we cast the resulting object to a Date, and print it. The same exceptions seen in the previous example apply here, including the possible IllegalArgumentException. In addition, newInstance() throws an InstantiationException if the class is abstract and cannot be instantiated. What about arrays? The reflection API allows you to create and inspect array of base types using the java.lang.reflect.Array class. The process is much the same as with the other classes. For more information, look in a language reference. What is Reflection good for?
http://localhost/java/javaref/exp/ch05_11.htm (5 of 6) [20/12/2001 11:02:34]
[Chapter 5] 5.11 Reflection
Well, we've already said that reflection is used by the serialization process (Chapter 8, Input/Output Facilities), and that it is used by graphical development environments, like Borland's JBuilder and Symantec's Visual Cafe. But these are pretty much behind the scenes applications. What can reflection do for the average Java programmer? First, it's there when you really need a method pointer. However, in most situations where a method pointer is convenient, there are other solutions to try; writing an anonymous adapter class is likely to be clearer and more efficient. Reflection would let you write a generic adapter class; that is, an adapter that doesn't know in advance what method to call. The adapter's client could pass a method name to the adapter as a string; the adapter would then use reflection to find the given Method in its client. Even more generally, you can use reflection in any situation where you need to call methods that you don't know about in advance. It's hard to think of good examples--but then, that's the beauty of Java: it opens possibilities for new kinds of applications. Perhaps you'll need to write some kind of self-extending program, that loads new modules dynamically and uses reflection to find out how to use them. In short, don't relegate reflection to the dusty toolbox of tricks that are only useful for experts. With some experimentation, you'll find that reflection greatly adds to Java's capabilities.
The Object and Class Classes
http://localhost/java/javaref/exp/ch05_11.htm (6 of 6) [20/12/2001 11:02:34]
Threads
[Chapter 6] 6.2 Threading Applets
Chapter 6 Threads
6.2 Threading Applets Applets are embeddable Java applications that are expected to be able to start and stop themselves on command. Unlike threads, applets can be started and stopped any number of times. A Java-enabled Web browser normally starts an applet when the applet is displayed and stops it when the user moves to another page or scrolls the applet out of view. In general, we would like an applet to cease its nonessential activity when it is stopped, and resume it when started again. (See Chapter 10, Understand the Abstract Windowing Toolkit for a complete discussion of applets.) In this section, we will build UpdateApplet, a simple base class for an Applet that maintains a Thread to automatically update its display at regular intervals. UpdateApplet handles the basic starting and stopping behavior for us, as shown below. public class UpdateApplet extends java.applet.Applet implements Runnable { private Thread updateThread; int updateInterval = 1000; public void run() { while ( true ) { try { Thread.sleep( updateInterval ); } catch (InterruptedException e ) { } repaint(); } } public void start() { if ( updateThread == null ) { updateThread = new Thread(this); updateThread.start();
http://localhost/java/javaref/exp/ch06_02.htm (1 of 4) [20/12/2001 11:02:34]
[Chapter 6] 6.2 Threading Applets
} } public void stop() { if ( updateThread != null ) { updateThread.stop(); updateThread = null; } } } UpdateApplet is a Runnable object that alternately sleeps and calls its repaint() method. It has two other public methods: start() and stop(). These are methods of the Applet class we are overriding; do not confuse them with the similarly named methods of the Thread class. These start() and stop() methods are called by the Java environment to tell the applet when it should and should not be running. UpdateApplet illustrates an environmentally friendly way to deal with threads in a simple applet. UpdateApplet kills its thread each time the applet is stopped and recreates it if the applet is restarted. When UpdateApplet's start() method is called, we first check to make sure there is no currently executing updateThread. We then create one to begin our execution. When our applet is subsequently stopped, we kill the thread by invoking its stop() method and throw away the reference by setting it to null. Setting updateThread to null serves both to allow the garbage collector to clean up the dead Thread object, and to indicate to UpdateApplet's start() method that the thread is gone. In truth, an Applet's start() and stop() methods are guaranteed to be called in sequence. As a result, we shouldn't have to check for the existence of updateThread in start() (it should always be null). However, it's good programming practice to perform the test. If we didn't, and for some reason stop() were to fail at its job, we might inadvertently start a lot of threads. With UpdateApplet doing all of the work for us, we can now create the world's simplest clock applet with just a few lines of code. Figure 6.3 shows our Clock. (This might be a good one to run on your Java wrist watch.) public class Clock extends UpdateApplet { public void paint( java.awt.Graphics g ) { g.drawString( new java.util.Date().toString(), 10, 25 ); } } Figure 6.3: The clock applet
http://localhost/java/javaref/exp/ch06_02.htm (2 of 4) [20/12/2001 11:02:34]
[Chapter 6] 6.2 Threading Applets
The java.util.Date().toString() sequence simply creates a string that contains the current time; we'll see where this code comes from in Chapter 7, Basic Utility Classes. Our Clock applet provides a good example of a simple thread; we don't mind throwing it away and subsequently rebuilding it if the user should happen to wander on and off of our Web page a few times. But what if the task that our thread handles isn't so simple? What if, for instance, we have to open a socket and establish a connection with another system? One solution is to use Thread's suspend() and resume() methods, as I'll show you momentarily. Now if you've been wondering why we've been using stop() to kill the thread, rather than using the suspend() and resume() methods all along, here's the explanation you've been waiting for. The problem with applets is that we have no control over how a user navigates Web pages. For example, say a user scrolls our applet out of view, and we use suspend() to suspend the applet. Now we have no way of ensuring that the user will bring the applet back into view before moving on to another page. And actually, the same situation would occur if the user simply moves on to another page and never comes back. If we call suspend(), we'd really like to make sure we call resume() at a later date, or we'll end up leaving the thread hanging in permanent suspense. But we have no way of knowing if the applet will ever be restarted, so just putting a call to resume() in the applet's start() method won't work. Leaving the suspended thread around forever might not hurt us, but it's not good programming practice to be wasteful. What we need is a way to guarantee we can clean up our mess if the applet is never used again. What to do? There is a solution for this dilemma, but in many cases, like with our simple Clock, it's just easier to use stop(), with a subsequent call to start() if necessary. In cases where it is expensive to set up and tear down a thread, we could make the following modifications to UpdateApplet: public void start() { if ( updateThread == null ) { updateThread = new Thread(this); updateThread.start(); } else updateThread.resume(); } public void stop() { updateThread.suspend();
http://localhost/java/javaref/exp/ch06_02.htm (3 of 4) [20/12/2001 11:02:34]
[Chapter 6] 6.2 Threading Applets
public void destroy() { if ( updateThread != null ) { updateThread.stop(); updateThread = null; } } These modifications change UpdateApplet so that it suspends and restarts its updateThread, rather than killing and recreating it. The new start() method creates the thread and calls start() if updateThread is null; otherwise it assumes that the thread has been suspended, so it calls resume(). The applet's stop() method simply suspends the thread by calling suspend(). What's new here is the destroy() method. This is another method that UpdateApplet inherits from the Applet class. The method is called by the Java environment when the applet is going to be removed (often from a cache). It provides a place where we can free up any resources the applet is holding. This is the perfect place to cut the suspense and clean up after our thread. In our destroy() method, we check to see that the thread exists, and if it does, we call stop() to kill it and set its reference to null.
Introducing Threads
http://localhost/java/javaref/exp/ch06_02.htm (4 of 4) [20/12/2001 11:02:34]
Synchronization
[Chapter 6] 6.3 Synchronization
Chapter 6 Threads
6.3 Synchronization Every thread has a life of its own. Normally, a thread goes about its business without any regard for what other threads in the application are doing. Threads may be time-sliced, which means they can run in arbitrary spurts and bursts as directed by the operating system. On a multiprocessor system, it is even possible for many different threads to be running simultaneously on different CPUs. This section is about coordinating the activities of two or more threads, so they can work together and not collide in their use of the same address space. Java provides a few simple structures for synchronizing the activities of threads. They are all based on the concept of monitors, a widely used synchronization scheme developed by C.A.R. Hoare. You don't have to know the details about how monitors work to be able to use them, but it may help you to have a picture in mind. A monitor is essentially a lock. The lock is attached to a resource that many threads may need to access, but that should be accessed by only one thread at a time. It's not unlike a public restroom at a gas station. If the resource is not being used, the thread can acquire the lock and access the resource. By the same token, if the restroom is unlocked, you can enter and lock the door. When the thread is done, it relinquishes the lock, just as you unlock the door and leave it open for the next person. However, if another thread already has the lock for the resource, all other threads have to wait until the current thread finishes and releases the lock, just as if the restroom is locked when you arrive, you have to wait until the current occupant is done and unlocks the door. Fortunately, Java makes the process of synchronizing access to resources quite easy. The language handles setting up and acquiring locks; all you have to do is specify which resources require locks.
Serializing Methods The most common need for synchronization among threads in Java is to serialize their access to some resource, namely an object. In other words, synchronization makes sure only one thread at a time can perform certain activities that manipulate an object. In Java, every object has a lock associated with it. To be more specific, every class and every instance of a class has its own lock. The synchronized keyword marks places where a thread must acquire the lock before proceeding. For example, say we implemented a SpeechSynthesizer class that contains a say() method. We don't want multiple threads calling say() at the same time or we wouldn't be able to understand
http://localhost/java/javaref/exp/ch06_03.htm (1 of 9) [20/12/2001 11:02:35]
[Chapter 6] 6.3 Synchronization
anything being said. So we mark the say() method as synchronized, which means that a thread has to acquire the lock on the SpeechSynthesizer object before it can speak: class SpeechSynthesizer { synchronized void say( String words ) { // Speak } } Because say() is an instance method, a thread has to acquire the lock on the particular SpeechSynthesizer instance it is using before it can invoke the say() method. When say() has completed, it gives up the lock, which allows the next waiting thread to acquire the lock and run the method. Note that it doesn't matter whether the thread is owned by the SpeechSynthesizer itself or some other object; every thread has to acquire the same lock, that of the SpeechSynthesizer instance. If say() were a class (static) method instead of an instance method, we could still mark it as synchronized. But in this case as there is no instance object involved, the lock would be on the class object itself. Often, you want to synchronize multiple methods of the same class, so that only one of the methods modifies or examines parts of the class at a time. All static synchronized methods in a class use the same class object lock. By the same token, all instance methods in a class use the same instance object lock. In this way, Java can guarantee that only one of a set of synchronized methods is running at a time. For example, a SpreadSheet class might contain a number of instance variables that represent cell values, as well as some methods that manipulate the cells in a row: class SpreadSheet { int cellA1, cellA2, cellA3; synchronized int sumRow() { return cellA1 + cellA2 + cellA3; } synchronized cellA1 = cellA2 = cellA3 = }
void setRow( int a1, int a2, int a3 ) { a1; a2; a3;
... } In this example, both methods setRow() and sumRow() access the cell values. You can see that problems might arise if one thread were changing the values of the variables in setRow() at the same moment another thread was reading the values in sumRow(). To prevent this, we have marked both methods as synchronized. When threads are synchronized, only one will be run at a time. If a thread is in
http://localhost/java/javaref/exp/ch06_03.htm (2 of 9) [20/12/2001 11:02:35]
[Chapter 6] 6.3 Synchronization
the middle of executing setRow() when another thread calls sumRow(), the second thread waits until the first one is done executing setRow() before it gets to run sumRow(). This synchronization allows us to preserve the consistency of the SpreadSheet. And the best part is that all of this locking and waiting is handled by Java; it's transparent to the programmer. In addition to synchronizing entire methods, the synchronized keyword can be used in a special construct to guard arbitrary blocks of code. In this form it also takes an explicit argument that specifies the object for which it is to acquire a lock: synchronized ( myObject ) { // Functionality that needs to be synced ... } The code block above can appear in any method. When it is reached, the thread has to acquire the lock on myObject before proceeding. In this way, we can have methods (or parts of methods) in different classes synchronized the same as methods in the same class. A synchronized method is, therefore, equivalent to a method with its statements synchronized on the current object. Thus: synchronized void myMethod () { ... } is equivalent to: void myMethod () { synchronized ( this ) { ... } }
wait( ) and notify( ) With the synchronized keyword, we can serialize the execution of complete methods and blocks of code. The wait() and notify() methods of the Object class extend this capability. Every object in Java is a subclass of Object, so every object inherits these methods. By using wait() and notify(), a thread can give up its hold on a lock at an arbitrary point, and then wait for another thread to give it back before continuing. All of the coordinated activity still happens inside of synchronized blocks, and still only one thread is executing at a given time. By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep. A thread might do this if it needs to wait for something to happen in another part of the application, as you'll see shortly. Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object. Now the first thread wakes up and begins trying to acquire the lock again. http://localhost/java/javaref/exp/ch06_03.htm (3 of 9) [20/12/2001 11:02:35]
[Chapter 6] 6.3 Synchronization
When the first thread manages to reacquire the lock, it continues from the point it left off. However, the thread that waited may not get the lock immediately (or perhaps ever). It depends on when the second thread eventually releases the lock, and which thread manages to snag it next. Note also, that the first thread won't wake up from the wait() unless another thread calls notify(). There is an overloaded version of wait(), however, that allows us to specify a timeout period. If another thread doesn't call notify() in the specified period, the waiting thread automatically wakes up. Let's look at a simple scenario to see what's going on. In the following example, we'll assume there are three threads--one waiting to execute each of the three synchronized methods of the MyThing class. We'll call them the waiter, notifier, and related threads, respectively. Here's a code fragment to illustrate: class MyThing { synchronized void waiterMethod() { // Do some stuff // Now we need to wait for notifier to do something wait(); // Continue where we left off } synchronized void notifierMethod() { // Do some stuff // Notify waiter that we've done it notify(); // Do more things } synchronized void relatedMethod() { // Do some related stuff } Let's assume waiter gets through the gate first and begins executing waiterMethod(). The two other threads are initially blocked, trying to acquire the lock for the MyThing object. When waiter executes the wait() method, it relinquishes its hold on the lock and goes to sleep. Now there are now two viable threads waiting for the lock. Which thread gets it depends on several factors, including chance and the priorities of the threads. (We'll discuss thread scheduling in the next section.) Let's say that notifier is the next thread to acquire the lock, so it begins to run. waiter continues to sleep and related languishes, waiting for its turn. When notifier executes the call to notify(), Java prods the waiter thread, effectively telling it something has changed. waiter then wakes up and rejoins related in vying for the MyThing lock. Note that it doesn't actually receive the lock; it just
http://localhost/java/javaref/exp/ch06_03.htm (4 of 9) [20/12/2001 11:02:35]
[Chapter 6] 6.3 Synchronization
changes from saying "leave me alone" to "I want the lock." At this point, notifier still owns the lock and continues to hold it until it leaves its synchronized method (or perhaps executes a wait() itself ). When it finally completes, the other two methods get to fight over the lock. waiter would like to continue executing waiterMethod() from the point it left off, while unrelated, which has been patient, would like to get started. We'll let you choose your own ending for the story. For each call to notify(), Java wakes up just one method that is asleep in a wait() call. If there are multiple threads waiting, Java picks the first thread on a first-in, first-out basis. The Object class also provides a notifyAll() call to wake up all waiting threads. In most cases, you'll probably want to use notifyAll() rather than notify(). Keep in mind that notify() really means "Hey, something related to this object has changed. The condition you are waiting for may have changed, so check it again." In general, there is no reason to assume only one thread at a time is interested in the change or able to act upon it. Different threads might look upon whatever has changed in different ways. Often, our waiter thread is waiting for a particular condition to change and we will want to sit in a loop like the following: ... while ( condition != true ) wait(); ... Other synchronized threads call notify() or notifyAll() when they have modified the environment so that waiter can check the condition again. This is the civilized alternative to polling and sleeping, as you'll see the following example.
The Message Passer Now we'll illustrate a classic interaction between two threads: a Producer and a Consumer. A producer thread creates messages and places them into a queue, while a consumer reads them out and displays them. To be realistic, we'll give the queue a maximum depth. And to make things really interesting, we'll have our consumer thread be lazy and run much slower than the producer. This means that Producer occasionally has to stop and wait for Consumer to catch up. The example below shows the Producer and Consumer classes. import java.util.Vector; class Producer extends Thread { static final int MAXQUEUE = 5; private Vector messages = new Vector(); public void run() { try { while ( true ) { putMessage(); http://localhost/java/javaref/exp/ch06_03.htm (5 of 9) [20/12/2001 11:02:35]
[Chapter 6] 6.3 Synchronization
sleep( 1000 ); } } catch( InterruptedException e ) { } } private synchronized void putMessage() throws InterruptedException { while ( messages.size() == MAXQUEUE ) wait(); messages.addElement( new java.util.Date().toString() ); notify(); } // Called by Consumer public synchronized String getMessage() throws InterruptedException { notify(); while ( messages.size() == 0 ) wait(); String message = (String)messages.firstElement(); messages.removeElement( message ); return message; } } class Consumer extends Thread { Producer producer; Consumer(Producer p) { producer = p; } public void run() { try { while ( true ) { String message = producer.getMessage(); System.out.println("Got message: " + message); sleep( 2000 ); } } catch( InterruptedException e ) { } } public static void main(String args[]) { http://localhost/java/javaref/exp/ch06_03.htm (6 of 9) [20/12/2001 11:02:35]
[Chapter 6] 6.3 Synchronization
Producer producer = new Producer(); producer.start(); new Consumer( producer ).start(); } } For convenience, we have included a main() method that runs the complete example in the Consumer class. It creates a Consumer that is tied to a Producer and starts the two classes. You can run the example as follows: % java Consumer The output is the time-stamp messages created by the Producer: Got message: Sun Dec 19 03:35:55 CST 1996 Got message: Sun Dec 19 03:35:56 CST 1996 Got message: Sun Dec 19 03:35:57 CST 1996 ... The time stamps initially show a spacing of one second, although they appear every two seconds. Our Producer runs faster than our Consumer. Producer would like to generate a new message every second, while Consumer gets around to reading and displaying a message only every two seconds. Can you see how long it will take the message queue to fill up? What will happen when it does? Let's look at the code. We are using a few new tools here. Producer and Consumer are subclasses of Thread. It would have been a better design decision to have Producer and Consumer implement the Runnable interface, but we took the slightly easier path and subclassed Thread. You should find it fairly simple to use the other technique; you might try it as an exercise. The Producer and Consumer classes pass messages through an instance of a java.util.Vector object. We haven't discussed the Vector class yet, but you can think of this one as a queue where we add and remove elements in first-in, first-out order. See Chapter 7, Basic Utility Classes for more information about the Vector class. The important activity is in the synchronized methods: putMessage() and getMessage(). Although one of the methods is used by the Producer thread and the other by the Consumer thread, they both live in the Producer class because they have to be synchronized on the same object to work together. Here they both implicitly use the Producer object's lock. If the queue is empty, the Consumer blocks in a call in the Producer, waiting for another message. Another design option would implement the getMessage() method in the Consumer class and use a synchronized code block to explicitly synchronize on the Producer object. In either case, synchronizing on the Producer is important because it allows us to have multiple Consumer objects that feed on the same Producer. putMessage()'s job is to add a new message to the queue. It can't do this if the queue is already full, so it first checks the number of elements in messages. If there is room, it stuffs in another time stamp. If the queue is at its limit however, putMessage() has to wait until there's space. In this situation,
http://localhost/java/javaref/exp/ch06_03.htm (7 of 9) [20/12/2001 11:02:35]
[Chapter 6] 6.3 Synchronization
putMessage() executes a wait() and relies on the consumer to call notify() to wake it up after a message has been read. Here we have putMessage() testing the condition in a loop. In this simple example, the test probably isn't necessary; we could assume that when putMessage() wakes up, there is a free spot. However, this test is another example of good programming practice. Before it finishes, putMessage() calls notify() itself to prod any Consumer that might be waiting on an empty queue. getMessage() retrieves a message for the Consumer. It enters a loop like the Producer's, waiting for the queue to have at least one element before proceeding. If the queue is empty, it executes a wait() and expects the producer to call notify() when more items are available. Notice that getMessage() makes its own unconditional call to notify(). This is a somewhat lazy way of keeping the Producer on its toes, so that the queue should generally be full. Alternatively, getMessage() might test to see if the queue had fallen below a low water mark before waking up the producer. Now let's add another Consumer to the scenario, just to make things really interesting. Most of the necessary changes are in the Consumer class; the example below shows the code for the modified class. class Consumer extends Thread { Producer producer; String name; Consumer(String name, Producer producer) { this.producer = producer; this.name = name; } public void run() { try { while ( true ) { String message = producer.getMessage(); System.out.println(name + " got message: " + message); sleep( 2000 ); } } catch( InterruptedException e ) { } } public static void main(String args[]) { Producer producer = new Producer(); producer.start(); // Start two this time new Consumer( "One", producer ).start(); new Consumer( "Two", producer ).start(); } }
http://localhost/java/javaref/exp/ch06_03.htm (8 of 9) [20/12/2001 11:02:35]
[Chapter 6] 6.3 Synchronization
The Consumer constructor now takes a string name, to identify each consumer. The run() method uses this name in the call to println() to identify which consumer received the message. The only modification to make in the Producer code is to change the call to notify() in putMessage() to a call to notifyAll(). Now, instead of the consumer and producer playing tag with the queue, we can have many players waiting on the condition of the queue to change. We might have a number of consumers waiting for a message, or we might have the producer waiting for a consumer to take a message. Whenever the condition of the queue changes, we prod all of the waiting methods to reevaluate the situation by calling notifyAll(). Note, however, that we don't need to change the call to notify() in getMessage(). If a Consumer thread is waiting for a message to appear in the queue, it's not possible for the Producer to be simultaneously waiting because the queue is full. Here is some sample output when there are two consumers running, as in the main() method shown above: One Two One Two One Two One Two ...
got got got got got got got got
message: message: message: message: message: message: message: message:
Wed Wed Wed Wed Wed Wed Wed Wed
Mar Mar Mar Mar Mar Mar Mar Mar
20 20 20 20 20 20 20 20
20:00:01 20:00:02 20:00:03 20:00:04 20:00:05 20:00:06 20:00:07 20:00:08
CST CST CST CST CST CST CST CST
1996 1996 1996 1996 1996 1996 1996 1996
We see nice, orderly alternation between the two consumers, as a result of the calls to sleep() in the various methods. Interesting things would happen, however, if we were to remove all of the calls to sleep() and let things run at full speed. The threads would compete and their behavior would depend on whether or not the system is using time slicing. On a time-sliced system, there should be a fairly random distribution between the two consumers, while on a nontime-sliced system, a single consumer could monopolize the messages. And since you're probably wondering about time slicing, let's talk about thread priority and scheduling.
Threading Applets
http://localhost/java/javaref/exp/ch06_03.htm (9 of 9) [20/12/2001 11:02:35]
Scheduling and Priority
[Chapter 6] 6.4 Scheduling and Priority
Chapter 6 Threads
6.4 Scheduling and Priority Java makes certain guarantees as to how its threads are scheduled. Every thread has a priority value. If, at any time, a thread of a higher priority than the current thread becomes runnable, it preempts the lower priority thread and begins executing. By default, threads at the same priority are scheduled round robin, which means once a thread starts to run, it continues until it does one of the following: Sleeps Calls Thread.sleep() or wait() Waits for lock Waits for a lock in order to run a synchronized method Blocks on I/O Blocks, for example, in a xread() or an accept() call Explicitly yields control Calls yield() Terminates Completes its target method or is terminated by a stop() call This situation looks something like what's shown in Figure 6.4. Figure 6.4: Priority preemptive, round robin scheduling
http://localhost/java/javaref/exp/ch06_04.htm (1 of 4) [20/12/2001 11:02:36]
[Chapter 6] 6.4 Scheduling and Priority
Java leaves certain aspects of scheduling up to the implementation.[2] The main point here is that some, but not all, implementations of Java use time slicing on threads of the same priority.[3] In a time-sliced system, thread processing is chopped up, so that each thread runs for a short period of time before the context is switched to the next thread, as shown in Figure 6.5. [2] This implementation-dependent aspect of Java isn't a big deal, since it doesn't hurt for an implementation to add time slicing on top of the default round-robin scheduling. It's actually not hard to create a time-slicing effect by simply having a high-priority thread sleeping for a specified time interval. Every time it wakes up, it interrupts a lower-priority thread and causes processing to shift round robin to the next thread. [3] As of Java Release 1.0, Sun's Java Interpreter for the Windows 95 and Windows NT platforms uses time slicing, as does the Netscape Navigator Java environment. Sun's Java 1.0 for the Solaris UNIX platforms doesn't. Higher priority threads still preempt lower priority threads in this scheme. The addition of time slicing mixes up the processing among threads of the same priority; on a multiprocessor machine, threads may even be run simultaneously. Unfortunately, this feature can lead to differences in your application's behavior. Figure 6.5: Priority preemptive, time-sliced scheduling
http://localhost/java/javaref/exp/ch06_04.htm (2 of 4) [20/12/2001 11:02:36]
[Chapter 6] 6.4 Scheduling and Priority
Since Java doesn't guarantee time slicing, you shouldn't write code that relies on this type of scheduling; any software you write needs to function under the default round-robin scheduling. But if you're wondering what your particular flavor of Java does, try the following experiment: class Thready { public static void main( String args [] ) { new MyThread("Foo").start(); new MyThread("Bar").start(); } } class MyThread extends Thread { String message; MyThread ( String message ) { this.message = message; } public void run() { while ( true ) System.out.println( message ); } } The Thready class starts up two MyThread objects. Thready is a thread that goes into a hard loop (very bad form) and prints its message. Since we don't specify a priority for either thread, they both inherit the priority of their creator, so they have the same priority. When you run this example, you will see how your Java implementation does it scheduling. Under a round-robin scheme, only "Foo" should be printed; "Bar" never appears. In a time-slicing implementation, you should occasionally see the "Foo" and "Bar" messages alternate.
Priorities Now let's change the priority of the second thread: class Thready { public static void main( String args [] ) { new MyThread("Foo").start(); Thread bar = new MyThread("Bar"); bar.setPriority( Thread.NORM_PRIORITY + 1 ); bar.start(); } } As you might expect, this changes how our example behaves. Now you may see a few "Foo" messages,
http://localhost/java/javaref/exp/ch06_04.htm (3 of 4) [20/12/2001 11:02:36]
[Chapter 6] 6.4 Scheduling and Priority
but "Bar" should quickly take over and not relinquish control, regardless of the scheduling policy. Here we have used the setPriority() method of the Thread class to adjust our thread's priority. The Thread class defines three standard priority values, as shown in Table 6.1. Table 6.1: Thread Priority Values Value
Definition MIN_PRIORITY Minimum priority NORM_PRIORITY Normal priority MAX_PRIORITY Maximum priority If you need to change the priority of a thread, you should use one of these values or a close relative value. But let me warn you against using MAX_PRIORITY or a close relative value; if you elevate many threads to this priority level, priority will quickly become meaningless. A slight increase in priority should be enough for most needs. For example, specifying NORM_PRIORITY + 1 in our example is enough to beat out our other thread.
Yielding As I said earlier, whenever a thread sleeps, waits, or blocks on I/O, it gives up its time slot, and another thread is scheduled. So as long as you don't write methods that use hard loops, all threads should get their due. However, a Thread can also give up its time voluntarily with the yield() call. We can change our previous example to include a yield() on each iteration: class MyThread extends Thread { ... public void run() { while ( true ) { System.out.println( message ); yield(); } } } Now you should see "Foo" and "Bar" messages alternating one for one. If you have threads that perform very intensive calculations, or otherwise eat a lot of CPU time, you might want to find an appropriate place for them to yield control occasionally. Alternatively, you might want to drop the priority of your intensive thread, so that more important processing can proceed around it.
Synchronization
http://localhost/java/javaref/exp/ch06_04.htm (4 of 4) [20/12/2001 11:02:36]
Basic Utility Classes
[Chapter 7] 7.2 Math Utilities
Chapter 7 Basic Utility Classes
7.2 Math Utilities Java supports integer and floating-point arithmetic directly. Higher-level math operations are supported through the java.lang.Math class. Java provides wrapper classes for all primitive data types, so you can treat them as objects if necessary. Java also provides the java.util.Random class for generating random numbers. Java handles errors in integer arithmetic by throwing an ArithmeticException: int zero = 0; try { int i = 72 / zero; } catch ( ArithmeticException e ) { }
// division by zero
To generate the error in the above example, we created the intermediate variable zero. The compiler is somewhat crafty and would have caught us if we had blatantly tried to perform a division by zero. Floating-point arithmetic expressions, on the other hand, don't throw exceptions. Instead, they take on the special out-of-range values shown in Table 7.3. Table 7.3: Special Floating-Point Values Value Mathematical representation POSITIVE_INFINITY 1.0/0.0 NEGATIVE_INFINITY -1.0/0.0 0.0/0.0 NaN The following example generates an infinite result: double zero = 0.0; double d = 1.0/zero;
http://localhost/java/javaref/exp/ch07_02.htm (1 of 6) [20/12/2001 11:02:37]
[Chapter 7] 7.2 Math Utilities
if ( d == Double.POSITIVE_INFINITY ) System.out.println( "Division by zero" ); The special value NaN indicates the result is "not a number." The value NaN has the special distinction of not being equal to itself (NaN != NaN). Use Float.isNaN() or Double.isNaN() to test for NaN.
java.lang.Math The java.lang.Math class serves as Java's math library. All its methods are static and used directly ; you can't instantiate a Math object. We use this kind of degenerate class when we really want methods to approximate normal functions in C. While this tactic defies the principles of object-oriented design, it makes sense in this case, as it provides a means of grouping some related utility functions in a single class. Table 7.4 summarizes the methods in java.lang.Math. Table 7.4: Methods in java.lang.Math Method
Argument type(s)
Functionality
int, long, float, double Absolute value Arc cosine Math.acos(a) double Arc sine Math.asin(a) double Arc tangent Math.atan(a) double Converts rectangular to polar coordinates Math.atan2(a,b) double Smallest whole number greater than or equal to Math.ceil(a) double a Cosine Math.cos(a) double Exponential number to the power of a Math.exp(a) double Math.abs(a)
Math.floor(a)
double
Largest whole number less than or equal to a
Math.log(a)
double
Natural logarithm of a
Math.max(a, b) int, long, float, double Maximum Math.min(a, b) int, long, float, double Minimum Math.pow(a, b) double None Math.random()
a to the power of b Random number generator Converts double value to integral value in double format
Math.rint(a)
double
Math.round(a)
float, double
Rounds
Math.sin(a) Math.sqrt(a) Math.tan(a)
double double double
Sine Square root Tangent
log(), pow(), and sqrt() can throw an ArithmeticException. abs(), max(), and min() http://localhost/java/javaref/exp/ch07_02.htm (2 of 6) [20/12/2001 11:02:37]
[Chapter 7] 7.2 Math Utilities
are overloaded for all the scalar values, int, long, float, or double, and return the corresponding type. Versions of Math.round() accept either float or double and return int or long respectively. The rest of the methods operate on and return double values: double irrational = Math.sqrt( 2.0 ); int bigger = Math.max( 3, 4 ); long one = Math.round( 1.125798 ); For convenience, Math also contains the static final double values E and PI: double circumference = diameter * Math.PI;
java.math If a long or a double just isn't big enough for you, the java.math package provides two classes, BigInteger and BigDecimal, that support arbitrary-precision numbers. These are full-featured classes with a bevy of methods for performing arbitrary-precision math. In the following example, we use BigInteger to add two numbers together. try { BigDecimal twentyone = new BigDecimal("21"); BigDecimal seven = new BigDecimal("7"); BigDecimal sum = twentyone.add(seven); int twentyeight = sum.intValue(); } catch (NumberFormatException nfe) { } catch (ArithmeticException ae) { }
Wrappers for Primitive Types In languages like Smalltalk, numbers and other simple types are objects, which makes for an elegant language design, but has trade-offs in efficiency and complexity. By contrast, there is a schism in the Java world between class types (i.e., objects) and primitive types (i.e., numbers, characters, and boolean values). Java accepts this trade-off simply for efficiency reasons. When you're crunching numbers you want your computations to be lightweight; having to use objects for primitive types would seriously affect performance. For the times you want to treat values as objects, Java supplies a wrapper class for each of the primitive types, as shown in Table 7.5. Table 7.5: Primitive Type Wrappers Primitive Wrapper void java.lang.Void boolean java.lang.Boolean char java.lang.Character
http://localhost/java/javaref/exp/ch07_02.htm (3 of 6) [20/12/2001 11:02:37]
[Chapter 7] 7.2 Math Utilities
byte short int long float double
java.lang.Byte java.lang.Short java.lang.Integer java.lang.Long java.lang.Float java.lang.Double
An instance of a wrapper class encapsulates a single value of its corresponding type. It's an immutable object that serves as a container to hold the value and let us retrieve it later. You can construct a wrapper object from a primitive value or from a String representation of the value. The following code is equivalent: Float pi = new Float( 3.14 ); Float pi = new Float( "3.14" ); Wrapper classes throw a NumberFormatException when there is an error in parsing from a string: try { Double bogus = new Double( "huh?" ); } catch ( NumberFormatException e ) { // bad number } You should arrange to catch this exception if you want to deal with it. Otherwise, since it's a subclass of RuntimeException, it will propagate up the call stack and eventually cause a run-time error if not caught. Sometimes you'll use the wrapper classes simply to parse the String representation of a number: String sheep = getParameter("sheep"); int n = new Integer( sheep ).intValue(); Here we are retrieving the value of the sheep parameter. This value is returned as a String, so we need to convert it to a numeric value before we can use it. Every wrapper class provides methods to get primitive values out of the wrapper; we are using intValue() to retrieve an int out of Integer. Since parsing a String representation of a number is such a common thing to do, the Integer and Long classes also provide the static methods Integer.parseInt() and Long.parseLong() that read a String and return the appropriate type. So the second line above is equivalent to: int n = Integer.parseInt( sheep ); All wrappers provide access to their values in various forms. You can retrieve scalar values with the methods doubleValue(), floatValue(), longValue(), and intValue():
http://localhost/java/javaref/exp/ch07_02.htm (4 of 6) [20/12/2001 11:02:37]
[Chapter 7] 7.2 Math Utilities
Double size = new Double ( 32.76 ); double d = size.doubleValue(); float f = size.floatValue(); long l = size.longValue(); int i = size.intValue(); The code above is equivalent to the primitive double value cast to the various types. For convenience, you can cast between the wrapper classes like Double class and the primitive data types. Another common use of wrappers occurs when we have to treat a primitive value as an object in order to place it in a list or other structure that operates on objects. As you'll see shortly, a Vector is an extensible array of Objects. We can use wrappers to hold numbers in a Vector, along with other objects: Vector myNumbers = new Vector(); Integer thirtyThree = new Integer( 33 ); myNumbers.addElement( thirtyThree ); Here we have created an Integer wrapper so that we can insert the number into the Vector using addElement(). Later, when we are taking elements back out of the Vector, we can get the number back out of the Integer as follows: Integer theNumber = (Integer)myNumbers.firstElement(); int n = theNumber.intValue(); // n = 33
Random Numbers You can use the java.util.Random class to generate random values. It's a pseudo-random number generator that can be initialized with a 48-bit seed.[1] The default constructor uses the current time as a seed, but if you want a repeatable sequence, specify your own seed with: [1] The generator uses a linear congruential formula. See The Art of Computer Programming, Volume 2 "Semi-numerical Algorithms," by Donald Knuth (Addison-Wesley). long seed = mySeed; Random rnums = new Random( seed ); This code creates a random-number generator. Once you have a generator, you can ask for random values of various types using the methods listed in Table 7.6.
Method nextInt()
Table 7.6: Random Number Methods Range -2147483648 to 2147483647
http://localhost/java/javaref/exp/ch07_02.htm (5 of 6) [20/12/2001 11:02:37]
[Chapter 7] 7.2 Math Utilities
-9223372036854775808 to 9223372036854775807 nextLong() nextFloat() -1.0 to 1.0 nextDouble() -1.0 to 1.0 By default, the values are uniformly distributed. You can use the nextGaussian() method to create a Gaussian distribution of double values, with a mean of 0.0 and a standard deviation of 1.0. The static method Math.random() retrieves a random double value. This method initializes a private random-number generator in the Math class, using the default Random constructor. So every call to Math.random() corresponds to a call to nextDouble() on that random number generator.
Strings
http://localhost/java/javaref/exp/ch07_02.htm (6 of 6) [20/12/2001 11:02:37]
Dates
[Chapter 7] 7.3 Dates
Chapter 7 Basic Utility Classes
7.3 Dates Working with dates and times without the proper tools can be a chore.[2] Java 1.1 gives you three classes that do all the hard work for you. The java.util.Date encapsulates a point in time. The java.util.GregorianCalendar class, which descends from the abstract java.util.Calendar, translates between a point in time and calendar fields like month, day, and year. Finally, the java.text.DateFormat class knows how to generate and parse string representations of dates and times. In Java 1.0.2, the Date class performed all three functions. In Java 1.1, most of its methods have been deprecated, so that its only purpose in life is to represent a point in time. [2] For a wealth of information about time and world time keeping conventions, see http://tycho.usno.navy.mil/, the U.S. Navy Directorate of Time. For a fascinating history of the Gregorian and Julian calendars, try http://barroom.visionsystems.com/serendipity/date/jul_greg.html. The separation of the Date class and the GregorianCalendar class is analagous to having a class representing temperature and a class that translates that temperature to Celsius units. Conceivably, we could define other subclasses of Calendar, say JulianCalendar or LunarCalendar. The default GregorianCalendar constructor creates an object that represents the current time, as determined by the system clock: GregorianCalendar now = new GregorianCalendar(); Other constructors accept values to initialize the calendar. In the first statement below, we construct an object representing August 9, 1996; the second statement specifies both a date and a time, yielding an object that represents 9:01 AM, April 8, 1997. GregorianCalendar daphne = new GregorianCalendar(1996, Calendar.AUGUST, 9); GregorianCalendar sometime = new GregorianCalendar(1997, Calendar.APRIL, 8, 9, 1); // 9:01 AM We can also create a GregorianCalendar by setting specific fields using the set() method. The Calendar class contains a torrent of constants representing both calendar fields and field values. The first argument to the set() method is a field constant; the second argument is the new value for the field. GregorianCalendar kristen = new GregorianCalendar(); kristen.set(Calendar.YEAR, 1972); kristen.set(Calendar.MONTH, Calendar.MAY); kristen.set(Calendar.DATE, 20); A GregorianCalendar is created in the default time zone. Setting the time zone of the calendar is as easy as obtaining the desired TimeZone and giving it to the GregorianCalendar:
http://localhost/java/javaref/exp/ch07_03.htm (1 of 3) [20/12/2001 11:02:38]
[Chapter 7] 7.3 Dates
GregorianCalendar smokey = new GregorianCalendar(); smokey.setTimeZone(TimeZone.getTimeZone("MST")); To create a string representing a point in time, use the DateFormat class. Although DateFormat itself is abstract, it has several factory methods that return useful DateFormat subclass instances. To get a default DateFormat, simply call getInstance(). DateFormat plain = DateFormat.getInstance(); String now = plain.format(new Date()); // 4/9/97 6:06 AM Those of you who don't live on the West coast will notice that the example above produces a result that is not quite right. DateFormat instances stubbornly insist on using Pacific Standard Time, so you have to tell them what time zone you're in: DateFormat plain = DateFormat.getInstance(); plain.setTimeZone(TimeZone.getDefault()); String now = plain.format(new Date()); // 4/9/97 9:06 AM You can generate a date string or a time string, or both, using the getDateInstance(), getTimeInstance(), and getDateTimeInstance() factory methods. The argument to these methods describes what level of detail you'd like to see. DateFormat defines four constants representing detail levels: they are SHORT, MEDIUM, LONG, and FULL. There is also a DEFAULT, which is the same as MEDIUM. The code below creates three DateFormat instances: one to format a date, one to format a time, and one to format a date and time together. Note that getDateTimeInstance() requires two arguments: the first specifies how to format the date, the second says how to format the time. DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT); // 09-Apr-97 DateFormat tf = DateFormat.getTimeInstance(DateFormat.DEFAULT); // 9:18:27 AM DateFormat dtf = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); // Wednesday, April 09, 1997 9:18:27 o'clock AM EDT Formatting dates and times for other countries is just as easy. There are overloaded factory methods that accept a Locale argument: DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.FRANCE); // 9 avr. 97 DateFormat tf = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.GERMANY); // 9:27:49 DateFormat dtf = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY); // mercoledi 9 aprile 1997 9.27.49 GMT-04:00 To parse a string representing a date, we use the parse() method of the DateFormat class. The result is a Date object. The parsing algorithms are finicky, so it's safest to parse dates and times that are in the same format that is produced by the DateFormat. The parse() method throws a ParseException if it doesn't understand the string you give it. Occasionally other exceptions are thrown from the parse() method. To cover all the bases, catch NullPointerExceptions and StringIndexOutOfBoundsExceptions also.
http://localhost/java/javaref/exp/ch07_03.htm (2 of 3) [20/12/2001 11:02:38]
[Chapter 7] 7.3 Dates
try { Date d; DateFormat df; df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); d = df.parse("Wednesday, April 09, 1997 2:22:22 o'clock PM EST"); // ok df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); d = df.parse("09-Apr-97 2:22:22 PM"); //ok df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); d = df.parse("April 09, 1997 2:22:22 PM EST"); // ok d = df.parse("09-Apr-97 2:22:22 PM"); // ParseException - detail level mismatch } catch (Exception e) {} There's been a lot of talk about the "millenium bug" lately. This refers to the expected failure of software in the year 2000, when programs that use two digits to represent years interpret "00" as 1900 instead of 2000. Java is mostly safe from this error. The Date class has no specific field for year and is thus immune to this problem. The only time you'll run into this error in Java is when you use a DateFormat to parse a date string with a two-digit year. Two-digit years are automatically prefixed with 19. My advice is to always use a four-digit year when you expect to parse a date string.
Math Utilities
http://localhost/java/javaref/exp/ch07_03.htm (3 of 3) [20/12/2001 11:02:38]
Vectors and Hashtables
[Chapter 7] 7.4 Vectors and Hashtables
Chapter 7 Basic Utility Classes
7.4 Vectors and Hashtables Vectors and hashtables are collection classes. Each stores a group of objects according to a particular retrieval scheme. Aside from that, they are not particularly closely related things. A hashtable is a dictionary; it stores and retrieves objects by a key value. A vector, on the other hand, holds an ordered collection of elements. It's essentially a dynamic array. Both of these, however, have more subtle characteristics in common. First, they are two of the most useful aspects of the core Java distribution. Second, they both take full advantage of Java's dynamic nature at the expense of some of its more static type safety. If you work with dictionaries or associative arrays in other languages, you should understand how useful these classes are. If you are someone who has worked in C or another static language, you should find collections to be truly magical. They are part of what makes Java powerful and dynamic. Being able to work with lists of objects and make associations between them is an abstraction from the details of the types. It lets you think about the problems at a higher level and saves you from having to reproduce common structures every time you need them.
java.util.Vector A Vector is a dynamic array; it can grow to accommodate new items. You can also insert and remove elements at arbitrary positions within it. As with other mutable objects in Java, Vector is thread-safe. The Vector class works directly with the type Object, so we can use them with instances of any kind of class.[3] We can even put different kinds of Objects in a Vector together; the Vector doesn't know the difference. [3] In C++, where classes don't derive from a single Object class that supplies a base type and common methods, the elements of a collection would usually be derived from some common collectable class. This forces the use of multiple inheritance and brings its associated problems. As you might guess, this is where things get tricky. To do anything useful with an Object after we take it back out of a Vector, we have to cast it back (narrow) it to its original type. This can be done with safety in Java because the cast is checked at run-time. Java throws a ClassCastException if we try to cast an object to the wrong type. However, this need for casting means that your code must remember types or methodically test them with instanceof. That is the price we pay for having a completely dynamic collection class that operates on all types. http://localhost/java/javaref/exp/ch07_04.htm (1 of 6) [20/12/2001 11:02:38]
[Chapter 7] 7.4 Vectors and Hashtables
You might wonder if you can subclass Vector to produce a class that looks like a Vector, but that works on just one type of element in a type-safe way. Unfortunately, the answer is no. We could override Vector's methods to make a Vector that rejects the wrong type of element at run-time, but this does not provide any new compile-time, static type safety. In C++, templates provide a safe mechanism for parameterizing types by restricting the types of objects used at compile-time. The keyword generic is a reserved word in Java. This means that it's possible that future versions might support C++-style templates, using generic to allow statically checked parameterized types. We can construct a Vector with default characteristics and add elements to it using addElement() and insertElement(): Vector things = new Vector(); String one = "one"; String two = "two"; String three = "three"; things.addElement( one ); things.addElement( three ); things.insertElementAt( two, 1 ); things now contains three String objects in the order "one," "two," and "three." We can retrieve objects by their position with elementAt(), firstElement(), and lastElement(): String s1 = (String)things.firstElement(); String s3 = (String)things.lastElement(); String s2 = (String)things.elementAt(1);
// "one" // "three" // "two"
We have to cast each Object back to a String in order to assign it a String reference. ClassCastException is a type of RuntimeException, so we can neglect to guard for the exception if we are feeling confident about the type we are retrieving. Often, as in this example, you'll just have one type of object in the Vector. If we were unsure about the types of objects we were retrieving, we would want to be prepared to catch the ClassCastException or test the type explicitly with the instanceof operator. We can search for an item in a Vector with the indexOf() method: int i = things.indexOf( three );
// i = 2
indexOf() returns a value of -1 if the object is not found. As a convenience, we can also use contains() simply to test for the presence of the object. Finally, removeElement() removes a specified Object from the Vector: things.removeElement( two );
http://localhost/java/javaref/exp/ch07_04.htm (2 of 6) [20/12/2001 11:02:38]
[Chapter 7] 7.4 Vectors and Hashtables
The element formerly at position three now becomes the second element. The size() method reports the number of objects currently in the Vector. You might think of using this to loop through all elements of a Vector, using elementAt() to get at each element. This works just fine, but there is a more general way to operate on a complete set of elements like those in a Vector.
java.util.Enumeration The java.util.Enumeration interface can be used by any sort of set to provide serial access to its elements. An object that implements the Enumeration interface presents two methods: nextElement() and hasMoreElements(). nextElement() returns an Object type, so it can be used with any kind of collection. As with taking objects from a Vector, you need to know or determine what the objects are and cast them to the appropriate types before using them. Enumeration is useful because any type of object can implement the interface and then use it to provide access to its elements. If you have an object that handles a set of values, you should think about implementing the Enumeration interface. Simply provide a hasMoreElements() test and a nextElement() iterator and declare that your class implements java.util.Enumeration. One advantage of an Enumeration is that you don't have to provide all values up front; you can provide each value as it's requested with nextElement(). And since Enumeration is an interface, you can write general routines that operate on all of the elements Enumeration. An Enumeration does not guarantee the order in which elements are returned, however, so if order is important you don't want to use an Enumeration. You can iterate through the elements in an Enumeration only once; there is no way to reset it to the beginning or move backwards through the elements. A Vector returns an Enumeration of its contents when we call the elements() method: Enumeration e = things.elements(); while ( e.hasMoreElements() ) { String s = (String)e.nextElement(); System.out.println( s ): } The above code loops three times, as call nextElement(), to fetch our strings. The actual type of object returned by elements() is a VectorEnumeration, but we don't have to worry about that. We can always refer to an Enumeration simply by its interface. Note that Vector does not implement the Enumeration interface. If it did, that would put a serious limitation on Vector because we could cycle through the elements in it only once. That's clearly not the purpose of a Vector, which is why Vector instead provides a method that returns an Enumeration.
http://localhost/java/javaref/exp/ch07_04.htm (3 of 6) [20/12/2001 11:02:38]
[Chapter 7] 7.4 Vectors and Hashtables
java.util.Hashtable As I said earlier, a hashtable is a dictionary, similar to an associative array. A hashtable stores and retrieves elements with key values; they are very useful for things like caches and minimalist databases. When you store a value in a hashtable, you associate a key with that value. When you need to look up the value, the hashtable retrieves it efficiently using the key. The name hashtable itself refers to how the indexing and storage of elements is performed, as we'll discuss shortly. First I want to talk about how to use a hashtable. The java.util.Hashtable class implements a hashtable that, like Vector, operates on the type Object. A Hashtable stores an element of type Object and associates it with a key, also of type Object. In this way, we can index arbitrary types of elements using arbitrary types as keys. As with Vector, casting is generally required to narrow objects back to their original type after pulling them out of a hashtable. A Hashtable is quite easy to use. We can use the put() method to store items: Hashtable dates = new Hashtable(); dates.put( "christmas", new GregorianCalendar( 1997, Calendar.DECEMBER, 25 ) ); dates.put( "independence", new GregorianCalendar( 1997, Calendar.JULY, 4 ) ); dates.put( "groundhog", new GregorianCalendar( 1997, Calendar.FEBRUARY, 2 ) ); First we create a new Hashtable. Then we add three GregorianCalendar objects to the hashtable, using String objects as keys. The key is the first argument to put(); the value is the second. Only one value can be stored per key. If we try to store a second object under a key that already exists in the Hashtable, the old element is booted out and replaced by the new one. The return value of the put() method is normally null, but if the call to put() results in replacing an element, the method instead returns the old stored Object. We can now use the get() method to retrieve each of the above dates by name, using the String key by which it was indexed: GregorianCalendar g = (GregorianCalendar)dates.get( "christmas" ); The get() method returns a null value if no element exists for the given key. The cast is required to narrow the returned object back to type GregorianCalendar. I hope you can see the advantage of using a Hashtable over a regular array. Each value is indexed by a key instead of a simple number, so unlike a simple array, we don't have to remember where each GregorianCalendar is stored. Once we've put a value in a Hashtable, we can take it back out with the remove() method, again using the key to access the value: dates.remove("christmas"); http://localhost/java/javaref/exp/ch07_04.htm (4 of 6) [20/12/2001 11:02:38]
[Chapter 7] 7.4 Vectors and Hashtables
We can test for the existence of a key with containsKey(): if ( dates.containsKey( "groundhog" ) ) {
// yes
Just like with a Vector, we're dealing with a set of items. Actually, we're dealing with two sets: keys and values. The Hashtable class has two methods, keys() and elements(), for getting at these sets. The keys() method returns an Enumeration of the keys for all of the elements in the Hashtable. We can use this Enumeration to loop through all of the keys: for (Enumeration e = dates.keys(); e.hasMoreElements(); ) { String key = (String)e.nextElement(); ... } Similarly, elements() provides an Enumeration of the elements themselves. Hashcodes and key values If you've used a hashtable before, you've probably guessed that there's more going on behind the scenes than I've let on so far. An element in a hashtable is not associated with its key by identity, but by something called a hashcode. Every object in Java has an identifying hashcode value determined by its hashCode() method, which is inherited from the Object class. When you store an element in a hashtable, the hashcode of the key object registers the element internally. Later, when you retrieve the item, that same hashcode looks it up efficiently. A hashcode is usually a random-looking integer value based on the contents of an object, so it's different for different instances of a class. Two objects that have different hashcodes serve as unique keys in a hashtable; each object can reference a different stored object. Two objects that have the same hashcode value, on the other hand, appear to a hashtable as the same key. They can't coexist as keys to different objects in the hashtable. Generally, we want our object instances to have unique hash codes, so we can put arbitrary items in a hashtable and index them with arbitrary keys. The default hashCode() method in the Object class simply assigns each object instance a unique number to be used as a hashcode. If a class does not override this method, each instance of the class will have a unique hashcode. This is sufficient for most objects. However, it's also useful to allow equivalent objects to serve as equivalent keys. String objects provide a good example of this case. Although Java does its best to consolidate them, a literal string that appears multiple times in Java source code is often represented by different String objects at run-time. If each of these String objects has a different hash code, even though the literal value is the same, we could not use strings as keys in a hashtable, like we did the in above examples. The solution is to ensure that equivalent String objects return the same hashcode value so that they can act as equivalent keys. The String class overrides the default hashCode() method so that equivalent String objects return the same hash code, while different String objects have unique hashcodes. This is possible because String objects are immutable; the contents can't change, so neither can the http://localhost/java/javaref/exp/ch07_04.htm (5 of 6) [20/12/2001 11:02:38]
[Chapter 7] 7.4 Vectors and Hashtables
hashcode. A few other classes in the Java API also override the default hashCode() method in order to provide equivalent hashcodes for equivalent objects. For example, each of the primitive wrapper classes provides a hashCode() method for this purpose. Other objects likely to be used as hashtable keys, such as Color, Date, File, and URL, also implement their own hashCode()methods. So now maybe you're wondering when you need to override the default hashCode() method in your objects. If you're creating a class to use for keys in a hashtable, think about whether the class supports the idea of "equivalent objects." If so, you should implement a hashCode() method that returns the same hashcode value for equivalent objects. To accomplish this, you need to define the hashcode of an object to be some suitably complex and arbitrary function of the contents of that object. The only criterion for the function is that it should be almost certain to provide different values for different contents of the object. Because the capacity of an integer is limited, hashcode values are not guaranteed to be unique. This limitation is not normally a problem though, as there are 2^32 possible hashcodes to choose from. The more sensitive the hashcode function is to small differences in the contents the better. A hashtable works most efficiently when the hashcode values are as randomly and evenly distributed as possible. As an example, you could produce a hashcode for a String object by adding the character values at each position in the string and multiplying the result by some number, producing a large random-looking integer.
java.util.Dictionary java.util.Dictionary is the abstract superclass of Hashtable. It lays out the basic get(), put(), and remove() functionality for dictionary-style collections. You could derive other types of dictionaries from this class. For example, you could implement a dictionary with a different storage format, such as a binary tree.
Dates
http://localhost/java/javaref/exp/ch07_04.htm (6 of 6) [20/12/2001 11:02:38]
Properties
[Chapter 7] 7.5 Properties
Chapter 7 Basic Utility Classes
7.5 Properties The java.util.Properties class is a specialized hashtable for strings. Java uses the Properties object to replace the environment variables used in other programming environments. You can use a Properties table to hold arbitrary configuration information for an application in an easily accessible format. The Properties object can also load and store information using streams (see Chapter 8, Input/Output Facilities for information on streams). Any string values can be stored as key/value pairs in a Properties table. However, the convention is to use a dot-separated naming hierarchy to group property names into logical structures, as is done with X resources on UNIX systems.[4] The java.lang.System class provides system-environment information in this way, through a system Properties table I'll describe shortly. [4] Unfortunately, this is just a naming convention right now, so you can't access logical groups of properties as you can with X resources. Create an empty Properties table and add String key/value pairs just as with any Hashtable: Properties props = new Properties(); props.put("myApp.xsize", "52"); props.put("myApp.ysize", "79"); Thereafter, you can retrieve values with the getProperty()method: String xsize = props.getProperty( "myApp.xsize" ); If the named property doesn't exist, getProperty() returns null. You can get an Enumeration of the property names with the propertyNames() method: for ( Enumeration e = props.propertyNames(); e.hasMoreElements; ) { String name = e.nextElement(); ... }
http://localhost/java/javaref/exp/ch07_05.htm (1 of 3) [20/12/2001 11:02:39]
[Chapter 7] 7.5 Properties
Default Values When you create a Properties table, you can specify a second table for default property values: Properties defaults; ... Properties props = new Properties( defaults ); Now when you call getProperty(), the method searches the default table if it doesn't find the named property in the current table. An alternative version of getProperty() also accepts a default value; this value is returned if the property is not found in the current list or in the default list: String xsize = props.getProperty( "myApp.xsize", "50" );
Loading and Storing You can save a Properties table to an OutputStream using the save() method. The property information is output in flat ASCII format. Continuing with the above example, output the property information to System.out as follows: props.save( System.out, "Application Parameters" ); As we'll discuss in Chapter 8, Input/Output Facilities, System.out is a standard output stream similar to C's stdout. We could also save the information to a file by using a FileOutputStream as the first argument to save(). The second argument to save() is a String that is used as a header for the data. The above code outputs something like the following to System.out: #Application Parameters #Mon Feb 12 09:24:23 CST 1997 myApp.ysize=79 myApp.xsize=52 The load() method reads the previously saved contents of a Properties object from an InputStream: FileInputStream fin; ... Properties props = new Properties() props.load( fin ); The list() method is useful for debugging. It prints the contents to an OutputStream in a format that is more human-readable but not retrievable by load().
http://localhost/java/javaref/exp/ch07_05.htm (2 of 3) [20/12/2001 11:02:39]
[Chapter 7] 7.5 Properties
System Properties The java.lang.System class provides access to basic system environment information through the static System.getProperty() method. This method returns a Properties table that contains system properties. System properties take the place of environment variables in other programming environments. Table 7.7 summarizes system properties that are guaranteed to be defined in any Java environment. Table 7.7: System Properties System Property Meaning Vendor-specific string java.vendor URL of vendor java.vendor.url Java version java.version Java installation directory java.home java.class.version Java class version The class path java.class.path Operating-system name os.name Operating-system architecture os.arch Operating-system version os.version File separator (such as "/" or " \") file.separator Path separator (such as ":" or ";") path.separator Line separator (such as "\n" or "\r\n") line.separator User account name user.name User's home directory user.home Current working directory user.dir Applets are, by current Web browser conventions, prevented from reading the following properties: java.home, java.class.path, user.name, user.home, and user.dir. As you'll see in the next section, these restrictions are implemented by a SecurityManager object.
Vectors and Hashtables
http://localhost/java/javaref/exp/ch07_05.htm (3 of 3) [20/12/2001 11:02:39]
The Security Manager
[Chapter 7] 7.6 The Security Manager
Chapter 7 Basic Utility Classes
7.6 The Security Manager As I described in Chapter 1, Yet Another Language?, a Java application's access to system resources, such as the display, the filesystem, threads, external processes, and the network, can be controlled at a single point with a security manager. The class that implements this functionality in the Java API is the java.lang.SecurityManager class. An instance of the SecurityManager class can be installed once, and only once, in the life of the Java run-time environment. Thereafter, every access to a fundamental system resource is filtered through specific methods of the SecurityManager object by the core Java packages. By installing a specialized SecurityManager, we can implement arbitrarily complex (or simple) security policies for allowing access to individual resources. When the Java run-time system starts executing, it's in a wide-open state until a SecurityManager is installed. The "null" security manager grants all requests, so the Java virtual environment can perform any activity with the same level of access as other programs running under the user's authority. If the application that is running needs to ensure a secure environment, it can install a SecurityManager with the static System.setSecurityManager() method. For example, a Java-enabled Web browser like Netscape Navigator installs a SecurityManager before it runs any Java applets. java.lang.SecurityManager must be subclassed to be used. This class does not actually contain any abstract methods; it's abstract as an indication that its default implementation is not very useful. By default, each security method in SecurityManager is implemented to provide the strictest level of security. In other words, the default SecurityManager simply rejects all requests. The following example, MyApp, installs a trivial subclass of SecurityManager as one of its first activities: class FascistSecurityManager extends SecurityManager { } public class MyApp { public static void main( Strings [] args ) { System.setSecurityManager( new FascistSecurityManager() ); // No access to files, network, windows, etc. ... } http://localhost/java/javaref/exp/ch07_06.htm (1 of 3) [20/12/2001 11:02:39]
[Chapter 7] 7.6 The Security Manager
} In the above scenario, MyApp does little aside from reading from System.in and writing to System.out. Any attempts to read or write files, access the network, or even open an window, results in a SecurityException being thrown. After this draconian SecurityManager is installed, it's impossible to change the SecurityManager in any way. The security of this feature is not dependent on the SecurityManager; you can't replace or modify the SecurityManager under any circumstances. The upshot of this is that you have to install one that handles all your needs up front. To do something more useful, we can override the methods that are consulted for access to various kinds of resources. Table 7.7 lists some of the more important access methods. You should not normally have to call these methods yourself, although you could. They are called by the core Java classes before granting particular types of access. Table 7.8: SecurityManager Methods Method checkAccess(Thread g)
Can I...? Access this thread?
checkExit(int status)
Execute a System.exit()?
exec() this process? Read a file? checkRead(String file) Write a file? checkWrite(String file) Delete a file? checkDelete(String file) checkConnect(String host, int port) Connect a socket to a host? Create a server socket? checkListen(int port) checkAccept(String host, int port) Accept this connection? Access this system property? checkPropertyAccess(String key) checkTopLevelWindow(Object window) Create this new top-level window? checkExec(String cmd)
All these methods, with the exception of checkTopLevelWindow(), simply return to grant access. If access is not granted, they throw a SecurityException. checkTopLevelWindow() returns a boolean value. A value of true indicates the access is granted; a value of false indicates the access is granted with the restriction that the new window should provide a warning border that serves to identify it as an untrusted window. Let's implement a silly SecurityManager that allows only files beginning with the name foo to be read: class
FooFileSecurityManager extends SecurityManager {
public void checkRead( String s ) { if ( !s.startsWith("foo") )
http://localhost/java/javaref/exp/ch07_06.htm (2 of 3) [20/12/2001 11:02:39]
[Chapter 7] 7.6 The Security Manager
throw new SecurityException("Access to non-foo file: " + s + " not allowed." ); } } Once the FooFileSecurityManager is installed, any attempt to read a filename other than foo* from any class will fail and cause a SecurityException to be thrown. All other security methods are inherited from SecurityManager, so they are left at their default restrictiveness. All restrictions placed on applets by an applet-viewer application are enforced through a SecurityManager, which allows untrusted code loaded from over the network to be executed safely. The restrictions placed on applets are currently fairly harsh. As time passes and security considerations related to applets are better understood and accepted, the applet API will hopefully become more powerful and allow forms of persistence and access to designated public information.
Properties
http://localhost/java/javaref/exp/ch07_06.htm (3 of 3) [20/12/2001 11:02:39]
Internationalization
[Chapter 7] 7.7 Internationalization
Chapter 7 Basic Utility Classes
7.7 Internationalization In order to deliver on the promise "Write once, run anywhere," the engineers at Java designed the famous Java Virtual Machine. True, your program will run anywhere there is a JVM, but what about users in other countries? Will they have to know English to use your application? Java 1.1 answers that question with a resounding "no," backed up by various classes that are designed to make it easy for you to write a "global" application. In this section we'll talk about the concepts of internationalization and the classes that support them.
java.util.Locale Internationalization programming revolves around the Locale class. The class itself is very simple; it encapsulates a country code, a language code, and a rarely used variant code. Commonly used languages and countries are defined as constants in the Locale class. (It's ironic that these names are all in English.) You can retrieve the codes or readable names, as follows: Locale l = Locale.ITALIAN; System.out.println(l.getCountry()); // IT System.out.println(l.getDisplayCountry()); // Italy System.out.println(l.getLanguage()); // it System.out.println(l.getDisplayLanguage()); // Italian The country codes comply with ISO 639. A complete list of country codes is at http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt. The language codes comply with ISO 3166. A complete list of language codes is at http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html. There is no official set of variant codes; they are designated as vendor-specific or platform-specific. Various classes throughout the Java API use a Locale to decide how to represent themselves. We have already seen how the DateFormat class uses Locales to determine how to format and parse strings.
Resource Bundles If you're writing an internationalized program, you want all the text that is displayed by your application to be in the correct language. Given what you have just learned about Locale, you could print out different messages by testing the Locale. This gets cumbersome quickly, however, because the messages for all Locales are embedded in your source code. ResourceBundle and its subclasses offer a cleaner, more http://localhost/java/javaref/exp/ch07_07.htm (1 of 7) [20/12/2001 11:02:40]
[Chapter 7] 7.7 Internationalization
flexible solution. A ResourceBundle is a collection of objects that your application can access by name, much like a Hashtable with String keys. The same ResourceBundle may be defined for many different Locales. To get a particular ResourceBundle, call the factory method ResourceBundle.getBundle(), which accepts the name of a ResourceBundle and a Locale. The following example gets a ResourceBundle for two Locales, retrieves a string message from it, and prints the message. We'll define the ResourceBundles later to make this example work. import java.util.*; public class Hello { public static void main(String[] args) { ResourceBundle bun; bun = ResourceBundle.getBundle("Message", Locale.ITALY); System.out.println(bun.getString("HelloMessage")); bun = ResourceBundle.getBundle("Message", Locale.US); System.out.println(bun.getString("HelloMessage")); } } The getBundle() method throws the runtime exception MissingResourceException if an appropriate ResourceBundle cannot be located. Locales are defined in three ways. They can be stand-alone classes, in which case they will either be subclasses of ListResourceBundle or direct subclasses of ResourceBundle. They can also be defined by a property file, in which case they will be represented at run-time by a PropertyResourceBundle object. When you call ResourceBundle.getBundle(), either a matching class is returned or an instance of PropertyResourceBundle corresponding to a matching property file. The algorithm used by getBundle() is based on appending the country and language codes of the requested Locale to the name of the resource. Specifically, it searches for resources using this order: name_language_country_variant name_language_country name_language name name_default-language_default-country_default-variant name_default-language_default-country name_default-language In the example above, when we try to get the ResourceBundle named Message, specific to Locale.ITALY, it searches for the following names (note that there are no variant codes in the Locales we are using): Message_it_IT Message_it Message Message_en_US
http://localhost/java/javaref/exp/ch07_07.htm (2 of 7) [20/12/2001 11:02:40]
[Chapter 7] 7.7 Internationalization
Message_en Let's define the Message_it_IT ResourceBundle now, using a subclass of ListResourceBundle. import java.util.*; public class Message_it_IT extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { {"HelloMessage", "Buon giorno, world!"}, {"OtherMessage", "Ciao."}, }; } ListResourceBundle makes it easy to define a ResourceBundle class; all we have to do is override the getContents() method. Now let's define a ResourceBundle for Locale.US. This time, we'll make a property file. Save the following data in a file called Message_en_US.properties: HelloMessage=Hello, world! OtherMessage=Bye. So what happens if somebody runs your program in Locale.FRANCE, and there is no ResourceBundle defined for that Locale? To avoid a run-time MissingResourceException, it's a good idea to define a default ResourceBundle. So in our example, you could change the name of the property file to Message.properties. That way, if a language-specific or country-specific ResourceBundle cannot be found, your application can still run.
java.text The java.text package includes, among other things, a set of classes designed for generating and parsing string representations of objects. We have already seen one of these classes, DateFormat. In this section we'll talk about the other format classes, NumberFormat, ChoiceFormat, and MessageFormat. The NumberFormat class can be used to format and parse currency, percents, or plain old numbers. Like DateFormat, NumberFormat is an abstract class. However, it has several useful factory methods. For example, to generate currency strings, use getCurrencyInstance(): double salary = 1234.56; String here = NumberFormat.getCurrencyInstance().format(salary); // $1,234.56 String italy = http://localhost/java/javaref/exp/ch07_07.htm (3 of 7) [20/12/2001 11:02:40]
[Chapter 7] 7.7 Internationalization
NumberFormat.getCurrencyInstance(Locale.ITALY).format(salary); // L 1.234,56 The first statement generates an American salary, with a dollar sign, a comma to separate thousands, and a period as a decimal point. The second statement presents the same string in Italian, with a lire sign, a period to separate thousands, and a comma as a decimal point. Remember that the NumberFormat worries about format only; it doesn't attempt to do currency conversion. (Among other things, that would require access to a dynamically updated table and exchange rates: a good opportunity for a Java Bean, but too much to ask of a simple formatter.) Likewise, getPercentInstance() returns a formatter you can use for generating and parsing percents. If you do not specify a Locale when calling a getInstance() method, the default Locale is used. NumberFormat pf = NumberFormat.getPercentInstance(); System.out.println(pf.format(progress)); // 44% try { System.out.println(pf.parse("77.2%")); // 0.772 } catch (ParseException e) {} And if you just want to generate and parse plain old numbers, use a NumberFormat returned by getInstance() or its equivalent, getNumberInstance(). NumberFormat guiseppe = NumberFormat.getInstance(Locale.ITALY); NumberFormat joe = NumberFormat.getInstance(); // defaults to Locale.US try { double theValue = guiseppe.parse("34.663,252").doubleValue(); System.out.println(joe.format(theValue)); // 34,663.252 } catch (ParseException e) {} We use guiseppe to parse a number in Italian format (periods separate thousands, comma as the decimal point). The return type of parse() is Number, so we use the doubleValue() method to retrieve the value of the Number as a double. Then we use joe to format the number correctly for the default (US) locale. Table 7.8 summarizes the factory methods for text formatters in the java.text package. Table 7.9: Format Factory Methods Factory Method DateFormat.getDateInstance() DateFormat.getDateInstance(int style) DateFormat.getDateInstance(int style, Locale aLocale) DateFormat.getDateTimeInstance() DateFormat.getDateTimeInstance(int dateStyle, int timeStyle)
http://localhost/java/javaref/exp/ch07_07.htm (4 of 7) [20/12/2001 11:02:40]
[Chapter 7] 7.7 Internationalization
DateFormat.getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale) DateFormat.getInstance() DateFormat.getTimeInstance() DateFormat.getTimeInstance(int style) DateFormat.getTimeInstance(int style, Locale aLocale) NumberFormat.getCurrencyInstance() NumberFormat.getCurrencyInstance(Locale inLocale) NumberFormat.getInstance() NumberFormat.getInstance(Locale inLocale) NumberFormat.getNumberInstance() NumberFormat.getNumberInstance(Locale inLocale) NumberFormat.getPercentInstance() NumberFormat.getPercentInstance(Locale inLocale) Thus far we've seen how to format dates and numbers as text. Now we'll take a look at a class, ChoiceFormat, that maps numerical ranges to text. ChoiceFormat is constructed by specifying the numerical ranges and the strings that correspond to them. One constructor accepts an array of doubles and an array of Strings, where each string corresponds to the range running from the matching number up through the next number: double[] limits = {0, 20, 40}; String[] labels = {"young", "less young", "old"}; ChoiceFormat cf = new ChoiceFormat(limits, labels); System.out.println(cf.format(12)); // young System.out.println(cf.format(26)); // less young You can specify both the limits and the labels using a special string in another ChoiceFormat constructor: ChoiceFormat cf = new ChoiceFormat("0#young|20#less young|40#old"); System.out.println(cf.format(40)); // old System.out.println(cf.format(50)); // old The limit and value pairs are separated by pipe characters (|; also known as "vertical bar"), while the number sign serves to separate each limit from its corresponding value. To complete our discussion of the formatting classes, we'll take a look at another class, MessageFormat, that helps you construct human-readable messages. To construct a MessageFormat, pass it a pattern string. A pattern string is a lot like the string you feed to printf() in C, although the syntax is different. Arguments are delineated by curly brackets, and may include information about how they should be formatted. Each argument consists of a number, an optional type, and an optional style. These are summarized in table Table 7.9.
http://localhost/java/javaref/exp/ch07_07.htm (5 of 7) [20/12/2001 11:02:40]
[Chapter 7] 7.7 Internationalization
Table 7.10: MessageFormat arguments Type Styles choice pattern date
short, medium, long, full, pattern
number integer, percent, currency, pattern time
short, medium, long, full, pattern
Let's use an example to clarify all of this. MessageFormat mf = new MessageFormat("You have {0} messages."); Object[] arguments = {"no"}; System.out.println(mf.format(arguments)); // You have no messages. We start by constructing a MessageFormat object; the argument to the constructor is the pattern on which messages will be based. The special incantation {0} means "in this position, substitute element 0 from the array passed as an argument to the format() method." Thus, we construct a MessageFormat object with a pattern, which is a template on which messages are based. When we generate a message, by calling format(), we pass in values to fill the blank spaces in the template. In this case, we pass the array arguments[] to mf.format; this substitutes arguments[0], yielding the result "You have no messages." Let's try this example again, except we'll show how to format a number and a date instead of a string argument. MessageFormat mf = new MessageFormat( "You have {0, number, integer} messages on {1, date, long}."); Object[] arguments = {new Integer(93), new Date()}; System.out.println(mf.format(arguments)); // You have 93 messages on April 10, 1997. In this example, we need to fill in two spaces in the template, and therefore need two elements in the arguments[] array. Element 0 must be a number, and is formatted as an integer. Element 1 must be a Date, and will be printed in the long format. When we call format(), the arguments[] array supplies these two values. This is still sloppy. What if there is only one message? To make this grammatically correct, we can embed a ChoiceFormat-style pattern string in our MessageFormat pattern string. MessageFormat mf = new MessageFormat( "You have {0, number, integer} message{0, choice, 0#s|1#|2#s}."); Object[] arguments = {new Integer(1)}; System.out.println(mf.format(arguments)); // You have 1 message. In this case, we use element 0 of arguments[] twice: once to supply the number of messages, and once to provide input to the ChoiceFormat pattern. The pattern says to add an "s" if argument 0 has the value zero, or is two or more. http://localhost/java/javaref/exp/ch07_07.htm (6 of 7) [20/12/2001 11:02:40]
[Chapter 7] 7.7 Internationalization
Finally, a few words on how to be clever. If you want to write international programs, you can use resource bundles to supply the strings for your MessageFormat objects. This way, you can automatically format messages that are in the appropriate language with dates and other language-dependent fields handled appropriately. In this context, it's helpful to realize that messages don't need to read elements from the array in order. In English, you would say "Disk C has 123 files"; in some other language, you might say "123 files are on Disk C." You could implement both messages with the same set of arguments: MessageFormat m1 = new MessageFormat( "Disk {0} has {1, number, integer} files."); MessageFormat m2 = new MessageFormat( "{1, number, integer} files are on disk {0}."); Object[] arguments = {"C", new Integer(123)}; In real life, you'd only use a single MessageFormat object, initialized with a string taken from a resource bundle.
The Security Manager
http://localhost/java/javaref/exp/ch07_07.htm (7 of 7) [20/12/2001 11:02:40]
Input/Output Facilities
[Chapter 8] 8.2 Files
Chapter 8 Input/Output Facilities
8.2 Files Unless otherwise restricted, a Java application can read and write to the host filesystem with the same level of access as the user who runs the Java interpreter. Java applets and other kinds of networked applications can, of course, be restricted by the SecurityManager and cut off from these services. We'll discuss applet access at the end of this section. First, let's take a look at the tools for basic file access. Working with files in Java is still somewhat problematic. The host filesystem lies outside of Java's virtual environment, in the real world, and can therefore still suffer from architecture and implementation differences. Java tries to mask some of these differences by providing information to help an application tailor itself to the local environment; I'll mention these areas as they occur.
java.io.File The java.io.File class encapsulates access to information about a file or directory entry in the filesystem. It gets attribute information about a file, lists the entries in a directory, and performs basic filesystem operations like removing a file or making a directory. While the File object handles these tasks, it doesn't provide direct access for reading and writing file data; there are specialized streams for that purpose. File constructors You can create an instance of File from a String pathname as follows: File fooFile = new File( "/tmp/foo.txt" ); File barDir = new File( "/tmp/bar" ); You can also create a file with a relative path like: File f = new File( "foo" ); In this case, Java works relative to the current directory of the Java interpreter. You can determine the current directory by checking the user.dir property in the System Properties list (System.getProperty('user.dir')). An overloaded version of the File constructor lets you specify the directory path and filename as separate String objects: File fooFile = new File( "/tmp", "foo.txt" ); With yet another variation, you can specify the directory with a File object and the filename with a String: File tmpDir = new File( "/tmp" ); http://localhost/java/javaref/exp/ch08_02.htm (1 of 7) [20/12/2001 11:02:41]
[Chapter 8] 8.2 Files
File fooFile = new File ( tmpDir, "foo.txt" ); None of the File constructors throw any exceptions. This means the object is created whether or not the file or directory actually exists; it isn't an error to create a File object for an nonexistent file. You can use the exists() method to find out whether the file or directory exists. Path localization One of the reasons that working with files in Java is problematic is that pathnames are expected to follow the conventions of the local filesystem. Java's designers intend to provide an abstraction that deals with most system-dependent filename features, such as the file separator, path separator, device specifier, and root directory. Unfortunately, not all of these features are implemented in the current version. On some systems, Java can compensate for differences such as the direction of the file separator slashes in the above string. For example, in the current implementation on Windows platforms, Java accepts paths with either forward slashes or backslashes. However, under Solaris, Java accepts only paths with forward slashes. Your best bet is to make sure you follow the filename conventions of the host filesystem. If your application is just opening and saving files at the user's request, you should be able to handle that functionality with the java.awt.FileDialog class. This class encapsulates a graphical file-selection dialog box. The methods of the FileDialog take care of system-dependent filename features for you. If your application needs to deal with files on its own behalf, however, things get a little more complicated. The File class contains a few static variables to make this task easier. File.separator defines a String that specifies the file separator on the local host (e.g., "/" on UNIX and Macintosh systems and "\" on Windows systems), while File.separatorChar provides the same information in character form. File.pathSeparator defines a String that separates items in a path (e.g., ":" on UNIX systems; ";" on Macintosh and Windows systems); File.pathSeparatorChar provides the information in character form. You can use this system-dependent information in several ways. Probably the simplest way to localize pathnames is to pick a convention you use internally, say "/", and do a String replace to substitute for the localized separator character: // We'll use forward slash as our standard String path = "mail/1995/june/merle"; path = path.replace('/', File.separatorChar); File mailbox = new File( path ); Alternately, you could work with the components of a pathname and built the local pathname when you need it: String [] path = { "mail", "1995", "june", "merle" }; StringBuffer sb = new StringBuffer(path[0]); for (int i=1; i< path.length; i++) sb.append( File.separator + path[i] ); File mailbox = new File( sb.toString() ); One thing to remember is that Java interprets the backslash character (\) as an escape character when used in a String. To get a backslash in a String, you have to use " \\". File methods Once we have a valid File object, we can use it to ask for information about the file itself and to perform standard operations on it. A number of methods lets us ask certain questions about the File. For example, isFile() returns
http://localhost/java/javaref/exp/ch08_02.htm (2 of 7) [20/12/2001 11:02:41]
[Chapter 8] 8.2 Files
true if the File represents a file, while isDirectory() returns true if it's a directory. isAbsolute() indicates whether the File has an absolute or relative path specification. The components of the File pathname are available through the following methods: getName(), getPath(), getAbsolutePath(), and getParent(). getName() returns a String for the filename without any directory information; getPath() returns the directory information without the filename. If the File has an absolute path specification, getAbsolutePath() returns that path. Otherwise it returns the relative path appended to the current working directory. getParent() returns the parent directory of the File. Interestingly, the string returned by getPath() or getAbsolutePath() may not be the same, case-wise, as the actual name of the file. You can retrieve the case-correct version of the file's path using getCanonicalPath(). In Windows 95, for example, you can create a File object whose getAbsolutePath() is C:\Autoexec.bat but whose getCanonicalPath() is C:\AUTOEXEC.BAT. We can get the modification time of a file or directory with lastModified(). This time value is not useful as an absolute time; you should use it only to compare two modification times. We can also get the size of the file in bytes with length(). Here's a fragment of code that prints some information about a file: File fooFile = new File( "/tmp/boofa" ); String type = fooFile.isFile() ? "File " : "Directory "; String name = fooFile.getName(); long len = fooFile.length(); System.out.println(type + name + ", " + len + " bytes " ); If the File object corresponds to a directory, we can list the files in the directory with the list() method: String [] files = fooFile.list(); list() returns an array of String objects that contains filenames. (You might expect that list() would return an Enumeration instead of an array, but it doesn't.) If the File refers to a nonexistent directory, we can create the directory with mkdir() or mkdirs(). mkdir() creates a single directory; mkdirs() creates all of the directories in a File specification. Use renameTo() to rename a file or directory and delete() to delete a file or directory. Note that File doesn't provide a method to create a file; creation is handled with a FileOutputStream as we'll discuss in a moment. Table 8.1 summarizes the methods provided by the File class. Table 8.1: File Methods Method
Return type Description Is the file (or directory) readable? canRead() boolean Is the file (or directory) writable? canWrite() boolean Deletes the file (or directory) delete() boolean Does the file (or directory) exist? exists() boolean Returns the absolute path of the file (or directory) getAbsolutePath() String Returns the absolute, case-correct path of the file (or directory) getCanonicalPath() String Returns the name of the file (or directory) getName() String Returns the name of the parent directory of the file (or directory) getParent() String Returns the path of the file (or directory) getPath() String Is the filename (or directory name) absolute? isAbsolute() boolean http://localhost/java/javaref/exp/ch08_02.htm (3 of 7) [20/12/2001 11:02:41]
[Chapter 8] 8.2 Files
isDirectory()
boolean
isFile()
boolean
Is the item a directory? Is the item a file?
lastModified()
long
Returns the last modification time of the file (or directory)
length() list()
Returns the length of the file long String [] Returns a list of files in the directory Creates the directory boolean
mkdir() mkdirs() boolean renameTo(File dest) boolean
Creates all directories in the path Renames the file (or directory)
File Streams Java provides two specialized streams for reading and writing files in the filesystem: FileInputStream and FileOutputStream. These streams provide the basic InputStream and OutputStream functionality applied to reading and writing the contents of files. They can be combined with the filtered streams described earlier to work with files in the same way we do other stream communications. Because FileInputStream is a subclass of InputStream, it inherits all standard InputStream functionality for reading the contents of a file. FileInputStream provides only a low-level interface to reading data, however, so you'll typically wrap another stream like a DataInputStream around the FileInputStream. You can create a FileInputStream from a String pathname or a File object: FileInputStream foois = new FileInputStream( fooFile ); FileInputStream passwdis = new FileInputStream( "/etc/passwd" ); When you create a FileInputStream, Java attempts to open the specified file. Thus, the FileInputStream constructors can throw a FileNotFoundException if the specified file doesn't exist, or an IOException if some other I/O error occurs. You should be sure to catch and handle these exceptions in your code. When the stream is first created, its available() method and the File object's length() method should return the same value. Be sure to call the close() method when you are done with the file. To read characters from a file, you can wrap an InputStreamReader around a FileInputStream. If you want to use the default character encoding scheme, you can use the FileReader class instead, which is provided as a convenience. FileReader works just like FileInputStream, except that it reads characters instead of bytes and wraps a Reader instead of an InputStream. The following class, ListIt, is a small utility that displays the contents of a file or directory to standard output: import java.io.*; class ListIt { public static void main ( String args[] ) throws Exception { File file = new File( args[0] ); if ( !file.exists() || !file.canRead() ) { System.out.println( "Can't read " + file ); return; } if ( file.isDirectory() ) {
http://localhost/java/javaref/exp/ch08_02.htm (4 of 7) [20/12/2001 11:02:41]
[Chapter 8] 8.2 Files
String [] files = file.list(); for (int i=0; i< files.length; i++) System.out.println( files[i] ); } else try { FileReader fr = new FileReader ( file ); BufferedReader in = new BufferedReader( fr ); String line; while ((line = in.readLine()) != null) System.out.println(line); } catch ( FileNotFoundException e ) { System.out.println( "File Disappeared" ); } } } ListIt constructs a File object from its first command-line argument and tests the File to see if it exists and is readable. If the File is a directory, ListIt prints the names of the files in the directory. Otherwise, ListIt reads and prints the file. FileOutputStream is a subclass of OutputStream, so it inherits all the standard OutputStream functionality for writing to a file. Just like FileInputStream though, FileOutputStream provides only a low-level interface to writing data. You'll typically wrap another stream like a DataOutputStream or a PrintStream around the FileOutputStream to provide higher-level functionality. You can create a FileOutputStream from a String pathname or a File object. Unlike FileInputStream however, the FileOutputStream constructors don't throw a FileNotFoundException. If the specified file doesn't exist, the FileOutputStream creates the file. The FileOutputStream constructors can throw an IOException if some other I/O error occurs, so you still need to handle this exception. If the specified file does exist, the FileOutputStream opens it for writing. When you actually call a write() method, the new data overwrites the current contents of the file. If you need to append data to an existing file, you should use a different constructor that accepts an append flag, as shown here: FileInputStream foois = new FileInputStream( fooFile ); FileInputStream passwdis = new FileInputStream( "/etc/passwd" ); Antoher alternative for appending files is to use a RandomAccessFile, as I'll discuss shortly. To write characters (instead of bytes) to a file, you can wrap an OutputStreamWriter around a FileOutputStream. If you want to use the default character encoding scheme, you can use the FileWriter class instead, which is provided as a convenience. FileWriter works just like FileOutputStream, except that it writes characters instead of bytes and wraps a Writer instead of an OutputStream. The following example reads a line of data from standard input and writes it to the file /tmp/foo.txt: String s = new BufferedReader( new InputStreamReader( System.in ) ).readLine(); File out = new File( "/tmp/foo.txt" ); FileWriter fw = new FileWriter ( out ); PrintWriter pw = new PrintWriter( fw, true ) pw.println( s ); Notice how we have wrapped a PrintWriter around the FileWriter to facilitate writing the data. To be a good http://localhost/java/javaref/exp/ch08_02.htm (5 of 7) [20/12/2001 11:02:41]
[Chapter 8] 8.2 Files
filesystem citizen, you need to call the close() method when you are done with the FileWriter.
java.io.RandomAccessFile The java.io.RandomAccessFile class provides the ability to read and write data from or to any specified location in a file. RandomAccessFile implements both the DataInput and DataOutput interfaces, so you can use it to read and write strings and Java primitive types. In other words, RandomAccessFile defines the same methods for reading and writing data as DataInputStream and DataOutputStream. However, because the class provides random, rather than sequential, access to file data, it's not a subclass of either InputStream or OutputStream. You can create a RandomAccessFile from a String pathname or a File object. The constructor also takes a second String argument that specifies the mode of the file. Use "r" for a read-only file or "rw" for a read-write file. Here's how to create a simple database to keep track of user information: try { RandomAccessFile users = new RandomAccessFile( "Users", "rw" ); ... } catch (IOException e) { } When you create a RandomAccessFile in read-only mode, Java tries to open the specified file. If the file doesn't exist, RandomAccessFile throws an IOException. If, however, you are creating a RandomAccessFile in read-write mode, the object creates the file if it doesn't exist. The constructor can still throw an IOException if some other I/O error occurs, so you still need to handle this exception. After you have created a RandomAccessFile, call any of the normal reading and writing methods, just as you would with a DataInputStream or DataOutputStream. If you try to write to a read-only file, the write method throws an IOException. What makes a RandomAccessFile special is the seek() method. This method takes a long value and uses it to set the location for reading and writing in the file. You can use the getFilePointer() method to get the current location. If you need to append data on the end of the file, use length() to determine that location. You can write or seek beyond the end of a file, but you can't read beyond the end of a file. The read methods throws a EOFException if you try to do this. Here's an example of writing some data to our user database: users.seek( userNum * RECORDSIZE ); users.writeUTF( userName ); users.writeInt( userID ); One caveat to notice with this example is that we need to be sure that the String length for userName, along with any data that comes after it, fits within the boundaries of the record size.
Applets and Files For security reasons, applets are not permitted to read and write to arbitrary places in the filesystem. The ability of an applet to read and write files, as with any kind of system resource, is under the control of a SecurityManager object. A SecurityManager is installed by the application that is running the applet, such as an applet viewer or Java-enabled Web browser. All filesystem access must first pass the scrutiny of the SecurityManager. With that in mind, applet-viewer applications are free to implement their own schemes for what, if any, access an applet may have.
http://localhost/java/javaref/exp/ch08_02.htm (6 of 7) [20/12/2001 11:02:41]
[Chapter 8] 8.2 Files
For example, Sun's HotJava Web browser allows applets to have access to specific files designated by the user in an access-control list. Netscape Navigator, on the other hand, currently doesn't allow applets any access to the filesystem. It isn't unusual to want an applet to maintain some kind of state information on the system where it's running. But for a Java applet that is restricted from access to the local filesystem, the only option is to store data over the network on its server. Although, at the moment, the Web is a relatively static, read-only environment, applets have at their disposal powerful, general means for communicating data over networks, as you'll see in Chapter 9, Network Programming. The only limitation is that, by convention, an applet's network communication is restricted to the server that launched it. This limits the options for where the data will reside. The only means of writing data to a server in Java is through a network socket. In Chapter 9, Network Programming we'll look at building networked applications with sockets in detail. With the tools of that chapter it's possible to build powerful client/server applications.
Streams
http://localhost/java/javaref/exp/ch08_02.htm (7 of 7) [20/12/2001 11:02:41]
Serialization
[Chapter 8] 8.3 Serialization
Chapter 8 Input/Output Facilities
8.3 Serialization Using streams and files, you can write an application that saves and loads its data to a disk drive. Java 1.1 provides an even more powerful mechanism called object serialization that does a lot of the work for you. In its simplest form, object serialization is an automatic way to save and load an object. However, object serialization has depths that we cannot plumb within the scope of this book, including complete control over the serialization process and interesting conundrums like class versioning. Basically, any class that implements the Serializable interface can be saved and restored from a stream. Special stream subclasses, ObjectInputStream and ObjectOutputStream, are used to serialize primitive types and objects. Subclasses of Serializable classes are also serializable. The default serialization mechanism saves the value of an object's nonstatic and nonvolatile member variables. One of the tricky things about serialization is that when an object is serialized, any object references it contains should also be serialized. We'll see this in an upcoming example. The implication is that any object we serialize must only contain references to Serializable objects. There are ways around this problem, like marking nonserializable members as volatile or overriding the default serialization mechanisms. In the following example, we create a Hashtable and write it to a disk file called h.ser. import java.io.*; import java.util.*; public class Save { public static void main(String[] args) { Hashtable h = new Hashtable(); h.put("string", "Gabriel Garcia Marquez"); h.put("int", new Integer(26)); h.put("double", new Double(Math.PI)); try { FileOutputStream fileOut = new FileOutputStream("h.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(h);
http://localhost/java/javaref/exp/ch08_03.htm (1 of 2) [20/12/2001 11:02:42]
[Chapter 8] 8.3 Serialization
} catch (Exception e) { System.out.println(e); } } } First we construct a Hashtable with a few elements in it. Then, in the three lines of code inside the try block, we write the Hashtable to a file called h.ser, using the writeObject() method of ObjectOutputStream. The ObjectOutputStream class is a lot like the DataOutputStream class, except that it includes the powerful writeObject() method. The Hashtable object is serializable because it implements the Serializable interface. The Hashtable we created has internal references to the items it contains. Thus, these components are automatically serialized along with the Hashtable. We'll see this in the next example when we deserialize the Hashtable. import java.io.*; import java.util.*; public class Load { public static void main(String[] args) { try { FileInputStream fileIn = new FileInputStream("h.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Hashtable h = (Hashtable)in.readObject(); System.out.println(h.toString()); } catch (Exception e) { System.out.println(e); } } } In this example, we read the Hashtable from the h.ser file, using the readObject() method of ObjectInputStream. The ObjectInputStream class is a lot like DataInputStream, except it includes the readObject() method. The return type of readObject() is Object, so we need to cast it to a Hashtable. Finally, we print out the contents of the Hashtable using its toString() method.
Files
http://localhost/java/javaref/exp/ch08_03.htm (2 of 2) [20/12/2001 11:02:42]
Data compression
[Chapter 8] 8.4 Data compression
Chapter 8 Input/Output Facilities
8.4 Data compression Java 1.1 includes a new package, java.util.zip, that contains classes you can use for data compression. In this section we'll talk about how to use the classes. We'll also present two useful example programs that build on what you have just learned about streams and files. The classes in the java.util.zip package support two widespread compression formats: GZIP and ZIP. Both of these are based on the ZLIB compression algorithm, which is discussed in RFC 1950, RFC 1951, and RFC 1952. These documents are available at ftp://ds.internic.net/rfc/. I don't recommend reading these documents unless you want to implement your own compression algorithm or otherwise extend the functionality of the java.util.zip package.
Compressing data The java.util.zip class provides two FilterOutputStream subclasses to write compressed data to a stream. To write compressed data in the GZIP format, simply wrap a GZIPOutputStream around an underlying stream and write to it. The following is a complete example that shows how to compress a file using the GZIP format. import java.io.*; import java.util.zip.*; public class GZip { public static int sChunk = 8192; public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GZip source"); return; } // Create output stream. String zipname = args[0] + ".gz"; GZIPOutputStream zipout; try { FileOutputStream out = new FileOutputStream(zipname); zipout = new GZIPOutputStream(out); } http://localhost/java/javaref/exp/ch08_04.htm (1 of 5) [20/12/2001 11:02:42]
[Chapter 8] 8.4 Data compression
catch (IOException e) { System.out.println("Couldn't create " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; // Compress the file. try { FileInputStream in = new FileInputStream(args[0]); int length; while ((length = in.read(buffer, 0, sChunk)) != -1) zipout.write(buffer, 0, length); in.close(); } catch (IOException e) { System.out.println("Couldn't compress " + args[0] + "."); } try { zipout.close(); } catch (IOException e) {} } } First we check to make sure we have a command-line argument representing a file name. Then we construct a GZIPOutputStream wrapped around a FileOutputStream representing the given file name with the .gz suffix appended. With this in place, we open the source file. We read chunks of data from it and write them into the GZIPOutputStream. Finally, we clean up by closing our open streams. Writing data to a ZIP file is a little more involved, but still quite manageable. While a GZIP file contains only one compressed file, a ZIP file is actually an archive of files, some (or all) of which may be compressed. Each item in the ZIP file is represented by a ZipEntry object. When writing to a ZipOutputStream, you'll need to call putNextEntry() before writing the data for each item. The following example shows how to create a ZipOutputStream. You'll notice it's just like creating a GZIPOutputStream. ZipOutputStream zipout; try { FileOutputStream out = new FileOutputStream("archive.zip"); zipout = new ZipOutputStream(out); } catch (IOException e) {} Let's say we have two files we want to write into this archive. Before we begin writing we need to call putNextEntry(). We'll create a simple entry with just a name. There are other fields in ZipEntry that you can set, but most of the time you won't need to bother with them. try {
http://localhost/java/javaref/exp/ch08_04.htm (2 of 5) [20/12/2001 11:02:42]
[Chapter 8] 8.4 Data compression
ZipEntry entry = new ZipEntry("First"); zipout.putNextEntry(entry); } catch (IOException e) {} At this point you can write the contents of the first file into the archive. When you're ready to write the second file into the archive, you simply call putNextEntry() again: try { ZipEntry entry = new ZipEntry("Second"); zipout.putNextEntry(entry); } catch (IOException e) {}
Decompressing data To decompress data, you can use one of the two FilterInputStream subclasses provided in java.util.zip. To decompress data in the GZIP format, simply wrap a GZIPInputStream around an underlying stream and read from it. The following is a complete example that shows how to decompress a GZIP file. import java.io.*; import java.util.zip.*; public class GUnzip { public static int sChunk = 8192; public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } // Create input stream. String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); }
http://localhost/java/javaref/exp/ch08_04.htm (3 of 5) [20/12/2001 11:02:42]
[Chapter 8] 8.4 Data compression
catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; // Decompress the file. try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) {} } } First we check to make sure we have a command-line argument representing a file name. If the argument ends with .gz, we figure out what the file name for the uncompressed file should be. Otherwise we just use the given argument and assume the compressed file has the .gz suffix. Then we construct a GZIPInputStream wrapped around a FileInputStream representing the compressed file. With this in place, we open the target file. We read chunks of data from the GZIPInputStream and write them into the target file. Finally, we clean up by closing our open streams. Again, the ZIP archive presents a little more complexity than the GZIP file. When reading from a ZipInputStream, you should call getNextEntry() before reading each item. When getNextEntry() returns null, there are no more items to read. The following example shows how to create a ZipInputStream. You'll notice it's just like creating a GZIPInputStream. ZipInputStream zipin; try { FileInputStream in = new FileInputStream("archive.zip"); zipin = new ZipInputStream(in); } catch (IOException e) {} Suppose we want to read two files from this archive. Before we begin reading we need to call getNextEntry(). At the least, the entry will give us a name of the item we are reading from the archive. try { ZipEntry first = zipin.getNextEntry();
http://localhost/java/javaref/exp/ch08_04.htm (4 of 5) [20/12/2001 11:02:42]
[Chapter 8] 8.4 Data compression
} catch (IOException e) {} At this point you can read the contents of the first item in the archive. When you come to the end of the item, the read() method will return -1. Now you can call getNextEntry() again to read the second item from the archive. try { ZipEntry second = zipin.getNextEntry(); } catch (IOException e) {} If you call getNextEntry() and it returns null, then there are no more items and you have reached the end of the archive.
Serialization
http://localhost/java/javaref/exp/ch08_04.htm (5 of 5) [20/12/2001 11:02:42]
Network Programming
[Chapter 9] 9.2 Datagram Sockets
Chapter 9 Network Programming
9.2 Datagram Sockets TinyHttpd used a Socket to create a connection to the client using the TCP protocol. In that example, TCP itself took care of data integrity; we didn't have to worry about data arriving out of order or incorrect. Now we'll take a walk on the wild side. We'll build an applet that uses a java.net.DatagramSocket, which uses the UDP protocol. A datagram is sort of like a "data telegram": it's a discrete chunk of data transmitted in one packet. Unlike the previous example, where we could get a convenient OutputStream from our Socket and write the data as if writing to a file, with a DatagramSocket we have to work one datagram at a time. (Of course, the TCP protocol was taking our OutputStream and slicing the data into packets, but we didn't have to worry about those details). UDP doesn't guarantee that the data will get through. If the data do get through, it may not arrive in the right order; it's even possible for duplicate datagrams to arrive. Using UDP is something like cutting the pages out of the encyclopedia, putting them into separate envelopes, and mailing them to your friend. If your friend wants to read the encyclopedia, it's his or her job to put the pages in order. If some pages got lost in the mail, your friend has to send you a letter asking for replacements. Obviously, you wouldn't use UDP to send a huge amount of data. But it's significantly more efficient than TCP, particularly if you don't care about the order in which messages arrive, or whether the data arrive at all. For example, in a database lookup, the client can send a query; the server's response itself constitutes an acknowledgment. If the response doesn't arrive within a certain time, the client can send another query. It shouldn't be hard for the client to match responses to its original queries. Some important applications that use UDP are the Domain Name System (DNS) and Sun's Network Filesystem (NFS).
The HeartBeat Applet In this section we'll build a simple applet, HeartBeat, that sends a datagram to its server each time it's started and stopped. (See Chapter 10, Understand the Abstract Windowing Toolkit for a complete discussion of the Applet class.) We'll also build a simple standalone server application, Pulse, that receives that datagrams and prints them. By tracking the output, you could have a crude measure of who is currently looking at your Web page at any given time. This is an ideal application for UDP: we don't want the overhead of a TCP socket, and if datagrams get lost, it's no big deal. First, the HeartBeat applet: import java.net.*; http://localhost/java/javaref/exp/ch09_02.htm (1 of 5) [20/12/2001 11:02:43]
[Chapter 9] 9.2 Datagram Sockets
import java.io.*; public class HeartBeat extends java.applet.Applet { String myHost; int myPort; public void init() { myHost = getCodeBase().getHost(); myPort = Integer.parseInt( getParameter("myPort") ); } private void sendMessage( String message ) { try { byte [] data = new byte [ message.length() ]; message.getBytes(0, data.length, data, 0); InetAddress addr = InetAddress.getByName( myHost ); DatagramPacket pack = new DatagramPacket(data, data.length, addr, myPort); DatagramSocket ds = new DatagramSocket(); ds.send( pack ); ds.close(); } catch ( IOException e ) System.out.println( e ); } public void start() { sendMessage("Arrived"); } public void stop() { sendMessage("Departed"); } } Compile the applet and include it in an HTML document with an tag: <param name="myPort" value="1234"> The myPort parameter should specify the port number on which our server application listens for data. Next, the server-side application, Pulse: import java.net.*;
http://localhost/java/javaref/exp/ch09_02.htm (2 of 5) [20/12/2001 11:02:43]
[Chapter 9] 9.2 Datagram Sockets
import java.io.*; public class Pulse { public static void main( String [] argv ) throws IOException { DatagramSocket s = new DatagramSocket(Integer.parseInt(argv[0])); while ( true ) { DatagramPacket packet = new DatagramPacket(new byte [1024], 1024); s.receive( packet ); String message = new String(packet.getData(), 0, 0, packet.getLength()); System.out.println( "Heartbeat from: " + packet.getAddress().getHostName() + " - " + message ); } } } Compile Pulse and run it on your Web server, specifying a port number as an argument: % java Pulse 1234 The port number should be the same as the one you used in the myPort parameter of the tag for HeartBeat. Now, pull up the Web page in your browser. You won't see anything there (a better application might do something visual as well), but you should get a blip from the Pulse application. Leave the page and return to it a few times. Each time the applet is started or stopped, it sends a message: Heartbeat Heartbeat Heartbeat Heartbeat ...
from: from: from: from:
foo.bar.com foo.bar.com foo.bar.com foo.bar.com
-
Arrived Departed Arrived Departed
Cool, eh? Just remember the datagrams are not guaranteed to arrive (although it's unlikely you'll see them fail), and it's possible that you could miss an arrival or a departure. Now let's look at the code. HeartBeat HeartBeat overrides the init(), start(), and stop() methods of the Applet class, and implements one private method of its own, sendMessage(), that sends a datagram. HeartBeat begins its life in init(), where it determines the destination for its messages. It uses the Applet getCodeBase() and getHost() methods to find the name of its originating host and fetches the correct port number from the myPort parameter of the HTML tag. After init() has finished, the start() and stop() methods are called whenever the applet is started or stopped. These methods http://localhost/java/javaref/exp/ch09_02.htm (3 of 5) [20/12/2001 11:02:43]
[Chapter 9] 9.2 Datagram Sockets
merely call sendMessage() with the appropriate message. sendMessage() is responsible for sending a String message to the server as a datagram. It takes the text as an argument, constructs a datagram packet containing the message, and then sends the datagram. All of the datagram information, including the destination and port number, are packed into a java.net.DatagramPacket object. The DatagramPacket is like an addressed envelope, stuffed with our bytes. After the DatagramPacket is created, sendMessage() simply has to open a DatagramSocket and send it. The first four lines of sendMessage() build the DatagramPacket: try { byte [] data = new byte [ message.length() ]; message.getBytes(0, data.length, data, 0); InetAddress addr = InetAddress.getByName( myHost ); DatagramPacket pack = new DatagramPacket(data, data.length, addr, myPort ); First, the contents of message are placed into an array of bytes called data. Next a java.net.InetAddress object is created from the name myHost. An InetAddress simply holds the network address information for a host in a special format. We get an InetAddress object for our host by using the static getByName() method of the InetAddress class. (We can't construct an InetAddress object directly.) Finally, we call the DatagramPacket constructor with four arguments: the byte array containing our data, the length of the data, the destination address object, and the port number. The remaining lines construct a default client DatagramSocket and call its send() method to transmit the DatagramPacket; after sending the datagram, we close the socket: DatagramSocket ds = new DatagramSocket(); ds.send( pack ); ds.close(); Two operations throw a type of IOException: the InetAddress.getByName() lookup and the DatagramSocket send(). InetAddress.getByName() can throw an UnknownHostException, which is a type of IOException that indicates that the host name can't be resolved. If send() throws an IOException, it implies a serious client side problem in talking to the network. We need to catch these exceptions; our catch block simply prints a message telling us that something went wrong. If we get one of these exceptions, we can assume the datagram never arrived. However, we can't assume the converse. Even if we don't get an exception, we still don't know that the host is actually accessible or that the data actually arrived; with a DatagramSocket, we never find out. Pulse The Pulse server corresponds to the HeartBeat applet. First, it creates a DatagramSocket to listen on our prearranged port. This time, we specify a port number in the constructor; we get the port number from the command line as a string (argv[0]) and convert it to an integer with
http://localhost/java/javaref/exp/ch09_02.htm (4 of 5) [20/12/2001 11:02:43]
[Chapter 9] 9.2 Datagram Sockets
Integer.parseInt(). Note the difference between this call to the constructor and the call in HeartBeat. In the server, we need to listen for incoming datagrams on a prearranged port, so we need to specify the port when creating the DatagramSocket. In the client, we need only to send datagrams, so we don't have to specify the port in advance; we build the port number into the DatagramPacket itself. Second, Pulse creates an empty DatagramPacket of a fixed size to receive an incoming datagram. This alternative constructor for DatagramPacket takes a byte array and a length as arguments. As much data as possible is stored in the byte array when it's received. (A practical limit on the size of a UDP datagram is 8K.) Finally, Pulse calls the DatagramSocket's receive() method to wait for a packet to arrive. When a packet arrives, its contents are printed. As you can see, working with DatagramSocket is slightly more tedious than working with Sockets. With datagrams, it's harder to spackle over the messiness of the socket interface. However, the Java API rather slavishly follows the UNIX interface, and that doesn't help. I don't see any reason why we have to prepare a datagram to hand to receive() (at least for the current functionality); receive() ought to create an appropriate object on its own and hand it to us, saving us the effort of building the datagram in advance and unpacking the data from it afterwards. It's easy to imagine other conveniences; perhaps we'll have them in a future release.
Sockets
http://localhost/java/javaref/exp/ch09_02.htm (5 of 5) [20/12/2001 11:02:43]
Working with URLs
[Chapter 9] 9.3 Working with URLs
Chapter 9 Network Programming
9.3 Working with URLs A URL points to an object on the Internet. It's a collection of information that identifies an item, tells you where to find it, and specifies a method for communicating with it or retrieving it from its source. A URL refers to any kind of information source. It might point to static data, such as a file on a local filesystem, a Web server, or an FTP archive; or it can point to a more dynamic object such as a news article on a news spool or a record in a WAIS database. URLs can even refer to less tangible resources such as Telnet sessions and mailing addresses. A URL is usually presented as a string of text, like an address.[3] Since there are many different ways to locate an item on the Net, and different mediums and transports require different kinds of information, there are different formats for different kinds of URLs. The most common form specifies three things: a network host or server, the name of the item and its location on that host, and a protocol by which the host should communicate: [3] The term URL was coined by the Uniform Resource Identifier (URI) working group of the IETF to distinguish URLs from the more general notion of Uniform Resource Names or URNs. URLs are really just static addresses, whereas URNs would be more persistent and abstract identifiers used to resolve the location of an object anywhere on the Net. URLs are defined in RFC 1738 and RFC 1808. protocol://hostname/location/item protocol is an identifier such as "http," "ftp," or "gopher"; hostname is an Internet hostname; and the location and item components form a path that identifies the object on that host. Variants of this form allow extra information to be packed into the URL, specifying things like port numbers for the communications protocol and fragment identifiers that reference parts inside the object. We sometimes speak of a URL that is relative to a base URL. In that case we are using the base URL as a starting point and supplying additional information. For example, the base URL might point to a directory on a Web server; a relative URL might name a particular file in that directory.
The URL class A URL is represented by an instance of the java.net.URL class. A URL object manages all information in a URL string and provides methods for retrieving the object it identifies. We can construct a URL object from a URL specification string or from its component parts: http://localhost/java/javaref/exp/ch09_03.htm (1 of 4) [20/12/2001 11:02:43]
[Chapter 9] 9.3 Working with URLs
try { URL aDoc = new URL( "http://foo.bar.com/documents/homepage.html" ); URL sameDoc = new URL("http","foo.bar.com","documents/homepage.html"); } catch ( MalformedURLException e ) { } The two URL objects above point to the same network resource, the homepage.html document on the server foo.bar.com. Whether or not the resource actually exists and is available isn't known until we try to access it. At this point, the URL object just contains data about the object's location and how to access it. No connection to the server has been made. We can examine the URL's components with the getProtocol(), getHost(), and getFile() methods. We can also compare it to another URL with the sameFile() method. sameFile() determines if two URLs point to the same resource. It can be fooled, but sameFile does more than compare the URLs for equality; it takes into account the possibility that one server may have several names, and other factors. When a URL is created, its specification is parsed to identify the protocol component. If the protocol doesn't make sense, or if Java can't find a protocol handler for it, the URL constructor throws a MalformedURLException. A protocol handler is a Java class that implements the communications protocol for accessing the URL resource. For example, given an "http" URL, Java prepares to use the HTTP protocol handler to retrieve documents from the specified server.
Stream Data The most general way to get data back from URL is to ask for an InputStream from the URL by calling openStream(). If you're writing an applet that will be running under Netscape, this is about your only choice. In fact, it's a good choice if you want to receive continuous updates from a dynamic information source. The drawback is that you have to parse the contents of an object yourself. Not all types of URLs support the openStream() method; you'll get an UnknownServiceException if yours doesn't. The following code reads a single line from an HTML file: try { URL url = new URL("http://server/index.html"); DataInputStream dis = new DataInputStream( url.openStream() ); String line = dis.readLine(); We ask for an InputStream with openStream(), and wrap it in a DataInputStream to read a line of text. Here, because we are specifying the "http" protocol in the URL, we still require the services of an HTTP protocol handler. As we'll discuss more in a bit, that brings up some questions about what handlers we have available to us and where. This example partially works around those issues because no content handler is involved; we read the data and interpret it as a content handler would. However, there are even more limitations on what applets can do right now. For the time being, if you construct URLs relative to the applet's codeBase(), you should be able to use them in applets as in the above example. This should guarantee that the needed protocol is available and accessible to the applet. Again, we'll discuss the more general issues a bit later.
http://localhost/java/javaref/exp/ch09_03.htm (2 of 4) [20/12/2001 11:02:43]
[Chapter 9] 9.3 Working with URLs
Getting the Content as an Object openStream() operates at a lower level than the more general content-handling mechanism implemented by the URL class. We showed it first because, until some things are settled, you'll be limited as to when you can use URLs in their more powerful role. When a proper content handler is available to Java (currently, only if you supply one with your standalone application), you'll be able to retrieve the object the URL addresses as a complete object, by calling the URL's getContent() method. getContent() initiates a connection to the host, fetches the data for you, determines the data's MIME type, and invokes a content handler to turn the data into a Java object. For example: given the URL http://foo.bar.com/index.html, a call to getContent() uses the HTTP protocol handler to receive the data and the HTML content handler to turn the data into some kind of object. A URL that points to a plain-text file would use a text-content handler that might return a String object. A GIF file might be turned into an Image object for display, using a GIF content handler. If we accessed the GIF file using an "ftp" URL, Java would use the same content handler, but would use the FTP protocol handler to receive the data. getContent() returns the output of the content handler. Now we're faced with a problem: exactly what did we get? Since the content handler can return almost anything, the return type of getContent() is Object. Before doing anything meaningful with this Object, we must cast it into some other data type that we can work with. For example, if we expect a String, we'll cast the result of getContent() to a String: String content; try content = (String)myURL.getContent(); catch ( Exception e ) { } Of course, we are presuming we will in fact get a String object back from this URL. If we're wrong, we'll get a ClassCastException. Since it's common for servers to be confused (or even lie) about the MIME types of the objects they serve, it's wise to catch that exception (it's a subclass of RuntimeException, so catching it is optional) or to check the type of the returned object with the instanceof operator: if ( content instanceof String ) { String s = (String)content; ... Various kinds of errors can occur when trying to retrieve the data. For example, getContent() can throw an IOException if there is a communications error; IOException is not a type of RuntimeException, so we must catch it explicitly, or declare the method that calls getContent() can throw it. Other kinds of errors can happen at the application level: some knowledge of how the handlers deal with errors is necessary. For example, consider a URL that refers to a nonexistent file on an HTTP server. When requested, the server probably returns a valid HTML document that consists of the familiar "404 Not Found" message. An appropriate HTML content handler is invoked to interpret this and return it as it would any other HTML http://localhost/java/javaref/exp/ch09_03.htm (3 of 4) [20/12/2001 11:02:43]
[Chapter 9] 9.3 Working with URLs
object. At this point, there are several alternatives, depending entirely on the content handler's implementation. It might return a String containing the error message; it could also conceivably return some other kind of object or throw a specialized subclass of IOException. To find out that an error occurred, the application may have to look directly at the object returned from getContent(). After all, what is an error to the application may not be an error as far as the protocol or content handlers are concerned. "404 Not Found" isn't an error at this level; it's a perfectly valid document. Another type of error occurs if a content handler that understands the data's MIME type isn't available. In this case, getContent() invokes a minimal content handler used for data with an unknown type and returns the data as a raw InputStream. A sophisticated application might specialize this behavior to try to decide what to do with the data on its own. The openStream() and getContent() methods both implicitly create a connection to the remote URL object. For some applications, it may be necessary to use the openConnection() method of the URL to interact directly with the protocol handler. openConnection() returns a URLConnection object, which represents a single, active connection to the URL resource. We'll examine URLConnections further when we start writing protocol handlers.
Datagram Sockets
http://localhost/java/javaref/exp/ch09_03.htm (4 of 4) [20/12/2001 11:02:43]
Web Browsers and Handlers
[Chapter 9] 9.4 Web Browsers and Handlers
Chapter 9 Network Programming
9.4 Web Browsers and Handlers The content- and protocol-handler mechanisms I've introduced can be used by any application that accesses data via URLs. This mechanism is extremely flexible; to handle a URL, you need only the appropriate protocol and content handlers. To extend a Java-built Web browser so that it can handle new and specialized kinds of URLs, you need only supply additional content and protocol handlers. Furthermore, Java's ability to load new classes over the Net means that the handlers don't even need to be a part of the browser. Content and protocol handlers could be downloaded over the Net, from the same site that supplies the data, and used by the browser. If you wanted to supply some completely new data type, using a completely new protocol, you could make your data file plus a content handler and a protocol handler available on your Web server; anyone using a Web browser built in Java would automatically get the appropriate handlers whenever they access your data. In short, Java lets you build automatically extendible Web browsers; instead of being a gigantic do-everything application, the browser becomes a lightweight scaffold that dynamically incorporates extensions as needed. Figure 9.3 shows the conceptual operation of a content handler; Figure 9.4 does the same for a protocol handler. Figure 9.3: A content handler at work
Figure 9.4: A protocol handler at work
http://localhost/java/javaref/exp/ch09_04.htm (1 of 3) [20/12/2001 11:02:44]
[Chapter 9] 9.4 Web Browsers and Handlers
Sun's HotJava was the first browser to demonstrate these features. When HotJava encounters a type of content or a protocol it doesn't understand, it searches the remote server for an appropriate handler class. HotJava also interprets HTML data as a type of content; that is, HTML isn't a privileged data type built into the browser. HTML documents use the same content- and protocol-handler mechanisms as other data types. Unfortunately, a few nasty flies are stuck in this ointment. Content and protocol handlers are part of the Java API: they're an intrinsic part of the mechanism for working with URLs. However, specific content and protocol handlers aren't part of the API; the ContentHandler class and the two classes that make up protocol handlers, URLStreamHandler and URLConnection, are all abstract classes. They define what an implementation must provide, but they don't actually provide an implementation. This is not as paradoxical as it sounds. After all, the API defines the Applet class, but doesn't include any specific applets. Likewise, the standard Java classes don't include content handlers for HTML, GIF, MPEG, or other common data types. Even this isn't a real problem, although a library of standard content handlers would be useful. (JDK provides some content and protocol handlers in the sun.net.www.content and sun.net.www.protocol packages, but these are undocumented and subject to change.) There are two real issues here: ● There isn't any standard that tells you what kind of object the content handler should return. I danced around the issue just above, but it's a real problem. It's common sense that GIF data should be turned into an Image object, but at the moment, that's an application-level decision. If you're writing your own application and your own content handlers, that isn't an issue: you can make any decision you want. But if you're writing content handlers that interface to arbitrary Web browsers, you need a standard that defines what the browser expects. You can use the sun.net classes to make a guess, but a real standard hasn't been worked out yet. ● There isn't any standard that tells you where to put content and protocol handlers so that an application (like a Web browser) can find them. Again, you can make application-level decisions about where to place your own handlers, but that doesn't solve the real problem: we want our content and protocol handlers to be usable by any browser. It's possible to make an educated guess about what the standard will be, but it's still a guess. The next release of Sun's HotJava Web browser should certainly take full advantage of handlers,[4] but http://localhost/java/javaref/exp/ch09_04.htm (2 of 3) [20/12/2001 11:02:44]
[Chapter 9] 9.4 Web Browsers and Handlers
current versions of Netscape Navigator do not. When the next release of HotJava appears, it may resolve these questions, at least on a de facto basis. (It would certainly be in Sun's interest to publish some kind of standard as soon as possible.) Although we can't tell you what standards will eventually evolve, we can discuss how to write handlers for standalone applications. When the standards issues are resolved, revising these handlers to work with HotJava and other Web browsers should be simple. [4] Downloadable handlers will be part of HotJava 1.0, though they are not supported by the "pre-beta 1" release. The current release does support local content and protocol handlers. HotJava 1.0 also promises additional classes to support network applications. The most common Java-capable platform, Netscape Navigator, doesn't use the content- and protocol-handler mechanisms to render Net resources. It's a classic monolithic application: knowledge about certain kinds of objects, like HTML and GIF files, is built-in. It can be extended via a plug-in mechanism, but plug-ins aren't portable (they're written in C) and can't be downloaded dynamically over the Net. Applets running in Netscape can use a limited version of the URL mechanism, but the browser imposes many restrictions. As I said earlier, you can construct URLs relative to the applet's code base, and use the openStream() method to get a raw input stream from which to read data, but that's it. For the time being, you can't use your own content or protocol handlers to work with applets loaded over the Net. Allowing this would be a simple extension, even without content- and protocol-handler support integrated into Netscape itself. We can only hope they add this support soon.
Working with URLs
http://localhost/java/javaref/exp/ch09_04.htm (3 of 3) [20/12/2001 11:02:44]
Writing a Content Handler
[Chapter 9] 9.5 Writing a Content Handler
Chapter 9 Network Programming
9.5 Writing a Content Handler getContent() invokes a content handler whenever it's called to retrieve an object at some URL. The content handler must read the flat stream of data produced by the URL's protocol handler (the data read from the remote source), and construct a well-defined Java object from it. By "flat," I mean that the data stream the content handler receives has no artifacts left over from retrieving the data and processing the protocol. It's the protocol handler's job to fetch and decode the data before passing it along. The protocol handler's output is your data, pure and simple. The roles of content and protocol handlers do not overlap. The content handler doesn't care how the data arrives, or what form it takes. It's concerned only with what kind of object it's supposed to create. For example, if a particular protocol involves sending an object over the network in a compressed format, the protocol handler should do whatever is necessary to unpack it before passing the data on to the content handler. The same content handler can then be used again with a completely different protocol handler to construct the same type of object received via a different transport mechanism. Let's look at an example. The following lines construct a URL that points to a GIF file on an FTP archive and attempt to retrieve its contents: try { URL url = new URL ("ftp://ftp.wustl.edu/graphics/gif/a/apple.gif"); Image img = (Image)url.getContent(); ... When we construct the URL object, Java looks at the first part of the URL string (i.e., everything prior to the colon) to determine the protocol and locate a protocol handler. In this case, it locates the FTP protocol handler, which is used to open a connection to the host and transfer data for the specified file. After making the connection, the URL object asks the protocol handler to identify the resource's MIME type.[5] It does this through a variety of means, but in this case it probably just looks at the filename extension (.gif ) and determines that the MIME type of the data is image/gif. The protocol handler then looks for the content handler responsible for the image/gif type and uses it to construct the right kind of object from the data. The content handler returns an Image object, which getContent() returns to us as an Object; we cast this Object back to the Image type so we can work with it. [5] MIME stands for Multipurpose Internet Mail Extensions. It's a standard design to facilitate multimedia email, but it has become more widely used as a way to specify the treatment of
http://localhost/java/javaref/exp/ch09_05.htm (1 of 8) [20/12/2001 11:02:45]
[Chapter 9] 9.5 Writing a Content Handler
data contained in a document. In an upcoming section, we'll build a simple content handler. To keep things as simple as possible, our example will produce text as output; the URL's getContent() method will return this as a String object.
Locating Content Handlers As I said earlier, there's no standard yet for where content handlers should be located. However, we're writing code now and need to know what package to place our class files in. In turn, this determines where to place the class files in the local filesystem. Because we are going to write our own standalone application to use our handler, we'll place our classes in a package in our local class path and tell Java where they reside. However, we will follow the naming scheme that's likely to become the standard. If other applications expect to find handlers in different locations (either locally or on servers), you'll simply have to repackage your class files according to their naming scheme and put them in the correct place. Package names translate to path names when Java is searching for a class. This holds for locating content-handler classes as well as other kinds of classes. For example, on a UNIX- or DOS-based system, a class in a package named net.www.content would live in a directory with net/www/content/ as part of its pathname. To allow Java to find handler classes for arbitrary new MIME types, content handlers are organized into packages corresponding to the basic MIME type categories. The handler classes themselves are then named after the specific MIME type. This allows Java to map MIME types directly to class names. According to the scheme we'll follow, a handler for the image/gif MIME type is called gif and placed in a package called net.www.content.image. The fully qualified name of the class would then be net.www.content.image.gif, and it would be located in the file net/www/content/image/gif.class, somewhere in the local class path or on a server. Likewise, a content handler for the video/mpeg MIME type would be called mpeg, and there would be an mpeg.class file located (again, on a UNIX-/DOS-like filesystem) in a net/www/content/video/ directory somewhere in a local class path or on a server. Many MIME type names include a dash (-), which is illegal in a class name. You should convert dashes and other illegal characters into underscores when building Java class and package names. Also note that there are no capital letters in the class names. This violates the coding convention used in most Java source files, in which class names start with capital letters. However, capitalization is not significant in MIME type names, so it's simpler to name the handler classes accordingly. Table 9.1 shows how some typical MIME types are converted to package and class names.[6] [6] The "pre-beta 1" release of HotJava has a temporary solution that is compatible with the convention described here. In the HotJava properties file, add the line: java.content.handler.pkgs=net.www.content. Table 9.1: Converting MIME Types to Class and Package Names MIME type Package name Class name Class location image/gif net.www.content.image gif image/jpeg net.www.content.image jpeg text/html net.www.content.text html
http://localhost/java/javaref/exp/ch09_05.htm (2 of 8) [20/12/2001 11:02:45]
net/www/content/image/ net/www/content/image/ net/www/content/text/
[Chapter 9] 9.5 Writing a Content Handler
The application/x-tar Handler In this section, we'll build a simple content handler that reads and interprets tar (tape archive) files. tar is an archival format widely used in the UNIX-world to hold collections of files, along with their basic type and attribute information.[7] A tar file is similar to a ZIP file, except that it's not compressed. Files in the archive are stored sequentially, in flat text or binary with no special encoding. In practice, tar files are usually compressed for storage using an application like UNIX compress or GNU gzip and then named with a filename extension like .tar.gz or .tgz. [7] There are several slightly different versions of the tar format. This content handler understands the most widely used variant. Most Web browsers, upon retrieving a tar file, prompt the user with a File Save dialog. The assumption is that if you are retrieving an archive, you probably want to save it for later unpacking and use. We would like to instead implement a tar content handler that allows an application to read the contents of the archive and give us a listing of the files that it contains. In itself, this would not be the most useful thing in the world, because we would be left with the dilemma of how to get at the archive's contents. However, a more complete implementation of our content handler, used in conjunction with an application like a Web browser, could generate output that lets us select and save individual files within the archive. The code that fetches the .tar file and lists its contents looks like this: try { URL listing = new URL("http://somewhere.an.edu/lynx/lynx2html.tar"); String s = (String)listing.getContents(); System.out.println( s ); ... We'll produce a listing similar to the UNIX tar application's output: Tape Archive Listing: 0 14773 470 172 3656 490 ...
Tue Tue Tue Thu Wed Thu
Sep Sep Sep Apr Mar Apr
28 28 28 01 03 01
18:12:47 18:01:55 18:13:24 15:05:43 15:40:20 14:55:04
CDT CDT CDT CST CST CST
1993 1993 1993 1993 1993 1993
lynx2html/ lynx2html/lynx2html.c lynx2html/Makefile lynx2html/lynxgate lynx2html/install.csh lynx2html/new_globals.c
Our content handler dissects the file to read the contents and generates the listing. The URL's getContent() method returns that information to our application as a String object. First we must decide what to call our content handler and where to put it. The MIME-type hierarchy classifies the tar format as an "application type extension." Its proper MIME type is then application/x-tar. Therefore, our handler belongs to the net.www.content.application package, and goes into the class file net/www/content/application/x_tar.class. Note that the name of our
http://localhost/java/javaref/exp/ch09_05.htm (3 of 8) [20/12/2001 11:02:45]
[Chapter 9] 9.5 Writing a Content Handler
class is x_tar, rather than x-tar; you'll remember the dash is illegal in a class name so, by convention, we convert it to an underscore. Here's the code for the content handler; compile it and place it in the net/www/content/application/ package, somewhere in your class path: package net.www.content.application; import java.net.*; import java.io.*; import java.util.Date; public class x_tar extends ContentHandler { static int RECORDLEN = 512, NAMEOFF = 0, NAMELEN = 100, SIZEOFF = 124, SIZELEN = 12, MTIMEOFF = 136, MTIMELEN = 12; public Object getContent(URLConnection uc) throws IOException { InputStream is = uc.getInputStream(); StringBuffer output = new StringBuffer( "Tape Archive Listing:\n\n" ); byte [] header = new byte[RECORDLEN]; int count = 0; while ( (is.read(header) == RECORDLEN) && (header[NAMEOFF] != 0) ) { String name = new String(header, 0, NAMEOFF, NAMELEN).trim(); String s = new String(header, 0, SIZEOFF, SIZELEN).trim(); int size = Integer.parseInt(s, 8); s = new String(header, 0, MTIMEOFF, MTIMELEN).trim(); long l = Integer.parseInt(s, 8); Date mtime = new Date( l*1000 ); output.append( size + " " + mtime + " " + name + "\n" ); count += is.skip( size ) + RECORDLEN; if ( count % RECORDLEN != 0 ) count += is.skip ( RECORDLEN - count % RECORDLEN); } if ( count == 0 ) output.append("Not a valid TAR file\n");
http://localhost/java/javaref/exp/ch09_05.htm (4 of 8) [20/12/2001 11:02:45]
[Chapter 9] 9.5 Writing a Content Handler
return( output.toString() ); } } The ContentHandler class Our x_tar handler is a subclass of the abstract class java.net.ContentHandler. Its job is to implement one method: getContent(), which takes as an argument a special "protocol connection" object and returns a constructed Java Object. The getContent() method of the URL class ultimately uses this getContent() method when we ask for the contents of the URL. The code looks formidable, but most of it's involved with processing the details of the tar format. If we remove these details, there isn't much left: public class x_tar extends ContentHandler { public Object getContent( URLConnection uc ) throws IOException { // get input stream InputStream is = uc.getInputStream(); // read stream and construct object // ... // return the constructed object return( output.toString() ); } } That's really all there is to a content handler; it's relatively simple. The URLConnection The java.net.URLConnection object that getContent() receives represents the protocol handler's connection to the remote resource. It provides a number of methods for examining information about the URL resource, such as header and type fields, and for determining the kinds of operations the protocol supports. However, its most important method is getInputStream(), which returns an InputStream from the protocol handler. Reading this InputStream gives you the raw data for the object the URL addresses. In our case, reading the InputStream feeds x_tar the bytes of the tar file it's to process. Constructing the object The majority of our getContent() method is devoted to interpreting the stream of bytes of the tar file and building our output object: the String that lists the contents of the tar file. Again, this means that this example involves the particulars of reading tar files, so you shouldn't fret too much about the details. After requesting an InputStream from the URLConnection, x_tar loops, gathering information about each file. Each archived item is preceded by a header that contains attribute and length fields. x_tar http://localhost/java/javaref/exp/ch09_05.htm (5 of 8) [20/12/2001 11:02:45]
[Chapter 9] 9.5 Writing a Content Handler
interprets each header and then skips over the remaining portion of the item. It accumulates the results (the file listings) in a StringBuffer. (See Chapter 7, Basic Utility Classes for a discussion of StringBuffer.) For each file, we add a line of text listing the name, modification time, and size. When the listing is complete, getContent() returns the StringBuffer as a String object. The main while loop continues as long as it's able to read another header record, and as long as the record's "name" field isn't full of ASCII null values. (The tar file format calls for the end of the archive to be padded with an empty header record, although most tar implementations don't seem to do this.) The while loop retrieves the name, size, and modification times as character strings from fields in the header. The most common tar format stores its numeric values in octal, as fixed-length ASCII strings. We extract the strings and use Integer.parseInt() to parse them. After reading and parsing the header, x_tar skips over the data portion of the file and updates the variable count, which keeps track of the offset into the archive. The two lines following the initial skip account for tar's "blocking" of the data records. In other words, if the data portion of a file doesn't fit precisely into an integral number of blocks of RECORDLEN bytes, tar adds padding to make it fit. Whew. Well, as I said, the details of parsing tar files are not really our main concern here. But x_tar does illustrate a few tricks of data manipulation in Java. It may surprise you that we didn't have to provide a constructor; our content handler relies on its default constructor. We don't need to provide a constructor because there isn't anything for it to do. Java doesn't pass the class any argument information when it creates an instance of it. You might suspect that the URLConnection object would be a natural thing to provide at that point. However, when you are calling the constructor of a class that is loaded at run-time, you can't pass it any arguments, as we discussed in Chapter 5, Objects in Java. Using our new handler When I began this discussion of content handlers, I showed a brief example of how our x_tar content handler would work for us. We need to make a few brief additions to that code in order to use our new handler and fetch URLs that point to .tar files. Since we're writing a standalone application, we're not only responsible for writing handlers that obey the package/class naming scheme we described earlier; we are also responsible for making our application use the naming scheme. In a standalone application, the mapping between MIME types and content-handler class names is done by a special java.net.ContentHandlerFactory object we must install. The ContentHandlerFactory accepts a String containing a MIME type and returns the appropriate content handler. It's responsible for implementing the naming convention and creating an instance of our handler. Note that you don't need a content-handler factory if you are writing handlers for use by remote applications; a browser like HotJava, that loads content handlers over the Net, has its own content-handler factory. To make absolutely clear what's happening, we'll provide a simple factory that knows only about our x_tar handler and install it at the beginning of our application: import java.net.*; import java.io.*;
http://localhost/java/javaref/exp/ch09_05.htm (6 of 8) [20/12/2001 11:02:45]
[Chapter 9] 9.5 Writing a Content Handler
class OurContentHandlerFactory implements ContentHandlerFactory { public ContentHandler createContentHandler(String mimetype) { if ( mimetype.equalsIgnoreCase( "application/x-tar" ) ) return new net.www.content.application.x_tar(); else return null; } } public class TarURLTest { public static void main (String [] args) throws Exception { URLConnection.setContentHandlerFactory(new OurContentHandlerFactory() ); URL url = new URL( args[0] ); String s = (String)url.getContent(); System.out.println( s ); } } The class OurContentHandlerFactory implements the ContentHandlerFactory interface. It recognizes the MIME-type application/x-tar and returns a new instance of our x_tar handler. TarURLTest uses the static method URLConnection.setContentHandlerFactory() to install our new ContentHandlerFactory. After it's installed, our factory is called every time we retrieve the contents of a URL object. If it returns a null value, Java looks for handlers in a default location.[8] [8] If we don't install a ContentHandlerFactory (or later, as we'll see a URLStreamHandlerFactory for protocol handlers), Java defaults to searching for a vendor-specific package name. If you have Sun's Java Development Kit, it searches for content handlers in the sun.net.www.content package hierarchy and protocol handler classes in the sun.net.www.protocol package hierarchy. After installing the factory, TarURLTest reads a URL from the command line, opens that URL, and lists its contents. Now you have a portable tar command that can read its tar files from arbitrary locations on the Net. I'll confess that I was lazy about exception handling in this example. Of course, a real application would need to catch and handle the appropriate exceptions; but we already know how to do that. A final design note. Our content handler returned the tar listing as a String. I don't want to harp on the point, but this isn't the only option. If we were writing a content handler to work in the context of a Web browser, we might want it to produce some kind of HTML object that might display the listing as hypertext. Again, knowing the right solution requires that we know what kind of object a browser expects to receive, and currently that's undefined. In the next section, we'll turn the tables and look at protocol handlers. There we'll be building URLConnection objects and someone else will have the pleasure of reconstituting the data.
http://localhost/java/javaref/exp/ch09_05.htm (7 of 8) [20/12/2001 11:02:45]
[Chapter 9] 9.5 Writing a Content Handler
Web Browsers and Handlers
http://localhost/java/javaref/exp/ch09_05.htm (8 of 8) [20/12/2001 11:02:45]
Writing a Protocol Handler
[Chapter 9] 9.6 Writing a Protocol Handler
Chapter 9 Network Programming
9.6 Writing a Protocol Handler A URL object uses a protocol handler to establish a connection with a server and perform whatever protocol is necessary to retrieve data. For example, an HTTP protocol handler knows how to talk to an HTTP server and retrieve a document; an FTP protocol handler knows how to talk to an FTP server and retrieve a file. All types of URLs use protocol handlers to access their objects. Even the lowly "file" type URLs use a special "file" protocol handler that retrieves files from the local filesystem. The data a protocol handler retrieves is then fed to an appropriate content handler for interpretation. While we refer to a protocol handler as a single entity, it really has two parts: a java.net.URLStreamHandler and a java.net.URLConnection. These are both abstract classes we will subclass to create our protocol handler. (Note that these are abstract classes, not interfaces. Although they contain abstract methods we are required to implement, they also contain many utility methods we can use or override.) The URL looks up an appropriate URLStreamHandler, based on the protocol component of the URL. The URLStreamHandler then finishes parsing the URL and creates a URLConnection when it's time to communicate with the server. The URLConnection represents a single connection with a server, and implements the communication protocol itself.
Locating Protocol Handlers Protocol handlers are organized in a package hierarchy similar to content handlers. Unlike content handlers, which are grouped into packages by the MIME types of the objects that they handle, protocol handlers are given individual packages. Both parts of the protocol handler (the URLStreamHandler class and the URLConnection class) are located in a package named for the protocol they support. For example, the classes for an FTP protocol handler would be found in the net.www.protocol.ftp package. The URLStreamHandler is placed in this package and given the name Handler; all URLStreamHandlers are named Handler and distinguished by the package in which they reside. The URLConnection portion of the protocol handler is placed in the same package, and can be given any name. There is no need for a naming convention because the corresponding URLStreamHandler is responsible for creating the URLConnection objects it uses. Table 9.2 gives the obvious examples.[9] [9] The "pre-beta 1" release of HotJava has a temporary solution that is compatible with the convention described here. In the HotJava properties file, add the line: java.protocol.handler.pkgs=net.www.protocol. http://localhost/java/javaref/exp/ch09_06.htm (1 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
Table 9.2: Mapping Protocols into Package and Class Names Protocol Package URLStreamHandler Handler name FTP HTTP
class name
net.www.protocol.ftp Handler net.www.protocol.http Handler
class location net/www/protocol/ftp/ net/www/protocol/http/
URLs, Stream Handlers, and Connections The URL, URLStreamHandler, URLConnection, and ContentHandler classes work together closely. Before diving into an example, let's take a step back, look at the parts a little more closely, and see how these things communicate. Figure 9.5 shows how these components relate to each other. Figure 9.5: The protocol handler machinery
We begin with the URL object, which points to the resource we'd like to retrieve. The URLStreamHandler helps the URL class parse the URL specification string for its particular protocol. For example, consider the following call to the URL constructor: URL url = new URL("protocol://foo.bar.com/file.ext"); The URL class parses only the protocol component; later, a call to the URL class's getContent() or openStream() method starts the machinery in motion. The URL class locates the appropriate protocol handler by looking in the protocol-package hierarchy. It then creates an instance of the appropriate URLStreamHandler class. The URLStreamHandler is responsible for parsing the rest of the URL string, including hostname and filename, and possibly an alternative port designation. This allows different protocols to have their own variations on the format of the URL specification string. Note that this step is skipped when a URL is constructed with the "protocol," "host," and "file" components specified explicitly. If the protocol is straightforward, its URLStreamHandler class can let Java do the parsing and accept the default behavior. For this illustration, we'll assume that the URL string requires no special parsing. (If we use a nonstandard URL with a strange format, we're responsible for parsing it ourselves, as I'll show shortly.) http://localhost/java/javaref/exp/ch09_06.htm (2 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
The URL object next invokes the handler's openConnection() method, prompting the handler to create a new URLConnection to the resource. The URLConnection performs whatever communications are necessary to talk to the resource and begins to fetch data for the object. At that time, it also determines the MIME type of the incoming object data and prepares an InputStream to hand to the appropriate content handler. This InputStream must send "pure" data with all traces of the protocol removed. The URLConnection also locates an appropriate content handler in the content-handler package hierarchy. The URLConnection creates an instance of a content handler; to put the content handler to work, the URLConnection's getContent() method calls the content handler's getContent() method. If this sounds confusing, it is: we have three getContent() methods calling each other in a chain. The newly created ContentHandler object then acquires the stream of incoming data for the object by calling the URLConnection's getInputStream() method. (Recall that we acquired an InputStream in our x_tar content handler.) The content handler reads the stream and constructs an object from the data. This object is then returned up the getContent() chain: from the content handler, the URLConnection, and finally the URL itself. Now our application has the desired object in its greedy little hands. To summarize, we create a protocol handler by implementing a URLStreamHandler class that creates specialized URLConnection objects to handle our protocol. The URLConnection objects implement the getInputStream() method, which provides data to a content handler for construction of an object. The base URLConnection class implements many of the methods we need; therefore, our URLConnection needs only to provide the methods that generate the data stream and return the MIME type of the object data. Okay. If you're not thoroughly confused by all that terminology (or even if you are), let's move on to the example. It should help to pin down what all these classes are doing.
The crypt Handler In this section, we'll build a crypt protocol handler. It parses URLs of the form: crypt:type//hostname[:port]/location/item type is an identifier that specifies what kind of encryption to use. The protocol itself is a simplified version of HTTP; we'll implement the GET command and no more. I added the type identifier to the URL to show how to parse a nonstandard URL specification. Once the handler has figured out the encryption type, it dynamically loads a class that implements the chosen encryption algorithm and uses it to retrieve the data. Obviously, we don't have room to implement a full-blown public-key encryption algorithm, so we'll use the rot13InputStream class from Chapter 8, Input/Output Facilities. It should be apparent how the example can be extended by plugging in a more powerful encryption class. The Encryption class First, we'll lay out our plug-in encryption class. We'll define an abstract class called CryptInputStream that provides some essentials for our plug-in encrypted protocol. From the
http://localhost/java/javaref/exp/ch09_06.htm (3 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
CryptInputStream we'll create a subclass, rot13CryptInputStream, that implements our particular kind of encryption: package net.www.protocol.crypt; import java.io.*; abstract class CryptInputStream extends InputStream { InputStream in; OutputStream talkBack; abstract public void set( InputStream in, OutputStream talkBack ); } class rot13CryptInputStream extends CryptInputStream { public void set( InputStream in, OutputStream talkBack ) { this.in = new example.io.rot13InputStream( in ); } public int read() throws IOException { if ( in == null ) throw new IOException("No Stream"); return in.read(); } } Our CryptInputStream class defines a method called set() that passes in the InputStream it's to translate. Our URLConnection calls set() after creating an instance of the encryption class. We need a set() method because we want to load the encryption class dynamically, and we aren't allowed to pass arguments to the constructor of a class when it's dynamically loaded. We ran into this same restriction in our content handler. In the encryption class, we also provide an OutputStream. A more complex kind of encryption might use the OutputStream to transfer public-key information. Needless to say, rot13 doesn't, so we'll ignore the OutputStream here. The implementation of rot13CryptInputStream is very simple. set() just takes the InputStream it receives and wraps it with the rot13InputStream filter we developed in Chapter 8, Input/Output Facilities. read() reads filtered data from the InputStream, throwing an exception if set() hasn't been called. The URLStreamHandler Next we'll build our URLStreamHandler class. The class name is Handler; it extends the abstract URLStreamHandler class. This is the class the Java URL looks up by converting the protocol name (crypt) into a package name (net.www.protocol.crypt). The fully qualified name of this class is net.www.protocol.crypt.Handler: package net.www.protocol.crypt;
http://localhost/java/javaref/exp/ch09_06.htm (4 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
import java.io.*; import java.net.*; public class Handler extends URLStreamHandler { String cryptype; protected void parseURL(URL u, String spec, int start, int end) { int slash = spec.indexOf('/'); cryptype = spec.substring(start, slash); start=slash; super.parseURL(u, spec, start, end); } protected URLConnection openConnection(URL url) throws IOException { return new CryptURLConnection( url, cryptype ); } } Java creates an instance of our URLStreamHandler when we create a URL specifying the crypt protocol. Handler has two jobs: to assist in parsing the URL specification strings and to create CryptURLConnection objects when it's time to open a connection to the host. Our parseURL() method overrides the parseURL() method in the URLStreamHandler class. It's called whenever the URL constructor sees a URL requesting the crypt protocol. For example: URL url = new URL("crypt:rot13//foo.bar.com/file.txt"); parseURL() is passed a reference to the URL object, the URL specification string, and starting and ending indexes that shows what portion of the URL string we're expected to parse. The URL class has already identified the protocol name, otherwise it wouldn't have found our protocol handler. Our version of parseURL() retrieves our type identifier from the specification, stores it in the variable cryptype, and then passes the rest on to the superclass's parseURL() method to complete the job. To find the encryption type, take everything between the starting index we were given and the first slash in the URL string. Before calling super.parseURL(), we update the start index, so that it points to the character just after the type specifier. This tells the superclass parseURL() that we've already parsed everything prior to the first slash, and it's responsible for the rest. Before going on, I'll note two other possibilities. If we hadn't hacked the URL string for our own purposes by adding a type specifier, we'd be dealing with a standard URL specification. In this case, we wouldn't need to override parseURL(); the default implementation would have been sufficient. It could have sliced the URL into host, port, and filename components normally. On the other hand, if we had created a completely bizarre URL format, we would need to parse the entire string. There would be no point calling super.parseURL(); instead, we'd have called the URLStreamHandler's protected method setURL() to pass the URL's components back to the URL object. http://localhost/java/javaref/exp/ch09_06.htm (5 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
The other method in our Handler class is openConnection(). After the URL has been completely parsed, the URL object calls openConnection() to set up the data transfer. openConnection() calls the constructor for our URLConnection with appropriate arguments. In this case, our URLConnection object is named CryptURLConnection, and the constructor requires the URL and the encryption type as arguments. parseURL() picked the encryption type from the URL string and stored it in the cryptype variable. openConnection() returns a reference to our URLConnection, which the URL object uses to drive the rest of the process. The URLConnection Finally, we reach the real guts of our protocol handler, the URLConnection class. This is the class that opens the socket, talks to the server on the remote host, and implements the protocol itself. This class doesn't have to be public, so you can put it in the same file as the Handler class we just defined. We call our class Crypt-URLConnection; it extends the abstract URLConnection class. Unlike ContentHandler and StreamURLConnection, whose names are defined by convention, we can call this class anything we want; the only class that needs to know about the URLConnection is the URLStreamHandler, which we wrote ourselves. class CryptURLConnection extends URLConnection { CryptInputStream cis; static int defaultPort = 80; CryptURLConnection ( URL url, String cryptype ) throws IOException { super( url ); try { String name = "net.www.protocol.crypt." + cryptype + "CryptInputStream"; cis = (CryptInputStream)Class.forName(name).newInstance(); } catch ( Exception e ) { } } synchronized public void connect() throws IOException { int port; if ( cis == null ) throw new IOException("Crypt Class Not Found"); if ( (port = url.getPort()) == -1 ) port = defaultPort; Socket s = new Socket( url.getHost(), port ); // Send the filename in plaintext OutputStream server = s.getOutputStream(); new PrintStream( server ).println( "GET "+url.getFile() ); // Initialize the CryptInputStream http://localhost/java/javaref/exp/ch09_06.htm (6 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
cis.set( s.getInputStream(), server ); connected = true; } synchronized public InputStream getInputStream() throws IOException { if (!connected) connect(); return ( cis ); } public String getContentType() { return guessContentTypeFromName( url.getFile() ); } } The constructor for our CryptURLConnection class takes as arguments the destination URL and the name of an encryption type. We pass the URL on to the constructor of our superclass, which saves it in a protected url instance variable. We could have saved the URL ourselves, but calling our parent's constructor shields us from possible changes or enhancements to the base class. We use cryptype to construct the name of an encryption class, using the convention that the encryption class is in the same package as the protocol handler (i.e., net.www.protocol.crypt); its name is the encryption type followed by the suffix CryptInputStream. Once we have a name, we need to create an instance of the encryption class. To do so, we use the static method Class.forName() to turn the name into a Class object and newInstance() to load and instantiate the class. (This is how Java loads the content and protocol handlers themselves.) newInstance() returns an Object; we need to cast it to something more specific before we can work with it. Therefore, we cast it to our CryptInputStream class, the abstract class that rot13CryptInputStream extends. If we implement any additional encryption types as extensions to CryptInputStream and name them appropriately, they will fit into our protocol handler without modification. We do the rest of our setup in the connect() method of the URLConnection. There, we make sure we have an encryption class and open a Socket to the appropriate port on the remote host. getPort() returns -1 if the URL doesn't specify a port explicitly; in that case we use the default port for an HTTP connection (port 80). We ask for an OutputStream on the socket, assemble a GET command using the getFile() method to discover the filename specified by the URL, and send our request by writing it into the OutputStream. (For convenience, we wrap the OutputStream with a PrintStream and call println() to send the message.) We then initialize the CryptInputStream class by calling its set() method and passing it an InputStream from the Socket and the OutputStream. The last thing connect() does is set the boolean variable connected to true. connected is a protected variable inherited from the URLConnection class. We need to track the state of our connection because connect() is a public method. It's called by the URLConnection's getInputStream() method, but it could also be called by other classes. Since we don't want to start a connection if one already exists, we use connected to tell us if this is so.
http://localhost/java/javaref/exp/ch09_06.htm (7 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
In a more sophisticated protocol handler, connect() would also be responsible for dealing with any protocol headers that come back from the server. In particular, it would probably stash any important information it can deduce from the headers (e.g., MIME type, content length, time stamp) in instance variables, where it's available to other methods. At a minimum, connect() strips the headers from the data so the content handler won't see them. I'm being lazy and assuming that we'll connect to a minimal server, like the modified TinyHttpd daemon I discuss below, which doesn't bother with any headers. The bulk of the work has been done; a few details remain. The URLConnection's getContent() method needs to figure out which content handler to invoke for this URL. In order to compute the content handler's name, getContent() needs to know the resource's MIME type. To find out, it calls the URLConnection's getContentType() method, which returns the MIME type as a String. Our protocol handler overrides getContentType(), providing our own implementation. The URLConnection class provides a number of tools to help determine the MIME type. It's possible that the MIME type is conveyed explicitly in a protocol header; in this case, a more sophisticated version of connect() would have stored the MIME type in a convenient location for us. Some servers don't bother to insert the appropriate headers, though, so you can use the method guessContentTypeFromName() to examine filename extensions, like .gif or .html, and map them to MIME types. In the worst case, you can use guessContentTypeFromStream() to intuit the MIME type from the raw data. The Java developers call this method "a disgusting hack" that shouldn't be needed, but that is unfortunately necessary "in a world where HTTP servers lie about content types and extensions are often nonstandard." We'll take the easy way out and use the guessContentTypeFromName() utility of the URLConnection class to determine the MIME type from the filename extension of the URL we are retrieving. Once the URLConnection has found a content handler, it calls the content handler's getContent() method. The content handler then needs to get an InputStream from which to read the data. To find an InputStream, it calls the URLConnection's getInputStream() method. getInputStream() returns an InputStream from which its caller can read the data after protocol processing is finished. It checks whether a connection is already established; if not, it calls connect() to make the connection. Then it returns a reference to our CryptInputStream. A final note on getting the content type: if you read the documentation, it's clear that the Java developers had some ideas about how to find the content type. The URLConnection's default getContentType() calls getHeaderField(), which is presumably supposed to extract the named field from the protocol headers (it would probably spit back information connect() had stored in protected variables). The problem is there's no way to implement getHeaderField() if you don't know the protocol, and since the Java developers were designing a general mechanism for working with protocols, they couldn't make any assumptions. Therefore, the default implementation of getHeaderField() returns null; you have to override it to make it do anything interesting. Why wasn't it an abstract method? I can only guess, but making getHeaderField() abstract would have forced everyone building a protocol handler to implement it, whether or not they actually needed it. The application We're almost ready to try out a crypt URL! We still need an application (a mini-browser, if you will) to use our protocol handler, and a server to serve data with our protocol. If HotJava were available, we
http://localhost/java/javaref/exp/ch09_06.htm (8 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
wouldn't need to write the application ourselves; in the meantime, writing this application will teach us a little about how a Java-capable browser works. Our application is similar to the application we wrote to test the x_tar content handler. Because we're working in a standalone application, we have to tell Java how to find our protocol-handler classes. Java relies on a java.net.URLStreamHandlerFactory object to take a protocol name and return an instance of the appropriate handler. The URLStreamHandlerFactory is very similar to the ContentHandlerFactory we saw earlier. We'll provide a trivial implementation that knows only our particular handler. Again, if we were using our protocol handler with HotJava, this step would not be necessary; HotJava has its own stream-handler factory that tells it where to find handlers. To get HotJava to read files with our new protocol, we'd only have to put our protocol handler in the right place. (Note too, that an applet running in HotJava can use any of the methods in the URL class and therefore can use the content- and protocol-handler mechanism; applets would also rely on HotJava's stream-handler and content-xhandler factories.) Here's our StreamHandlerFactory and sample application: import java.net.*; class OurURLStreamHandlerFactory implements URLStreamHandlerFactory { public URLStreamHandler createURLStreamHandler(String protocol) { if ( protocol.equalsIgnoreCase("crypt") ) return new net.www.protocol.crypt.Handler(); else return null; } } class CryptURLTest { public static void main( String argv[] ) throws Exception { URL.setURLStreamHandlerFactory( new OurURLStreamHandlerFactory()); URL url = new URL("crypt:rot13//foo.bar.com:1234/myfile.txt"); System.out.println( url.getContent() ); } } The CryptURLTest class installs our factory and reads a document via the new "crypt:rot13" URL. (In the example, we have assumed that a rot13 server is running on port 1234 on the host foo.bar.com.) When the CryptURLTest application calls the URL's getContent() method, it automatically finds our protocol handler, which decodes the file. OurURLStreamHandlerFactory is really quite simple. It implements the URLStreamHandlerFactory interface, which requires a single method called createURLStreamHandler(). In our case, this method checks whether the protocol's name is http://localhost/java/javaref/exp/ch09_06.htm (9 of 10) [20/12/2001 11:02:46]
[Chapter 9] 9.6 Writing a Protocol Handler
crypt ; if so, the method returns an instance of our encryption protocol handler, net.www.protocol.crypt.Handler. For any other protocol name, it returns null. If we were writing a browser and needed to implement a more general factory, we would compute a class name from the protocol name, check to see if that class exists, and return an instance of that class. The server We still need a rot13 server. Since the crypt protocol is nothing more than HTTP with some encryption added, we can make a rot13 server by modifying one line of the TinyHttpd server we developed earlier, so that it spews its files in rot13. Just change the line that reads the data from the file: f.read( data ); To instead read through a rot13InputStream: new example.io.rot13InputStream( f ).read( data ); I assume you placed the rot13InputStream example in a package called example.io, and that it's somewhere in your class path. Now recompile and run the server. It automatically encodes the files before sending them; our sample application decodes them on the other end. I hope that this example and the rest of this chapter have given you some food for thought. Content and protocol handlers are among the most exciting ideas in Java. It's unfortunate that we have to wait for future releases of HotJava and Netscape to take full advantage of them. In the meantime, you can experiment and implement your own applications.
Writing a Content Handler
http://localhost/java/javaref/exp/ch09_06.htm (10 of 10) [20/12/2001 11:02:46]
Understand the Abstract Windowing Toolkit
[Chapter 10] 10.2 Applets
Chapter 10 Understand the Abstract Windowing Toolkit
10.2 Applets If you've been waiting for a more detailed discussion of the applet class, here it is. For examples of writing applets, please see Chapter 2, A First Applet (the tutorial) and the examples in Chapter 11, Using and Creating GUI Components and throughout the book. An Applet is something like a Panel with a mission. It is a GUI Container that has some extra structure to allow it to be used in an "alien" environment like a Web browser or appletviewer. Applets also have a life-cycle that lets them act more like an application than a static component. Although applets tend to be relatively simple, there's no inherent restriction on their complexity. There's no reason you couldn't write an air traffic control system (well, let's be less ambitious: a word processor) as an applet. Structurally, an applet is a sort of wrapper for your Java code. In contrast to a standalone graphical Java application, which starts up from a main() method and creates a GUI, an applet is itself a Component that expects to be dropped into someone else's GUI. Thus, an applet can't run by itself; it runs in the context of a Web browser or an appletviewer. Instead of having your application create a Frame to hold your GUI, you stuff your application inside an Applet (which is itself a Container) and let someone else add the applet to their GUI. Pragmatically, an applet is an intruder into someone else's environment, and therefore has to be treated with suspicion. The Web browsers that run applets impose restrictions on what the applet is allowed to do. The restrictions are enforced by a security manager, which the applet is not allowed to change. The browser also provides an "applet context," which is additional support that helps the applet live within its restrictions. Aside from that top level structure and the security restrictions, there is no difference between an applet and an application. If your application can live within the restrictions imposed by a browser's security manager, you can easily structure it to function as an applet and a standalone application. (We'll show an example of an Applet that can also be run as a standalone below.) Conversely, if you can supply all of the things that an applet requires from its environment, you can use applets within your stand-alone applications and within other applets (though this requires a bit of work). As we said a moment ago, an Applet expects to be embedded in GUI (perhaps a document) and used in a viewing environment that provides it with special resources. In all other respects, however, applets are just ordinary Panel objects. (See Figure 10.8.) Like a Panel, an Applet can contain user-interface components and implement all the basic drawing and event-handling capabilities of the Component class. We draw on an Applet by overriding its paint() method; we respond to events in the Applet's display area by providing the appropriate event-listeners. The additional structure applets have helps them interact with the viewer environment. Figure 10.8: The java.applet package
http://localhost/java/javaref/exp/ch10_02.htm (1 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
Applet Control The Applet class contains four methods an applet can override to guide it through its life cycle. The init(), start(), stop(), and destroy() methods are called by an applet viewer, such as a Web browser, to direct the applet's behavior. init() is called once, after the applet is created. The init() method is where you perform basic setup like parsing parameters, building a user interface, and loading resources. Given what we've said about objects, you might expect the Applet's constructor would be the right place for such initialization. However, the constructor is meant to be called by the applet's environment, for simple creation of the applet. This might happen before the applet has access to certain resources, like information about its environment. Therefore, an applet doesn't normally do any work in its constructor; it relies on the default constructor for the Applet class and does its initialization in the init() method. The start() method is called whenever the applet becomes visible; it shouldn't be a surprise then that the stop() method is called whenever the applet becomes invisible. init() is only called once in the life of an applet, but start() and stop() can be called any number of times (but always in the logical sequence). For example, start() is called when the applet is displayed, such as when it scrolls onto the screen; stop() is called if the applet scrolls off the screen or the viewer leaves the document. start() tells the applet it should be active. The applet may want to create threads, animate, or otherwise perform useful (or annoying) activity. stop() is called to let the applet know it should go dormant. Applets should cease CPU-intensive or wasteful activity when they are stopped and resume it when (and if) they are restarted. However, there's no requirement that an invisible applet stop computing; in some applications, it may be useful for the applet to continue running in the background. Just be considerate of your user, who doesn't want an invisible applet dragging down system performance. And for the users: be aware of the tools that will develop to let you monitor and squash rogue applets in your web browser. Finally, the destroy() method is called to give the applet a last chance to clean up before it's removed--some time after the call to stop(). For example, an applet might want to close down suspended communications channels or remove graphics frames. Exactly when destroy() is called depends on the applet viewer; Netscape Navigator calls destroy() just prior to deleting the applet from its cache. This means that although an applet can cling to life after being told to stop(), how long it can go on is unpredictable. If you want to maintain your applet as the user progresses through other activities, consider putting it in an HTML frame (see "Driving the Browser" later in this chapter).
http://localhost/java/javaref/exp/ch10_02.htm (2 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
The Applet security Sandbox Applets are quarantined within the browser by an applet SecurityManager. The SecurityManager is part of the application that runs the applet, e.g., the web browser or applet viewer. It is installed before the browser loads any applets and implements the basic restrictions that let you run untrusted applets safely. Remember that, aside from basic language robustness, there are no inherent security restrictions on a standalone Java application. It is the browser's responsibility to install a special security manager and limit what applets are allowed to do. Most browsers impose the following restrictions on untrusted applets: ● Untrusted Applets cannot read or write files on the local host. ● Untrusted Applets can only open network connections (sockets) to the server from which they originated. ● Untrusted Applets cannot start other processes on the local host. ● Untrusted Applets cannot have native methods. We discuss these restrictions in more detail in the relevant chapters in this book. However, the motivation for these restrictions should be fairly obvious: you clearly wouldn't want a program coming from some random Internet site to access your files, or run arbitrary programs. Although untrusted applets cannot directly read and write files on the client side or talk to arbitrary hosts on the network, applets can work with servers to store data and communicate. For example, an applet can use Java's RMI (Remote Method Invocation) facility to do processing on its server. An applet can communicate with other applets on the Net by proxy through its server. Trusted Applets The latest version of Java makes it possible to sign archive files that contain applets. Because a signature identifies the applet's origin unambiguously, we can now distinguish between "trusted" applets (i.e., applets that come from a site or person you trust not to do anything harmful) and run of the mill "untrusted" applets. In web browsers that support signing, trusted applets can be granted permission to "go outside" of the applet security sandbox. Trusted applets can be allowed to do most of the things that standalone Java applications can do: read and write files, open network connections to arbitrary machines, and interact with the local operating system by starting processes. Trusted applets still can't have native methods, but including native methods in an applet would make it unportable, and would therefore be a bad idea. Chapter 3, Tools of the Trade discusses how to package your applet's class files and resources into a JAR file and sign it with your digital signature. Currently, HotJava is the only browser that supports signing, but Netscape Navigator, Internet Explorer, and others will probably catch up soon.
Getting Applet Resources An applet needs to communicate with its applet viewer. For example, it needs to get its parameters from the HTML document in which it appears. An applet may also need to load images, audio clips, and other items. It may also want to ask the viewer about other applets on the same HTML page in order to communicate with them. To get resources from the applet viewer environment, applets use the AppletStub and AppletContext interfaces. Unless you're writing a browser or some other application that loads and runs applets, you won't have to implement these interfaces, but you do use them within your applet. Applet Parameters An applet gets its parameters from the parameter tags placed inside the tag in the HTML document. For example, the code below reads the "sheep" parameter from its HTML page: String imageName = getParameter( "imageName" ); try { http://localhost/java/javaref/exp/ch10_02.htm (3 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
int numberOfSheep = Integer.parseInt(getParameter( "sheep" )); } catch ( NumberFormatException e ) { // use default } A friendly applet will provide information about the parameters it accepts through its getParameterInfo() method. getParameterInfo() returns an array of string arrays, listing and describing the applet's parameters. For each parameter, three strings are provided: the parameter name, its possible values or value types, and a verbose description. For example: public String [][] getParameterInfo() { String [][] appletInfo = {"logo", "url", "Main logo image"} {"timer", "int", "Time to wait before becoming annoying"}, {"flashing", "constant | intermittant", "Flag for how to flash"}, return appletInfo; } Applet Resources An applet can find where it lives by calling the getDocumentBase() and getCodeBase() methods. getDocumentBase() returns the base URL of the document in which the applet appears; getCodeBase() returns the base URL of the Applet's class files. An applet can use these to construct relative URLs from which to load other resources like images, sounds, and other data. The getImage() method takes a URL and asks for an image from the viewer environment. The image may be pulled from a cache or loaded asynchronously when later used. The getAudioClip() method, similarly, retrieves sound clips. See Chapter 9, Network Programming for a full discussion of how to work with URLs, and Chapter 11, Using and Creating GUI Components for examples of applets that load images. The following example uses getCodeBase() to construct a URL and load a properties-configuration file, located at the same location as the applet's class file. (See Chapter 7, Basic Utility Classes for a discussion of properties.) Properties props = new Properties(); try { URL url = new URL(getCodeBase(), "appletConfig.props"); props.load( url.openStream() ); } catch ( IOException e ) { // failed } A better way to load resources is by calling the getResource() and getResourceAsStream() methods of the Class class, which search the applet's JAR files (if any) as well as its codebase. See Chapter 8, Input/Output Facilities for a discussion of resource loading. The following code loads the properties file appletConfig.props: Properties props = new Properties(); try { props.load( getClass().getResourceAsStream("appletConfig.props") ); } catch ( IOException e ) { // failed } Driving the Browser The status line is a blurb of text that usually appears somewhere in the viewer's display, indicating a current activity. An applet can request that some text be placed in the status line with the showStatus() method. (The browser isn't required to do anything in response to this call, but most browsers will oblige you.) An applet can also ask the browser to show a new document. To do this, the applet makes a call to the showDocument(
http://localhost/java/javaref/exp/ch10_02.htm (4 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
url ) method of the AppletContext. You can get a reference to the AppletContext with the Applet's getAppletContext() method. showDocument() can take an additional String argument to tell the browser where to display the new URL: getAppletContext().showDocument( url, name ); The name argument can be the name of an existing labeled HTML frame; the document referenced by the URL will be displayed in that frame. You can use this method to create an applet that "drives" the browser to new locations dynamically, but stays active on the screen in a separate frame. If the named frame doesn't exist, the browser will create a new top-level window to hold it. Alternatively, name can have one of the following special values: _self Show in the current Frame _parent Show in the parent of our Frame _top Show in outer-most (top level) frame. _blank Show in a new top level browser window. Both showStatus() and showDocument() requests may be ignored by a cold-hearted viewer or Web browser. *** Missing Discussion of getApplet() *** *** Add a blurb about the upcoming InfoBus stuff *** Applets vs. Standalone Applications *** Discuss getImage() and image loading from JAR files for applications *** The following list summarizes the methods of the applet API: // from the AppletStub boolean isActive(); URL getDocumentBase(); URL getCodeBase(); String getParameter(String name); AppletContext getAppletContext(); void appletResize(int width, int height); // from the AppletContext AudioClip getAudioClip(URL url); Image getImage(URL url); Applet getApplet(String name); Enumeration getApplets(); void showDocument(URL url); public void showDocument(URL url, String target); void showStatus(String status); These are the methods that are provided by the applet viewer environment. If your applet doesn't happen to use any of them, or if you can provide alternatives to handle special cases (such as loading images from JAR files), your applet could be made able to function as a standalone application as well as an applet. For example, our HelloWeb applet from Chapter 2, A First Applet was very simple. We can easily give it a main() method to allow it to be run as a standalone application: public class HelloWeb extends Applet {
http://localhost/java/javaref/exp/ch10_02.htm (5 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
public void paint( java.awt.Graphics gc ) { gc.drawString( "Hello Web!", 125, 95 ); } public static void main( String [] args ) { Frame theFrame = new Frame(); Applet helloWeb = new HelloWeb(); theFrame.add("Center", helloWeb); theFrame.setSize(200,200); helloWeb.init(); helloWeb.start(); theFrame.show(); } } Here we get to play "appletviewer" for a change. We have created an instance of HelloWeb using its constructor something we don't normally do$mdash;and added it to our own Frame. We call its init() method to give the applet a chance to wake up and then call its start() method. In this example, HelloWeb doesn't implement these, init() and start(), so we're calling methods inherited from the Applet class. This is the procedure that an appletviewer would use to run an applet. (If we wanted to go further, we could implement our own AppletContext and AppletStub, and set them in the Applet before startup). Trying to make your applets into applications as well often doesn't make sense, and is not always trivial. We show this only to get you thinking about the real differences between applets and applications. It is probably best to stay within the applet API until you have a need to go outside it. Remember that trusted applets can do almost all of the things that applications can. It is probably wiser to make an applet that requires trusted permissions than an application.
Events We've spent a lot of time discussing the different kinds of objects in AWT--components, containers, and a few special containers like applets. But we've neglected communications between different objects. A few times, we've mentioned events, and we have even used them in the occasional program (like our applets in Chapter 2, A First Applet), but we have deferred a discussion of events until later. Now is the time to pay that debt. AWT objects communicate by sending events. The way we talk about "firing" events and "handling" them makes it sound as if they are part of some special Java language feature. But they aren't. An event is simply an ordinary Java object that is delivered to its receiver by invoking an ordinary Java method. Everything else, however interesting, is purely convention. The entire Java event mechanism is really just a set of conventions for the kinds of descriptive objects that should be delivered; these conventions prescribe when, how, and to whom events should be delivered. Events are sent from a single source object to one or more listeners (or "targets"). A listener implements specific event handling methods that enable it to receive a type of event. It then registers itself with a source of that kind of event. Sometimes there may be an "adapter" object interposed between the event source and the listener, but there is always a connection established before any events are delivered. An event object is a subclass of java.util.EventObject that holds information about "something that's happened" to its source. The EventObject class serves mainly to identify event objects; the only information it contains is a reference to the event source (the object that sent the event). Components do not normally send or receive EventObjects as such; they work with subclasses that provide more specific information. AWTEvent is a subclass of EventObject that is used within AWT; further subclasses of AWTEvent provide information about specific event types. For example, events of type ActionEvent are fired by buttons when they are pushed. ActionEvents are also sent when a menu item is selected or when a user presses ENTER in a TextField. Similarly, MouseEvents are http://localhost/java/javaref/exp/ch10_02.htm (6 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
generated when you operate your mouse within a component's area. You can gather the general meaning of these two events from their names; they are relatively self-descriptive. ActionEvents correspond to a decisive "action" that a user has taken with the component--like pressing a button, or pressing ENTER to indicate that he has filled in a text field. An ActionEvent thus carries the name of an action to be performed (the "action command") by the program. MouseEvents describe the state of the mouse, and therefore carry information like the x and y coordinates and the state of your mouse buttons at the time it was created. You might hear someone say that ActionEvent is at a "higher semantic level" than MouseEvent. This means that ActionEvent is an interpretation of something that happened and is, therefore, conceptually more powerful than the MouseEvent, which carries raw data. An ActionEvent lets us know that a component has done its job, while a MouseEvent simply confers a lot of information about the mouse at a given time. You could figure out that somebody clicked on a Button by examining mouse events, but it is simpler to work with action events. The precise meaning of an event, however, can depend on the context in which it is received. (More on that in a moment.) Event Receivers and Listener Interfaces An event is delivered by passing it as an argument to an event handler method in the receiving object. ActionEvents, for example, are always delivered to a method called actionPerformed() in the receiver: // Receiver public void actionPerformed( ActionEvent e ) { ... } For each type of event, there is a corresponding listener interface that describes the methods it must provide to receive those events. In this case, any object that receives ActionEvents must implement the ActionListener interface: public interface ActionListener extends java.util.EventListener { public void actionPerformed( ActionEvent e ); } // Reciever implements ActionListener All listener interfaces are subinterfaces of java.util.EventListener, but EventListener is simply an empty interface. It exists only to help the compiler identify listener interfaces. Listener interfaces are required for a number of reasons. First, they help to identify objects that are capable of receiving a given type of event. This way we can give the event handler methods friendly, descriptive names and still make it easy for documentation, tools, and humans to recognize them in a class. Next, listener interfaces are useful because there can be several methods specified for an event receiver. For example, the FocusListener interface contains two methods: abstract void focusGained( FocusEvent e ); abstract void focusLost( FocusEvent e ); Athough these methods both take a FocusEvent as an argument, they correspond to different meanings for why the event was fired; in this case, whether the FocusEvent means that focus was received or lost. You could figure out what happened by inspecting the event; all AWTEvents contain a constant specifying the event's subtype. By requiring two methods, the FocusListener interface saves you the effort: if focusGained() is called, you know the event type was FOCUS_GAINED. Similarly, the MouseListener interface defines five methods for receiving mouse events (and MouseMotionListener defines two more), each of which gives you some additional information about why the event occurred. In general, the listener interfaces group sets of related event handler methods; the method called in any given situation provides a context for the information in the event object. There can be more than one listener interface for dealing with a particular kind of event. For example, the http://localhost/java/javaref/exp/ch10_02.htm (7 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
MouseListener interface describes methods for receiving MouseEvents when the mouse enters or exits an area, or a mouse button is pressed or released. MouseMotionListener is an entirely separate interface that describes methods to get mouse events when the mouse is moved (no buttons pressed) or dragged (buttons pressed). By separating mouse events into these two categories, Java lets you be a little more selective about the circumstances under which you want to recieve MouseEvents. You can register as a listener for mouse events without receiving mouse motion events; since mouse motion events are extremely common, you don't want to handle them if you don't need to. Finally, we should point out two simple patterns in the naming of AWT event listener interfaces and handler methods: ● Event handler methods are public methods that return type void and take a single event object (a subclass of java.util.EventObject as an argument).[2]
●
[2] This rule is not complete. The full Java Beans allows event handler methods to take additional arguments when absolutely necessary and also to throw checked exceptions. Listener interfaces are subclasses of java.util.EventListener that are named with the suffix "Listener," e.g., FooListener.
These may seem pretty obvious, but they are important because they are our first hint of a design pattern governing how to build components that work with events. Event Sources The previous section described the machinery that an event receiver uses to accept events. In this section we'll describe how the receiver tells an event source to start sending it events as they occur. To receive events, an eligible listener must register itself with an event source. It does this by calling an "add listener" method in the event source, and passing a reference (a callback) to itself. For example, the AWT Button class is a source of ActionEvents. In order to receive these events, our code might do something like the following: // source of ActionEvents Button theButton = new Button("Belly"); // receiver of ActionEvents class TheReceiver implements ActionListener { setupReceiver() { ... theButton.addActionListener( this ); } public void actionPerformed( ActionEvent e ) { // Belly Button pushed... } The receiver makes a call to addActionListener() to complete its setup and become eligible to receive ActionEvents from the button when they occur. It passes the reference this, to add itself as the ActionListener. To manage its listeners, an ActionEvent source (like the Button) always implements two methods: // ActionEvent source public void addActionListener(ActionListener listener) { ... } public void removeActionListener(ActionListener listener) {
http://localhost/java/javaref/exp/ch10_02.htm (8 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
... } The removeActionListener() method complements addActionListener() and does what you'd expect: it removes the listener from the list so that it will not receive future events from that source. Now, you may be expecting an "event source" interface listing these two methods, but there isn't one. There are no event source interfaces in the current conventions. If you are analyzing a class and trying to determine what events it generates, you have to look for the add and remove methods. For example, the presence of the addActionListener() and removeActionListener() methods define the object as a source of ActionEvents. If you happen to be a human being, you can simply look at the documentation; but if the documentation isn't available, or if you're writing a program that needs to analyze a class (a process called "reflection"), you can look for this design pattern: ● A source of events for the FooListener interface must implement a pair of add/remove methods: ❍ addFooListener(FooListener listener) (*) ❍ removeFooListener(FooListener listener) ● If an event source can only support one event listener (unicast delivery), the add listener method can throw the checked exception java.util.TooManyListenersException. So, what do all the naming patterns up to this point accomplish? Well, for one thing they make it possible for automated tools and integrated development environments to divine what are sources and what are sinks of particular events. Tools that work with Java Beans will use the Java reflection and introspection APIs to search for these kinds of design patterns and identify the events that can be fired and received by a component. It also means that event hookups are strongly typed, just like the rest of Java. So, it's not easy to accidentally hook up the wrong kind of components; for example, you can't register to receive ItemEvents from a Button, because a button doesn't have an addItemListener() method. Java knows at compile time what types of events can be delivered to whom. Event Delivery AWT events are multicast; every event is associated with a single source, but can be delivered to any number of receivers. Events are registered and distributed using an observer/observable model. When an event listener registers itself with an event source, the event source adds the listener to a list. When an event is fired, it is delivered individually to each listener on the list. Figure 10.9: Event delivery
There are no guarantees about the order in which events will be delivered. Neither are there any guarantees if you
http://localhost/java/javaref/exp/ch10_02.htm (9 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
register yourself more than once with an event source; you may get the event more than once, or not. Similarly, you should assume that every listener receives the same event data. Events are "immutable"; they can't be changed by their listeners. There's one important exception to this rule, which we'll discuss later. To be complete we could say that event delivery is synchronous with respect to the event source, but that follows from the fact that the event delivery is really just the invocation of a normal Java method. The source of the event calls the handler method of each listener. However, listeners shouldn't assume that all of the events will be sent in the same thread. An event source could decide to sent out events to all of the listeners in parallel. How exactly an event source maintains its set of listeners, constructs, and fires the events is up to it. Often it is sufficient to use a Vector to hold the list. We'll show the code for a component that uses a custom event in Chapter 11, Using and Creating GUI Components. For efficiency, AWT components all use the java.awt.AWTEventMulticaster object, which maintains a linked tree of the listeners for the component. You can use that too, if you are firing standard AWT events. We'll describe the event multicaster in Chapter 11, Using and Creating GUI Components as well. AWTEvents All of the events used by AWT GUI components are subclasses of java.awt.AWTEvent. AWTEvent holds some common information that is used by AWT to identify and process events. You can use or subclass any of the AWTEvent types for use in your own components. Use the event hierarchy from Java in a Nutshell or AWT Reference. ComponentEvent is the base class for events that can be fired by any AWT component. This includes events that provide notification when a component changes its dimensions or visibility, as well as the other event types for mouse operation and key presses. ContainerEvents are fired by AWT containers when components are added or removed. java.awt.event.InputEvent MouseEvents, which track the state of the mouse, and KeyEvents, which are fired when the user uses the keyboard, are types of java.awt.event.InputEvent. Input events from the mouse and keyboard are a little bit special. They are normally produced by the native Java machinery associated with the peers. When the user touches a key or moves the mouse within a component's area, the events are generated with that component as the source. Input events and some other AWT events are placed on a special event queue that is managed by the AWT Toolkit. This gives the Toolkit control over how the events are delivered. First, under some circumstances, the Toolkit can decide to "compress" a sequence of the same type of event into a single event. This is done to make some event types more efficient--in particular, mouse events and some special internal events used to control repainting. Perhaps more important to us, input events are delivered with a special arrangement that lets listeners decide if the component itself should act on the event. Consuming events Normally, the native peer of a standard AWT component operates by receiving InputEvents telling it about the mouse and keyboard. When you push a Button, the native ButtonPeer object receives a MouseEvent and does its job in native land to accomplish the button-depressing behavior. But for InputEvents, the Toolkit first delivers the event to any listeners registered with the the component and gives those listeners a chance to mark the event as "consumed," effectively telling the peer to ignore it. An InputEvent is marked "consumed" by calling the consume() method. (Yes, this is a case where an event is not treated as immutable.) So, we could stop our Button from working by registering a listener with it that catches "mouse button depressed"
http://localhost/java/javaref/exp/ch10_02.htm (10 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
events. When it got one, we could call its consume() method to tell the ButtonPeer to ignore that event. This is particularly useful if you happen to be building a develoment environment in Java and you want to "turn off" components while the user arranges them. If you need to, in a trusted application you can get access to the AWT event queue. The Toolkit uses an instance of java.awt.EventQueue. With it you can peek at pending AWT events or even to push in new ones. Mouse and Key Modifiers on InputEvents InputEvents come with a set of flags for special modifiers. These let you detect if the SHIFT or ALT key was held down during a mouse button or key press, or if the second or third mouse buttons were pressed. The following are the flag values contained in java.awt.event.InputEvent: ● SHIFT_MASK ● CTRL_MASK ● META_MASK ● ALT_MASK ● BUTTON1_MASK ● BUTTON2_MASK ● BUTTON3_MASK To check for these masks, you can simply do a boolean AND of the modifiers, returned by the InputEvent's getModifiers() method and the flag or flags you're interested in: public void mousePressed (MouseEvent e) { int mods = e.getModifiers(); if ((mods & InputEvent.SHIFT_MASK) != 0) // Shifted Mouse Button press } In the list you'll notice there are three BUTTON flags. These can be used to detect if a particular mouse button was used in a mouse press on a two or three button mouse. Be warned, if you use these you run the risk that your program won't work on platforms without multibutton mice. Currently, BUTTON2_MASK is equivalent to ALT_MASK, and BUTTON3_MASK is equivalent to META_MASK. This means that pushing the second mouse button is equivalent to pressing the first (or only) button with the ALT key depressed, and the third button is equivalent to the first with the META key depressed. However, if you really want to guarantee portability, you should limit yourself to a single button, possibly in combination with keyboard modifiers, rather than relying on the button masks. Key events provide one other situation in which events aren't immutable. You can change the character that the user typed by calling setKeyChar(), setKeyCode(), or setKeyModifiers(). A user's keystroke isn't displayed until the KeyEvent is delivered to the peer. Therefore, by changing the character in the KeyEvent, you can change the character displayed on the screen. This is a good way to implement a field that only displays uppercase characters, regardless of what the user types.
AWT Event Reference The following tables summarize the AWT Events, which components fire them, and the methods of the listener interfaces that receive them: AWT Component and Container Events Event
Fired by
Listener interface(s) Handler Method(s)
http://localhost/java/javaref/exp/ch10_02.htm (11 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
componentResized() ComponentEvent ComponentListener componentMoved() componentShown() componentHidden() focusGained() FocusEvent FocusListener focusLost() keyTyped() All Components (*) KeyEvent KeyListener keyPressed() keyReleased() mouseClicked() mousePressed() MouseListener mouseReleased() MouseEvent mouseEntered() mouseExited() mouseDragged() MouseMotionListener mouseMoved() componentAdded() ContainerEvent All Containers ContainerListener componentRemoved() Component specific AWT Events Event
Fired by Listener interface(s) Handler Method(s) TextField MenuItem ActionEvent ActionListener actionPerformed() List Button List Checkbox ItemEvent ItemListener itemStateChanged() Choice CheckboxMenuItem ScrollPane AdjustmentEvent AdjustmentListener adjustmentValueChanged() Scrollbar TextArea TextEvent TextListener textValueChanged() TextField windowOpened() windowClosing() windowClosed() WindowEvent Frame, Dialog WindowListener windowIconified() windowDeiconified() windowActivated() windowDeactivated()
http://localhost/java/javaref/exp/ch10_02.htm (12 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
Adapter Classes It's not ideal to have your application components implement a listener interface and receive events directly. Sometimes it's not even possible. Being an event receiver forces you to modify or subclass your objects to implement the appropriate event listener interfaces and add the code necessary to handle the events. A more subtle issue is that, since we are talking about AWT events here, you are, of necessity, building GUI logic into parts of your application that shouldn't have to know anything about the GUI. Let's look at an example: Figure 10.10: Implementing the ActionListener interface
In Figure 10.10 we have drawn the plans for our Vegomatic food processor. Here we have made our Vegomatic object implement the ActionListener interface so that it can receive events directly from the three Button components: "Chop," "Puree," and "Frappe." The problem is that our Vegomatic object now has to know more than how to mangle food. It also has to be aware that it will be driven by three controls, specifically buttons that send action commands, and be aware of which methods in itself it should invoke for those commands. Our boxes labeling the GUI and Application code overlap in an unwholesome way. If the marketing people should later want to add or remove buttons, or perhaps just change the names, we have to be careful. We may have to modify the logic in our Vegomatic Object. All is not well. An alternative is to place an "adapter" class between our event source and receiver. An adapter is a simple object whose sole purpose is to map an incoming event to an outgoing method. Figure 10.11: A design using adapter classes
Figure 10.11 shows a better design that uses three adapter classes, one for each button. The implementation of the first adapter might look like: class VegomaticAdapter1 implements actionListener { Vegotmatic vegomatic; VegomaticAdapter1 ( Vegotmatic vegomatic ) { this.vegomatic = vegomatic; }
http://localhost/java/javaref/exp/ch10_02.htm (13 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
public void actionPerformed( ActionEvent e ) { vegomatic.chopFood(); } } So somewhere in the code where we build our GUI, we could register our listener like so: // building GUI for our Vegomatic Vegomatic theVegomatic = ...; Button chopButton = ...; // make the hookup chopButton.addActionListener( new VegomaticAdapter1(theVegomatic) ); We have completely separated the messiness of our GUI from the application code. However, we have added three new classes to our application, none of which does very much. Is that good? That depends on your vantage point. Under different circumstances our buttons may have been able to share a common adapter class that was simply instantiated with different parameters. There are various trade-off that can be made between size, efficiency, and elegance of code. Often, adapter classes will be generated automatically by development tools. The way we have named our adapter classes "VegomaticAdapter1," "VegomaticAdapter2," and "VegomaticAdapter3" hints at this. More often, when hand coding, you'll use an inner class. At the other extreme, we can forsake Java's strong typing and use the reflection API to create a completely dynamic hookup betwen an event source and listener. AWT Dummy Adapters Many listener interfaces contain more than one event handler method. Unfortunately, this means that to register yourself as interested in any one of those events, you must implement the whole listener interface. And to accomplish this you might find yourself typing in dummy "stubbed out" methods, simply to complete the interface. There is really nothing wrong with this, but it is a bit tedious. To save you some trouble, AWT provides some helper classes that implement these dummy methods for you. For each listener interface containing more than one method there is an adapter class containing the stubbed methods. The adapter class serves as a base class for your own adapters. So, when you need a class to patch together your event source and listener, you can simply subclass the adapter and override only the methods you want. For example, the MouseAdapter class implements the MouseListener interface and provides the following implementation: public public public public public
void void void void void
mouseClicked(MouseEvent e) {}; mousePressed(MouseEvent e) {}; mouseReleased(MouseEvent e) {}; mouseEntered(MouseEvent e) {}; mouseExited(MouseEvent e) {};
This may not look like a tremendous time saver, and you're right. It's simply a bit of sugar. The primary advantage comes into play when we use the MouseAdapter as the base for your own adapter in an anonymous inner class. For example, suppose we want to catch a mousePressed() event in some component and blow up a building. We can use the following to make the hookup: someComponent.addMouseListener( new MouseAdapter() { public void MousePressed(MouseEvent e) { building.blowUp(); } } );
http://localhost/java/javaref/exp/ch10_02.htm (14 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
We've taken artistic liberties with the formatting, but I think it's very readable, and I like it. It's a common enough activity that it's nice to avoid typing those extra few lines and perhaps stave off the onset of carpal tunnel syndrome for a few more hours. Remember that any time you use an inner class, the compiler is generating a class for you, so the messiness you've saved in your source still exists in the output classes.
Old Style and New Style Event Processing Although Java is still a youngster, it has a bit of a legacy. Versions of Java before 1.1 used a different style of event delivery. Back in the old days (a few months ago) event types were limited and events were only delivered to the Component that generated it, or one of its parent containers. The old style component event handler methods (now deprecated) returned a boolean value declaring whether or not they had "handled" the event. boolean handleEvent( Event e ) { ... } If the method returns false, the event is automatically redelivered to the component's container to give it a chance. If the container does not handle it, it is passed on to its parent container and so on. In this way, events were propogated up the containment hierarchy until they were either consumed or passed over to the component peer, just as current InputEvents are ultimately interpreted used the peer if no registered event listeners have consumed them. Although this style of event delivery was convenient for some simple applications, it is not very flexible. Events could only be handled by components, which meant that you always had to subclass a Component or Container type to handle events. This was a degenerate use of inheritance (bad design) that led to the creation of lots of unnecessary classes. We could, alternatively, receive the events for many embedded components in a single parent container, but that would often lead to very convoluted logic in the container's event handling methods. It is also very costly to run every single AWT event through a guantlet of (often empty) tests as it traverses its way up the tree of containers. This is why Java now provides the more dynamic and general event source/listener model that we have described in this chapter. The old style events and event handler methods are, however, still with us. Java is not allowed to simply change and break an established API. Instead, as we described in Chapter 1, Yet Another Language?, older ways of doing things are simply "deprecated" in favor of the new ones. This means that code using the old style event handler methods will still work; you may see old-style code around for a long time. The problem with relying on old-style event delivery, however, is that the old and new ways of doing things cannot be mixed. By default, Java is obligated to perform the old behavior--offering events to the component and each of its parent containers. However, Java turns off the old style delivery whenever it thinks that we have elected to use the new style. Java determines whether a Component should recieve old style or new style events based on whether any event listeners are registered, or whether new style events have been explicitly enabled. When an AWT event listener is registered with a Component, new style events are implicitly turned on (a flag is set). Additionally, a mask is set telling the component the types of AWT events it should process. The mask allows components to be more selective about which events they process. processEvent() When new style events are enabled, all events are first routed to the dispatchEvent() method of the Component class. The dispatchEvent() method examines the component's event mask and decides whether the event should be processed or ignored. Events that have been "enabled" are sent to the processEvent() method, which simply looks at the event's type and delegates it to a "helper" processing method named for its type. The helper processing method finally dispatches the event to the set of registered listeners for its type.
http://localhost/java/javaref/exp/ch10_02.htm (15 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
This process closely parallels the way in which old style events are processed, and the way in which events are first directed to a single handleEvent() method that dispatches them to more specific handler methods in the Component class. The differences are that new style events are not delivered unless someone is listening for them, and the listener registration mechanism means that we don't have to subclass the component in order to override its event handler methods and insert our own code. Enabling New Style Events Explicitly Still, if you are subclassing a Component type for other reasons, or you really want to process all events in a single method, you should be aware that it is possible to emulate the old style event handling and override your component's event processing methods. You simply have to call the Component's enableEvents() method with the appropriate mask value to turn on processing for the given type of event. You can then override the corresponding method and insert your code. The mask values are found in the java.awt.AWTEvent class: java.awt.AWTEvent mask method COMPONENT_EVENT_MASK processComponentEvent() FOCUS_EVENT_MASK processFocusEvent() KEY_EVENT_MASK processKeyEvent() MOUSE_EVENT_MASK processMouseEvent() MOUSE_MOTION_EVENT_MASK processMouseMotionEvent() For example: public void init() { ... enableEvent( AWTEvent.KEY_EVENT_MASK ): } public void processKeyEvent(KeyEvent e) { if ( e.getID() == KeyEvent.KEY_TYPED ) // do work super.processKeyEvent(e); } If you do this it is vital that you remember to make a call to super.process...Event() in order to allow normal event delegation to continue. Of course, by emulating old-style event handling, we're giving up the virtues of the new style; in particular, this code is a lot less flexible than the code we could write with the new event model. As we've seen, the user interface is hopelessly tangled with the actual work your program does. A compromise solution would be to have your subclass declare that it implements the appropriate listener interface and register itself, as we have done in the simpler examples in this book: class MyApplet implements KeyListener ... public void init() { addKeyListener( this ): ... } public void keyTyped(KeyEvent e) { // do work }
http://localhost/java/javaref/exp/ch10_02.htm (16 of 17) [20/12/2001 11:02:49]
[Chapter 10] 10.2 Applets
GUI Concepts in Java
http://localhost/java/javaref/exp/ch10_02.htm (17 of 17) [20/12/2001 11:02:49]
Using and Creating GUI Components
[Chapter 11] 11.2 Text Components
Chapter 11 Using and Creating GUI Components
11.2 Text Components AWT gives us two basic text components: TextArea is a multiline text editor with vertical and horizontal scrollbars; TextField is a simple, single-line text editor. Both TextField and TextArea derive from the TextComponent class, which provides the functionality they have in common. This includes methods for setting and retrieving the displayed text, specifying whether the text is "editable" or read-only, manipulating the caret (cursor) position in the display, and manipulating the "selection text." Both TextAreas and TextFields send TextEvents to listeners when their text is modified. To receive these events, you must implement the java.awt.TextListener interface and register by calling the component's addTextListener() method. In addition, TextField components generate an ActionEvent whenever the user presses the RETURN key within the field. To get these events, implement the ActionListener interface and call addActionListener() to register. Here are a couple of simple applets that show you how to work with text areas and fields.
A TextEntryBox Our first example, TextEntryBox, creates a TextArea and ties it to a TextField, as you can see in Figure 11.1. When the user hits RETURN in the TextField, we receive an ActionEvent and add the line to the TextArea's display. Try it out. You may have to click your mouse in the TextField to give it focus before typing in it. If you fill up the display with lines, you can test drive the scrollbar. Figure 11.1: The TextEntryBox applet
http://localhost/java/javaref/exp/ch11_02.htm (1 of 7) [20/12/2001 11:02:50]
[Chapter 11] 11.2 Text Components
import java.awt.*; import java.awt.event.*; public class TextEntryBox extends java.applet.Applet implements ActionListener { TextArea area; TextField field; public void init() { setLayout( new BorderLayout() ); add( "Center", area = new TextArea() ); area.setFont( new Font("TimesRoman",Font.BOLD,18) ); area.setText("Howdy!\n"); add( "South", field = new TextField() ); field.addActionListener ( this ); } public void actionPerformed(ActionEvent e) { area.append( field.getText() + '\n' ); field.setText("");
http://localhost/java/javaref/exp/ch11_02.htm (2 of 7) [20/12/2001 11:02:50]
[Chapter 11] 11.2 Text Components
} } TextEntryBox is exceedingly simple; we've done a few things to make it more interesting. First, we set the applet's layout manager to BorderLayout. We use BorderLayout to position the TextArea above the TextField; the text area goes in the "North" region of the layout, and the text field is in the "South" region. We give the text area a bigger font using Component's setFont() method; fonts are discussed in Chapter 11, Using and Creating GUI Components. Finally, we want to be notified whenever the user types RETURN in the text field, so we register our applet (this) as a listener for action events by calling field.addActionListener(this). Hitting RETURN in the TextField generates an action event, and that's where the fun begins. We handle the event in the actionPerformed() method of our container, the TextEntryBox applet. Then we use the getText() and setText() methods to manipulate the text the user has typed. These methods can be used for both TextField and TextArea, because these components are derived from the TextComponent class, and therefore have some common functionality. Our event handler is called actionPerformed(), as required by the ActionListener interface. First, actionPerformed() calls field.getText() to read the text that the user typed into our TextField. It then adds this text to the TextArea by calling area.append(). Finally, we clear the text field by calling field.setText(""), preparing it for more input. By default, TextField and TextArea are editable; you can type and edit in both text components. They can be changed to output-only areas with the setEditable() method. Both text components also support selections. A selection is a subset of text that is highlighted for copying and pasting in your windowing system. You select text by dragging the mouse over it; you can then copy and paste it into other text windows. You can get the selected text explicitly with getSelectedText().
TextWatcher Applet Our next example is a TextWatcher that consists of two linked text areas. Anything the user types into either area is reflected in both. It demonstrates how to handle a TextEvent, which is generated whenever the text changes in a TextComponent. It also demonstrates how to use an adapter class, which is a more realistic way of setting up event listeners. Registering the applet as a listener is okay for simple programs, but the technique shown here will serve you better in more complex situations. Figure 11.2: The TextWatcher applet
http://localhost/java/javaref/exp/ch11_02.htm (3 of 7) [20/12/2001 11:02:50]
[Chapter 11] 11.2 Text Components
import java.awt.*; import java.awt.event.*; public class TextWatcher extends java.applet.Applet { TextArea area1, area2; public void init() { setLayout( new GridLayout(2,1) ); add( area1 = new TextArea() ); add( area2 = new TextArea() ); area1.addTextListener ( new TextSyncAdapter( area2 )); area2.addTextListener ( new TextSyncAdapter( area1 )); } class TextSyncAdapter implements TextListener { TextArea targetArea; TextSyncAdapter( TextArea targetArea ) { this.targetArea = targetArea; } public void textValueChanged(TextEvent e) { TextArea sourceArea = (TextArea)e.getSource(); if ( ! targetArea.getText().equals( sourceArea.getText() ) ) targetArea.setText( sourceArea.getText() ); } } } Setting up the display is simple. We use a GridLayout and add two text areas to the layout. Then we add our listeners for text events, which are generated whenever the text in a TextComponent is changed. There is one listener for each text area; both are TextSyncAdapter objects. One listens to events from area1 and modifies the text in area2; the other listens to events from area2 and modifies the text in area1. All the real work is done by the TextSyncAdapter. This is an inner class; its definition is contained within TextWatcher and can't be referenced by classes outside of our TextWatcher. The adapter implements the TextListener interface, and therefore includes a textValueChanged() method.
http://localhost/java/javaref/exp/ch11_02.htm (4 of 7) [20/12/2001 11:02:50]
[Chapter 11] 11.2 Text Components
textValueChanged() is the heart of the listener. First, it extracts the source area from the incoming event; this is the area that generated the event. The area whose text the listener is changing (the target area) was stored by the constructor. Then it tests whether or not the texts in both areas are the same. If they aren't, it calls the target area's setText() method to set its text equal to the source area's. The one mysterious feature of this method is the test for equality. Why is it necessary? Why can't we just say "the text in one area changed, so set the text in the other?" A TextEvent is generated whenever a TextComponent is modified for any reason; this includes changes caused by software, not just changes that occur when a user types. So think about what happens when the user types into area1. Typing generates a TextEvent, which causes the adapter to change the text in area2. This generates another TextEvent, which if we didn't do any testing, would cause us to change area1 again, which would generate another TextEvent, ad infinitum. By checking whether or not the texts in our two areas are equivalent, we prevent an infinite loop in which text events ping-pong back and forth between the two areas.
Managing Text Yourself Text areas and text fields do the work of handling keystrokes for you, but they're certainly not your only options for dealing with keyboard input. Any Component can register KeyListeners to recieve KeyEvents that occur when their component has focus Chapter 10, Understand the Abstract Windowing Toolkit. We will provide an example here that shows how you might use these to make your own text gadgets. Figure 11.3: The KeyWatcher applet
import java.awt.*; import java.awt.event.*; public class KeyWatcher extends java.applet.Applet { StringBuffer text = new StringBuffer(); public void init () { http://localhost/java/javaref/exp/ch11_02.htm (5 of 7) [20/12/2001 11:02:50]
[Chapter 11] 11.2 Text Components
setFont( new Font("TimesRoman",Font.BOLD,18) ); addKeyListener ( new KeyAdapter() { public void keyPressed( KeyEvent e ) { System.out.println(e); type( e.getKeyCode(), e.getKeyChar() ); } } ); requestFocus(); } public void type(int code, char ch ) { switch ( code ) { case ( KeyEvent.VK_BACK_SPACE ): if (text.length() > 0) text.setLength( text.length() - 1 ); break; case ( KeyEvent.VK_ENTER ): System.out.println( text ); // Process line text.setLength( 0 ); break; default: if ( (ch >= ' ') && (ch "); return; } text = args; Center f = new Center(); f.show(); } public void addNotify() { super.addNotify(); int maxWidth = 0; FontMetrics fm = getToolkit().getFontMetrics(getFont()); http://localhost/java/javaref/awt/ch03_02.htm (3 of 7) [20/12/2001 11:08:26]
[Chapter 3] 3.2 FontMetrics
for (int i=0;i= 3)) break; g.setColor (colors[i*5+j]); g.fillRect (i*width, j*height, width, height); } } } public boolean keyDown (Event e, int c) { for (int i=0;i 0) && (((TextField)(e.target)).getText ().length () >= this.size)) { // Check for backspace / delete / tab--let these pass through if ((key == 127) || (key == 8) || (key == 9)) { return false; } return true; } return false; } protected String paramString () { String str = super.paramString (); if (size != 0) { str += ",size=" + size; } return str; } } Most of the SizedTextField class consists of constructors; you really don't need to provide an equivalent to all the superclass's constructors, but it's not a bad idea. The keyDown() method looks at what the user types before it reaches the screen and acts accordingly. It checks the length of the TextField and compares it to the maximum length. It then does another check to see if the user typed a Backspace, Delete, or Tab, all of which we want to allow: if the field has gotten too long, we want to allow the user to shorten it. We also want to allow tab under all circumstances, so that focus traversal works properly. The rest of the logic is simple: ● If the user typed Backspace, Delete, or Tab, return false to propagate the event. ● If the field is too long, return true to prevent the event from reaching the peer. This effectively ignores the character.
TextArea
http://localhost/java/javaref/awt/ch08_04.htm (2 of 2) [20/12/2001 11:09:10]
Pick Me
[Chapter 9] 9.2 Lists
Chapter 9 Pick Me
9.2 Lists Like the Choice component, the List provides a way to present your user with a fixed sequence of choices to select. However, with List, several items can be displayed at a time on the screen. A List can also allow multiple selection, so that more than one choice can be selected. Normally, a scrollbar is associated with the List to enable the user to move to the items that do not fit on the screen. On some platforms, the List may not display the scrollbar if there is enough room to display all choices. A List can be resized by the LayoutManager according to the space available. Figure 9.2 shows two lists, one of which has no items to display.
List Methods Constructors public List () This constructor creates an empty List with four visible lines. You must rely on the current LayoutManager to resize the List or override the preferredSize() (version 1.0) or getPreferredSize() (version 1.1) method to affect the size of the displayed List. A List created with this constructor is in single-selection mode, so the user can select only one item at a time. public List (int rows) This constructor creates a List that has rows visible lines. This is just a request; the LayoutManager is free to adjust the height of the List to some other amount based upon available space. A List created with this constructor is in single-selection mode, so the user will be able to select only one item at a time. public List (int rows, boolean multipleSelections) The final constructor for List creates a List that has rows visible lines. This is just a request; the LayoutManager is free to adjust the height of the List to some other amount based upon available space. If multipleSelections is true, this List permits multiple items to be selected. If false, this is a single-selection list. Figure 9.2: Two lists; the list on the right is empty
http://localhost/java/javaref/awt/ch09_02.htm (1 of 10) [20/12/2001 11:09:13]
[Chapter 9] 9.2 Lists
Content control public int getItemCount () public int countItems () The getItemCount() method returns the length of the list. The length of the list is the number of items in the list, not the number of visible rows. countItems() is the Java 1.0 name for this method. public String getItem (int index) The getItem() method returns the String representation for the item at position index. The String is the parameter passed to the addItem() or add() method. public String[] getItems () The getItems() method returns a String array that contains all the elements in the List. This method does not care if an item is selected or not. public synchronized void add (String item) public synchronized void addItem (String item) The add() method adds item as the last entry in the List. If item already exists in the list, this method adds it again. addItem() is the Java 1.0 name for this method. public synchronized void add (String item, int index) public synchronized void addItem (String item, int index) This version of the add() method has an additional parameter, index, which specifies where to add item to the List. If index < 0 or index >= getItemCount(), item is added to the end of the List. The position count is zero based, so if index is 0, it will be added as the first item. addItem() is the Java 1.0 name for this method. public synchronized void replaceItem (String newItem, int index)
http://localhost/java/javaref/awt/ch09_02.htm (2 of 10) [20/12/2001 11:09:13]
[Chapter 9] 9.2 Lists
The replaceItem() method replaces the contents at position index with newItem. If the item at index has been selected, newItem will not be selected. public synchronized void removeAll () public synchronized void clear () The removeAll() method clears out all the items in the list. clear() is the Java 1.0 name for this method. NOTE: Early versions ( Java1.0) of the clear() method did not work reliably across platforms. You were better off calling the method listVar.delItems(0, listVar.countItems()-1), where listVar is your List instance. public synchronized void remove (String item) The remove() method removes item from the list of available choices. If item appears in the List several times, only the first instance is removed. If item is null, remove() throws the run-time exception NullPointerException. If item is not found in the List, remove() throws the IllegalArgumentException run-time exception. public synchronized void remove (int position) public synchronized void delItem (int position) The remove() method removes the entry at position from the List. If position is invalid--either position < 0 or position >= getItemCount()--remove() throws the ArrayIndexOutOfBoundsException run-time exception with a message indicating that position was invalid. delItem() is the Java 1.0 name for this method. public synchronized void delItems (int start, int end) The delItems() method removes entries from position start to position end from the List. If either parameter is invalid--either start < 0 or end >= getItemCount()--delItems() throws the ArrayIndexOutOfBoundsException run-time exception with a message indicating which position was invalid. If start is greater than end, nothing happens. Selection and positioning public synchronized int getSelectedIndex () The getSelectedIndex() method returns the position of the selected item. If nothing is selected in the List, getSelectedIndex() returns -1. The value -1 is also returned if the List is in multiselect mode and multiple items are selected. For multiselection lists, use getSelectedIndexes() instead. public synchronized int[] getSelectedIndexes () The getSelectedIndexes() method returns an integer array of the selected items. If nothing
http://localhost/java/javaref/awt/ch09_02.htm (3 of 10) [20/12/2001 11:09:13]
[Chapter 9] 9.2 Lists
is selected, the array will be empty. public synchronized String getSelectedItem () The getSelectedItem() method returns the label of the selected item. The label is the string used in the add() or addItem() call. If nothing is selected in the List, getSelectedItem() returns null. The return value is also null if List is in multiselect mode and multiple items are selected. For multiselection lists, use getSelectedItems() instead. public synchronized String[] getSelectedItems () The getSelectedItems() method returns a String array of the selected items. If nothing is selected, the array is empty. public synchronized Object[] getSelectedObjects () The getSelectedObjects() method returns the results of the method getSelectedItems() as an Object array instead of a String array, to conform to the ItemSelectable interface. If nothing is selected, the returned array is empty. public synchronized void select (int index) The select() method selects the item at position index, which is zero based. If the List is in single-selection mode, any other selected item is deselected. If the List is in multiple-selection mode, calling this method has no effect on the other selections. The item at position index is made visible. NOTE: A negative index seems to select everything within the List. This seems more like an irregularity than a feature to rely upon. public synchronized void deselect (int index) The deselect() method deselects the item at position index, which is zero based. deselect() does not reposition the visible elements. public boolean isIndexSelected (int index) public boolean isSelected (int index) The isIndexSelected() method checks whether index is currently selected. If it is, isIndexSelected() returns true; otherwise, it returns false. isSelected() is the Java 1.0 name for this method. public boolean isMultipleMode () public boolean allowsMultipleSelections () The isMultipleMode() method returns the current state of the List. If the List is in multiselection mode, isMultipleMode() returns true; otherwise, it returns false. allowsMultipleSelections() is the Java 1.0 name for this method.
http://localhost/java/javaref/awt/ch09_02.htm (4 of 10) [20/12/2001 11:09:13]
[Chapter 9] 9.2 Lists
public void setMultipleMode (boolean value) public void setMultipleSelections (boolean value) The setMultipleMode() method allows you to change the current state of a List from one selection mode to the other. The currently selected items change when this happens. If value is true and the List is going from single- to multiple-selection mode, the selected item gets deselected. If value is false and the List is going from multiple to single, the last item physically selected remains selected (the last item clicked on in the list, not the item with the highest index). If there was no selected item, the first item in the list becomes selected, or the last item that was deselected becomes selected. If staying within the same mode, setMultipleMode() has no effect on the selected items. setMultipleSelections() is the Java 1.0 name for this method. public void makeVisible (int index) The makeVisible() method ensures that the item at position index is displayed on the screen. This is useful if you want to make sure a certain entry is displayed when another action happens on the screen. public int getVisibleIndex () The getVisibleIndex() method returns the last index from a call to the method makeVisible(). If makeVisible() was never called, -1 is returned. Sizing public int getRows () The getRows() method returns the number of rows passed to the constructor of the List. It does not return the number of visible rows. To get a rough idea of the number of visible rows, compare the getSize() of the component with the results of getPreferredSize(getRows()). public Dimension getPreferredSize (int rows) public Dimension preferredSize (int rows) The getPreferredSize() method returns the preferable Dimension (width and height) for the size of a List with a height of rows. The rows specified may be different from the rows designated in the constructor. preferredSize() is the Java 1.0 name for this method. public Dimension getPreferredSize () public Dimension preferredSize () The getPreferredSize() method returns the Dimension (width and height) for the preferred size of the List. Without the rows parameter, this version of getPreferredSize() uses the constructor's number of rows to calculate the List's preferred size. preferredSize() is the Java 1.0 name for this method.
http://localhost/java/javaref/awt/ch09_02.htm (5 of 10) [20/12/2001 11:09:13]
[Chapter 9] 9.2 Lists
public Dimension getMiminumSize (int rows) public Dimension minimumSize (int rows) The getMinimumSize() method returns the minimum Dimension (width and height) for the size of a List with a height of rows. The rows specified may be different from the rows designated in the constructor. For a List, getMinimumSize() and getPreferredSize() should return the same dimensions. minimumSize() is the Java 1.0 name for this method. public Dimension getMiminumSize () public Dimension minimumSize () The getMinimumSize() method returns the minimum Dimension (width and height) for the size of the List. Without the rows parameter, this getMinimumSize() uses the constructor's number of rows to calculate the List's minimum size. minimumSize() is the Java 1.0 name for this method. Miscellaneous methods public synchronized void addNotify () The addNotify() method creates the List peer. If you override this method, call super.addNotify() first, then add your customizations for the new class. You will then be able to do everything you need with the information about the newly created peer. public synchronized void removeNotify () The removeNotify() method destroys the peer of the List and removes it from the screen. Prior to the List peer's destruction, the last selected entry is saved. If you override this method for a specific List, issue the particular commands that you need for your new object, then call super.removeNotify() last. protected String paramString () When you call the toString() method of List, the default toString() method of Component is called. This in turn calls paramString(), which builds up the string to display. At the List level, the currently selected item (getSelectedItem()) is appended to the output. Using Figure 9.2 as an example, the results would be the following: java.awt.List[0,34,107x54,selected=null]
List Events The primary event for a List occurs when the user selects an item in the list. With the 1.0 event model, double-clicking a selection causes an ACTION_EVENT and triggers the action() method, while single-clicking causes a LIST_SELECT or LIST_DESELECT event. Once the List has the input focus, it is possible to change the selection by using the arrow or keyboard keys. The arrow keys scroll through the list of choices, triggering the KEY_ACTION, LIST_SELECT, LIST_DESELECT, and http://localhost/java/javaref/awt/ch09_02.htm (6 of 10) [20/12/2001 11:09:13]
[Chapter 9] 9.2 Lists
KEY_ACTION_RELEASE events, and thus the keyDown(), handleEvent(), and keyUp() methods (no specific method gets called for LIST_SELECT and LIST_DESELECT). action() is called only when the user double-clicks on an item with the mouse. If the mouse is used to scroll through the list, no mouse events are triggered; ACTION_EVENT is generated only when the user double-clicks on an item. With the 1.1 event model, you register an ItemListener with addItemListener() or an ActionListener with the addActionListener() method. When the user selects the List, either the ItemListener.itemStateChanged() method or the ActionListener.actionPerformed() method is called through the protected List.processItemEvent() method or List.processActionEvent() method. Key, mouse, and focus listeners are registered through the three Component methods of addKeyListener(), addMouseListener(), and addFocusListener(), respectively. Action public boolean action (Event e, Object o) The action() method for a List is called when the user double-clicks on any item in the List. e is the Event instance for the specific event, while o is the label for the item selected, from the add() or addItem() call. If List is in multiple-selection mode, you might not wish to catch this event because it's not clear whether the user wanted to choose the item just selected or all of the items selected. You can solve this problem by putting a multi-selecting list next to a Button that the user presses when the selection process is finished. Capture the event generated by the Button. The following example shows how to set up and handle a list in this manner, with the display shown in Figure 9.3. In this example, I just print out the selections to prove that I captured them. import java.awt.*; import java.applet.*; public class list3 extends Applet { List l; public void init () { String fonts[]; fonts = Toolkit.getDefaultToolkit().getFontList(); l = new List(4, true); for (int i = 0; i < fonts.length; i++) { l.addItem (fonts[i]); } setLayout (new BorderLayout (10, 10)); add ("North", new Label ("Pick Font Set")); add ("Center", l); add ("South", new Button ("Submit")); resize (preferredSize()); validate(); } public boolean action (Event e, Object o) { if (e.target instanceof Button) { String chosen[] = l.getSelectedItems(); http://localhost/java/javaref/awt/ch09_02.htm (7 of 10) [20/12/2001 11:09:13]
[Chapter 9] 9.2 Lists
for (int i=0;i 0, addImpl() throws the run-time exception IllegalArgumentException. If a component is already within the ScrollPane, it is removed before comp is added. The constraints parameter is ignored. Scrolling methods public int getScrollbarDisplayPolicy() The getScrollbarDisplayPolicy() method retrieves the current display policy, as set by the constructor. You cannot change the policy once it has been set. The return value is one of the class constants: SCROLLBARS_AS_NEEDED, SCROLLBARS_ALWAYS, or SCROLLBARS_NEVER. public Dimension getViewportSize() The getViewportSize() method returns the current size of the ScrollPane, less any Insets, as a Dimension object. The size is given in pixels and has an initial value of 100 x 100. public int getHScrollbarHeight() The getHScrollbarHeight() method retrieves the height in pixels of a horizontal scrollbar. The value returned is without regard to the display policy; that is, you may be given a height even if the scrollbar is not displayed. This method may return 0 if the scrollbar's height cannot be calculated at this time (no peer) or if you are using the SCROLLBARS_NEVER display policy. The width of a horizontal scrollbar is just getViewportSize().width. public int getVScrollbarWidth() The getVScrollbarWidth() method retrieves the width in pixels of a vertical scrollbar. The value returned is without regard to the display policy; that is, you may be given a width even if the scrollbar is not displayed. This method may return 0 if the scrollbar's width cannot be calculated at this time (no peer) or if you are using the SCROLLBARS_NEVER display policy. The height of a vertical scrollbar is just getViewportSize().height. public Adjustable getHAdjustable() The getHAdjustable() method returns the adjustable object representing the horizontal scrollbar (or null if http://localhost/java/javaref/awt/ch11_04.htm (2 of 5) [20/12/2001 11:09:28]
[Chapter 11] 11.4 ScrollPane
it is not present). Through the methods of Adjustable, you can get the different settings of the scrollbar. The object that this method returns is an instance of the package private class ScrollPaneAdjustable, which implements the Adjustable interface. this class allows you to register listeners for the scrollpane's events and inquire about various properties of the pane's scrollbars. It does not let you set some scrollbar properties; the setMinimum(), setMaximum(), and setVisibleAmount() methods throw an AWTError when called. public Adjustable getVAdjustable() The getVAdjustable() method returns the adjustable object representing the vertical scrollbar (or null if it is not present). Through the methods of Adjustable, you can get the different settings of the scrollbar. The object that this method returns is an instance of the package private class ScrollPaneAdjustable, which implements the Adjustable interface. this class allows you to register listeners for the scrollpane's events and inquire about various properties of the pane's scrollbars. It does not let you set some scrollbar properties; the setMinimum(), setMaximum(), and setVisibleAmount() methods throw an AWTError when called. public void setScrollPosition(int x, int y) This setScrollPosition() method moves the ScrollPane to the designated location if possible. The x and y arguments are scrollbar settings, which should be interpreted in terms of the minimum and maximum values given to you by the horizontal and vertical Adjustable objects (returned by the previous two methods). If the ScrollPane does not have a child component, this method throws the run-time exception NullPointerException. You can also move the ScrollPane by calling the Adjustable.setValue() method of one of the scrollpane's Adjustable objects. public void setScrollPosition(Point p) This setScrollPosition() method calls the previous with parameters of p.x, and p.y. public Point getScrollPosition() The getScrollPosition() method returns the current position of both the scrollpane's Adjustable objects as a Point. If there is no component within the ScrollPane, getScrollPosition() throws the NullPointerException run-time exception. Another way to get this information is by calling the Adjustable.getValue() method of each Adjustable object. Miscellaneous methods public void printComponents (Graphics g) The printComponents() method of ScrollPane prints the single component it contains. This is done by clipping the context g to the size of the display area and calling the contained component's printAll() method. public synchronized void addNotify () The addNotify() method creates the ScrollPane peer. If you override this method, call super.addNotify() first, then add your customizations for the new class. You will then be able to do everything you need with the information about the newly created peer. protected String paramString () ScrollPane doesn't have its own toString() method; so when you call the toString() method of a ScrollPane, you are actually calling the Component.toString() method. This in turn calls paramString(), which builds the string to display. For a ScrollPane, paramString() adds the current scroll position, insets, and scrollbar display policy. For example:
http://localhost/java/javaref/awt/ch11_04.htm (3 of 5) [20/12/2001 11:09:28]
[Chapter 11] 11.4 ScrollPane
java.awt.ScrollPane[scrollpane0,0,0,0x0,invalid,ScrollPosition=(0,0), Insets=(0,0,0,0),ScrollbarDisplayPolicy=always]
ScrollPane Events The ScrollPane peer deals with the scrolling events for you. It is not necessary to catch or listen for these events. As with any other Container, you can handle the 1.0 events of the object you contain or listen for 1.1 events that happen within you.
Using a ScrollPane The following applet demonstrates one way to use a ScrollPane. Basically, you place the object you want to scroll in the ScrollPane by calling the add() method. This can be a Panel with many objects on it or a Canvas with an image drawn on it. You then add as many objects as you want to the Panel or scribble on the Canvas to your heart's delight. No scrolling event handling is necessary. That is all there is to it. To make this example a little more interesting, whenever you select a button, the ScrollPane scrolls to a randomly selected position. Figure 11.4 displays the screen. Figure 11.4: A ScrollPane containing many buttons
Here's the code: // Java 1.1 only import java.awt.*; import java.awt.event.*; import java.applet.*; public class scroll extends Applet implements ActionListener, ContainerListener { ScrollPane sp = new ScrollPane (ScrollPane.SCROLLBARS_ALWAYS); public void init () { setLayout (new BorderLayout ()); Panel p = new Panel(new GridLayout (7, 8)); p.addContainerListener (this); for (int j=0;j 255)) { throw (new AWTException ("Invalid Colors " + maxColors)); } store = new int[height][width]; if (raw) { // binary format (raw) pixel data byte row[] = new byte [width*3]; for (int i=0;ix`, where the width and height are taken from the constructor. After updating properties, this method sets the properties list of the consumer. public void setDimensions (int width, int height) The setDimensions() method of ReplicateScaleFilter passes the new width and height from the constructor along to the consumer. If either of the constructor's parameters are negative, the size is recalculated proportionally. If both are negative, the size becomes width x height. public void setPixels (int x, int y, int w, int h, ColorModel model, int pixels[], int offset, int scansize) public void setPixels (int x, int y, int w, int h, ColorModel model, byte pixels[], int offset, int scansize) The setPixels() method of ReplicateScaleFilter checks to see which rows and columns of pixels to pass along.
AreaAveragingScaleFilter The AreaAveragingScaleFilter subclasses ReplicateScaleFilter to provide a better scaling algorithm. Instead of just dropping or adding rows and columns, AreaAveragingScaleFilter tries to blend pixel values when creating new rows and columns. The filter works by replicating rows and columns to generate an image that is a multiple of the original size. Then the image is resized back down by an algorithm that blends the pixels around each destination pixel. AreaAveragingScaleFilter methods Because this filter subclasses ReplicateScaleFilter, the only methods it includes are those that override methods of ReplicateScaleFilter. Constructors public AreaAveragingScaleFilter (int width, int height) The constructor for AreaAveragingScaleFilter specifies the size of the resulting image. If either parameter is -1, the resulting image maintains the same aspect ratio as the original image. ImageConsumer interface methods public void setHints (int hints) The setHints() method of AreaAveragingScaleFilter checks to see if some optimizations can be performed based upon the value of the hints parameter. If they can't, the image filter has to cache the pixel data until it receives the entire image. public void setPixels (int x, int y, int w, int h, ColorModel model, byte pixels[], int offset, int scansize) public void setPixels (int x, int y, int w, int h, ColorModel model, int pixels[], int offset, int scansize) The setPixels() method of AreaAveragingScaleFilter accumulates the pixels or passes them along based upon the available hints. If setPixels() accumulates the pixels, this filter passes them along to the consumer when appropriate.
Cascading Filters It is often a good idea to perform complex filtering operations by using several filters in a chain. This technique requires the system to perform several passes through the image array, so it may be slower than using a single complex filter; however, cascading filters yield code that is easier to understand and quicker to write--particularly if
http://localhost/java/javaref/awt/ch12_05.htm (13 of 15) [20/12/2001 11:09:44]
[Chapter 12] 12.5 ImageFilter
you already have a collection of image filters from other projects. For example, assume you want to make a color image transparent and then render the image in black and white. The easy way to do this task is to apply a filter that converts color to a gray value and then apply the TransparentImageFilter we developed in Example 12.9. Using this strategy, we have to develop only one very simple filter. Example 12.11 shows the source for the GrayImageFilter; Example 12.12 shows the applet that applies the two filters in a daisy chain. Example 12.11: GrayImageFilter Source import java.awt.image.*; public class GrayImageFilter extends RGBImageFilter { public GrayImageFilter () { canFilterIndexColorModel = true; } public int filterRGB (int x, int y, int rgb) { int gray = (((rgb & 0xff0000) >> 16) + ((rgb & 0x00ff00) >> 8) + (rgb & 0x0000ff)) / 3; return (0xff000000 | (gray tag. getApplet() returns null if the applet does not exist in the current context. This method allows you to call methods of other applets within the same context, loaded by the same ClassLoader. For example: MyApplet who = (MyApplet)getAppletContext().getApplet("hey"); who.method(); TIP: Netscape Navigator 3.0 restricts which applets can communicate with each other. Internet Explorer seems to have a similar restriction. For applets to communicate, they must: ❍ Have the same CODEBASE.
http://localhost/java/javaref/awt/ch14_03.htm (1 of 3) [20/12/2001 11:09:47]
[Chapter 14] 14.3 AppletContext Interface
❍ ❍
Have the same or no ARCHIVES tag. Have MAYSCRIPT tags and appear in the same frame; alternatively, neither applet may have a MAYSCRIPT tag.
If these conditions are not met and you try to cast the return value of getApplet() or getApplets() to the appropriate class, either the cast will throw a ClassCastException; or nothing will happen, and the method will not continue beyond the point of the failure. public abstract Enumeration getApplets () The getApplets() method gathers all the Applets in the current context, loaded by the same ClassLoader, into a collection and returns the Enumeration. You can then cycle through them to perform some operation collectively. For example: Enumeration e = getAppletContext().getApplets(); while (e.hasMoreElements()) { Object o = e.nextElement(); if (o instance of MyApplet) { MyApplet a = (Object)o; a.MyAppletMethod(); } } TIP: If you want communication between applets on one page, be aware that there is no guarantee which applet will start first. Communications must be synchronized by using a controlling class or continual polling. public abstract void showDocument (URL url) The showDocument() method shows url in the current browser window. The browser may ignore the request if it so desires. public abstract void showDocument (URL url, String frame) The showDocument() method shows url in a browser window specified by frame. Different frame values and the results are shown in Table 14.1. The browser may ignore the request, as appletviewer does. try { URL u = new URL (getDocumentBase(), (String) file); getAppletContext().showDocument (u, "_blank"); } catch (Exception e) { } Table 14.1: Target Values Target String Results _blank
Show url new browser window with no name.
http://localhost/java/javaref/awt/ch14_03.htm (2 of 3) [20/12/2001 11:09:47]
[Chapter 14] 14.3 AppletContext Interface
_parent
Show url in the parent frame of the current window.
_self
Replace current url with url (i.e., display in the current window).
_top
Show url in top-most frame.
name
Show url in new browser window named name.
public abstract void showStatus (String message) The showStatus() method displays message on the browser's status line, if it has one. How to display this string is up to the browser, and the browser can overwrite it whenever it wants. You should use showStatus() only for messages that the user can afford to miss.
AudioClip Interface
http://localhost/java/javaref/awt/ch14_03.htm (3 of 3) [20/12/2001 11:09:47]
AppletStub Interface
[Chapter 14] 14.4 AppletStub Interface
Chapter 14 And Then There Were Applets
14.4 AppletStub Interface The AppletStub interface provides a way to get information from the run-time browser environment. The Applet class provides methods with similar names that call these methods. Methods public abstract boolean isActive () The isActive() method returns the current state of the applet. While an applet is initializing, it is not active, and calls to isActive() return false. The system marks the applet active just prior to calling start(); after this point, calls to isActive() return true. public abstract URL getDocumentBase () The getDocumentBase() method returns the complete URL of the HTML file that loaded the applet. This method can be used with the getImage() or getAudioClip() methods to load an image or audio file relative to the HTML file. public abstract URL getCodeBase () The getCodeBase() method returns the complete URL of the .class file that contains the applet. This method can be used with the getImage() method or the getAudioClip() method to load an image or audio file relative to the .class file. public abstract String getParameter (String name) The getParameter() method allows you to get parameters from tags within the <APPLET> tag of the HTML file that loaded the applet. The name parameter of getParameter() must match the name string of the tag; name is case insensitive. The return value of getParameter() is the value associated with name; it is always a String regardless of the type of data in the tag. If name is not found within the tags of the <APPLET>, getParameter() returns null. public abstract AppletContext getAppletContext () The getAppletContext() method returns the current AppletContext of the applet. This is part of the stub that is set by the system when setStub() is called. public abstract void appletResize (int width, int height) The appletResize() method is called by the resize method of the Applet class. The method changes the size of the applet space to width x height. The browser must support changing the
http://localhost/java/javaref/awt/ch14_04.htm (1 of 2) [20/12/2001 11:09:48]
[Chapter 14] 14.4 AppletStub Interface
applet space; if it doesn't, the size remains unchanged.
AppletContext Interface
http://localhost/java/javaref/awt/ch14_04.htm (2 of 2) [20/12/2001 11:09:48]
Audio in Applications
[Chapter 14] 14.5 Audio in Applications
Chapter 14 And Then There Were Applets
14.5 Audio in Applications The rest of this chapter describes how to use audio in your applications. Because the audio support discussed so far has been provided by the browser, applications that don't run in the context of a browser must use a different set of classes to work with audio. These classes are within the sun.audio package. Although the sun.* package hierarchy is not necessarily included by other vendors, the sun.audio classes discussed here are provided with Netscape Navigator 2.0/3.0 and Internet Explorer 3.0. Therefore, you can use these classes within applets, too. This section ends by developing a SunAudioClip class that has an interface similar to the applet's audio interface; you can use it to minimize coding differences between applets and applications.
AudioData The AudioData class holds a clip of 8000 Hz µLaw audio data. This data can be used to construct an AudioDataStream or ContinuousAudioDataStream, which can then be played with the AudioPlayer. Constructor public AudioData (byte buffer[]) The AudioData constructor accepts a byte array buffer and creates an instance of AudioData. The buffer should contain 8000 Hz µLaw audio data. Methods There are no methods for AudioData.
AudioStream AudioStream subclasses FilterInputStream, which extends InputStream. Using an InputStream lets you move back and forth (rewind and fast forward) within an audio file, in addition to playing the audio data from start to finish. Constructors public AudioStream (InputStream in) throws IOException The AudioStream constructor has InputStream in as its parameter and can throw IOException on error. In the following code, we get an input stream by opening a .au file. Another common way to construct an AudioStream is to use the stream associated with a URL through the URL's openStream() method. FileInputStream fis = new FileInputStream ("/usr/openwin/demo/sounds/1.au"); AudioStream audiostream = new AudioStream (fis); or: AudioStream audiostream = new AudioStream (savedUrl.openStream());
http://localhost/java/javaref/awt/ch14_05.htm (1 of 5) [20/12/2001 11:09:50]
[Chapter 14] 14.5 Audio in Applications
If you are constructing the audio data yourself, you would use a ByteArrayInputStream. Whatever the source of the data, the input stream should provide data in Sun's .au format. Methods public int read (byte buffer[], int offset, int length) throws IOException The read() method for AudioStream reads an array of bytes into buffer. offset is the first element of buffer that is used. length is the maximum number of bytes to read. This method blocks until some input is available. read() returns the actual number of bytes read. If the end of stream is encountered and no bytes were read, read() returns -1. Ordinarily, you read() an AudioStream only if you want to modify the audio data in some way. public int getLength() The getLength() method returns the length of the audio data contained within the AudioStream, excluding any header information in the file. public AudioData getData () throws IOException The getData() method of AudioStream is the most important and most frequently used. It reads the data from the input stream and creates an AudioData instance. As the following code shows, you can create an AudioStream and get the AudioData with one statement. AudioData audiodata = new AudioStream (aUrl.openStream()).getData();
AudioDataStream Constructors public AudioDataStream (AudioData data) This constructor creates an AudioDataStream from an AudioData object data. The resulting AudioDataStream is a subclass of ByteArrayInputStream and can be played by the AudioPlayer.start() method. Methods There are no methods for AudioDataStream.
ContinuousAudioDataStream Constructors public ContinuousAudioDataStream (AudioData data) This constructor creates a continuous stream of audio from data. The resulting ContinuousAudioDataStream is a subclass of AudioDataStream and, therefore, of ByteArrayInputStream. It can be played by AudioPlayer.start(); whenever the player reaches the end of the continuous audio data stream, it restarts from the beginning. Methods public int read () This read() method of ContinuousAudioDataStream overrides the read() method in ByteArrayInputStream to rewind back to the beginning of the stream when end-of-file is reached. This method is used by the system when it reads the InputStream; it is rarely called directly. read() never returns -1 since it loops back to the beginning on end-of-file. public int read (byte buffer[], int offset, int length)
http://localhost/java/javaref/awt/ch14_05.htm (2 of 5) [20/12/2001 11:09:50]
[Chapter 14] 14.5 Audio in Applications
This read() method of ContinuousAudioDataStream overrides the read() method in ByteArrayInputStream to rewind back to the beginning of the stream when end-of-file is reached. This method is used by the system when it reads the InputStream; it is rarely called directly. read() returns the actual number of bytes read. read() never returns -1 since it loops back to the beginning on end-of-file.
AudioStreamSequence Constructors public AudioStreamSequence (Enumeration e) The constructor for AudioStreamSequence accepts an Enumeration e(normally the elements of a Vector of AudioStreams) as its sole parameter. The constructor converts the sequence of audio streams into a single stream to be played in order. An example follows: Vector v = new Vector (); v.addElement (new AudioStream (url1.openStream ()); v.addElement (new AudioStream (url2.openStream ()); AudioStreamSequence audiostream = new AudioStreamSequence (v.elements ()); Methods public int read () This read() method of AudioStreamSequence overrides the read() method in InputStream to start the next stream when end-of-file is reached. This method is used by the system when it reads the InputStream and is rarely called directly. If the end of all streams is encountered and no bytes were read, read() returns -1. Otherwise, read() returns the character read. public int read (byte buffer[], int offset, int length) This read() method of AudioStreamSequence overrides the read() method in InputStream to start the next stream when end-of-file is reached. This method is used by the system when it reads the InputStream and is rarely called directly. read() returns the actual number of bytes read. If the end of all streams is encountered and no bytes were read, read() returns -1.
AudioPlayer The AudioPlayer class is the workhorse of the sun.audio package. It is used to play all the streams that were created with the other classes. There is no constructor for AudioPlayer; it just extends Thread and provides start() and stop() methods. Variable public final static AudioPlayer player player is the default audio player. This audio player is initialized automatically when the class is loaded; you do not have to initialize it (in fact, you can't because it is final) or call the constructor yourself. Methods public synchronized void start (InputStream in) The start() method starts a thread that plays the InputStream in. Stream in continues to play until there is no more data or it is stopped. If in is a ContinuousAudioDataStream, the playing continues until stop() (described next) is called. public synchronized void stop (InputStream in) The stop() method stops the player from playing InputStream in. Nothing happens if the stream in is no longer playing or was never started.
http://localhost/java/javaref/awt/ch14_05.htm (3 of 5) [20/12/2001 11:09:50]
[Chapter 14] 14.5 Audio in Applications
SunAudioClip Class Definition The class in Example 14.3 is all you need to play audio files in applications. It implements the java.applet.AudioClip interface, so the methods and functionality will be familiar. The test program in main() demonstrates how to use the class. Although the class itself can be used in applets, provided your users have the sun.audio package available, it is geared towards application users. Example 14.3: The SunAudioClip Class import java.net.URL; import java.io.FileInputStream; import sun.audio.*; public class SunAudioClip implements java.applet.AudioClip { private AudioData audiodata; private AudioDataStream audiostream; private ContinuousAudioDataStream continuousaudiostream; static int length; public SunAudioClip (URL url) throws java.io.IOException { audiodata = new AudioStream (url.openStream()).getData(); audiostream = null; continuousaudiostream = null; } public SunAudioClip (String filename) throws java.io.IOException { FileInputStream fis = new FileInputStream (filename); AudioStream audioStream = new AudioStream (fis); audiodata = audioStream.getData(); audiostream = null; continuousaudiostream = null; } public void play () { audiostream = new AudioDataStream (audiodata); AudioPlayer.player.start (audiostream); } public void loop () { continuousaudiostream = new ContinuousAudioDataStream (audiodata); AudioPlayer.player.start (continuousaudiostream); } public void stop () { if (audiostream != null) AudioPlayer.player.stop (audiostream); if (continuousaudiostream != null) AudioPlayer.player.stop (continuousaudiostream); } public static void main (String args[]) throws Exception { URL url1 = new URL ("http://localhost:8080/audio/1.au"); URL url2 = new URL ("http://localhost:8080/audio/2.au"); SunAudioClip sac1 = new SunAudioClip (url1); SunAudioClip sac2 = new SunAudioClip (url2); SunAudioClip sac3 = new SunAudioClip ("1.au"); sac1.play (); sac2.loop (); http://localhost/java/javaref/awt/ch14_05.htm (4 of 5) [20/12/2001 11:09:50]
[Chapter 14] 14.5 Audio in Applications
sac3.play (); try {// Delay for loop Thread.sleep (2000); } catch (InterruptedException ie) {} sac2.stop(); } }
AppletStub Interface
http://localhost/java/javaref/awt/ch14_05.htm (5 of 5) [20/12/2001 11:09:50]
Toolkit and Peers
[Chapter 15] 15.2 The Peer Interfaces
Chapter 15 Toolkit and Peers
15.2 The Peer Interfaces Each GUI component that AWT provides has a peer. The peer is the implementation of that component in the native environment. For example, the Choice component in AWT corresponds to some native object that lets the user select one or more items from a list. As a Java developer, you need to worry only about the interface of the Choice object; when someone runs your program, the Choice object is mapped to an appropriate native object, which is the Choice peer, that "does the right thing." You don't really care what the peer is or how it's implemented; in fact, the peer may look (and to some extent, behave) differently on each platform. The glue that allows an AWT component and its peer to work together is called a peer interface. A peer interface is simply an interface that defines the methods that the peer is required to support. These interfaces are collected in the package java.awt.peer. For example, this package contains the ButtonPeer interface, which contains the single method setLabel(). This means that the native object used to implement a Button must contain a method called setLabel() in order for AWT to use it as a button peer. (It's not quite that simple; since a button is also a Component, the button's peer must also implement the ComponentPeer interface, which is much more complicated.) With one exception, there is a one-to-one correspondence between Component classes and peer interfaces: a Window has a WindowPeer, a Checkbox has a CheckboxPeer, and so on. The one exception is a new peer interface that appears in Java 1.1: the LightweightPeer, which doesn't have a corresponding component. The LightweightPeer is used by components that exist purely in Java, don't have a native peer, and are displayed and managed by another container. LightweightPeer makes it easier to create new components or containers that can behave like other components, but don't subclass Canvas or Panel and don't correspond to anything in the native environment. The best usage I can think of is to subclass Container to create a lightweight Panel. If you are only using a Panel to manage layout, there is no need for a peer to be created to process events. This should result in substantial resource savings where multiple panels need to be created just to help with layout. The following code is all you need to create a LightWeightPanel: import java.awt.*; public class LightWeightPanel extends Container { } There also tends to be a one-to-one relationship between the peer methods and the methods of the Java
http://localhost/java/javaref/awt/ch15_02.htm (1 of 4) [20/12/2001 11:09:52]
[Chapter 15] 15.2 The Peer Interfaces
component. That is, each method in the peer interface corresponds to a method of the component. However, although a peer must implement each method in its peer interface, it doesn't necessarily have to do anything in that method. It's entirely possible for a platform to have a native button object that doesn't let you set the label. In this case, the button peer would implement the setLabel() method required by the ButtonPeer interface, but it wouldn't do anything. Of course, the component may also have many methods that don't correspond to the peer methods. Methods that don't correspond to anything in the peer are handled entirely within Java. The ComponentPeer interface is the parent of all non-menu objects in the peer package. The MenuComponentPeer is the parent of all menu objects. The trees mirror the regular object hierarchies. Figure 15.1 shows the object hierarchy diagram. Figure 15.1: java.awt.peer object hierarchy
Creating a Java component (e.g., Button b = new Button (`Foo`)) does not create the peer. An object's peer is created when the object's addNotify() method is called. This is usually when the component's container is added to the screen. The call to a component's addNotify() method in turn calls the appropriate createxxxx() method of the Toolkit (for a Button, createButton()). Figure 15.2 shows the process. Figure 15.2: Creating a Button peer
http://localhost/java/javaref/awt/ch15_02.htm (2 of 4) [20/12/2001 11:09:52]
[Chapter 15] 15.2 The Peer Interfaces
When you remove a component from a container by calling remove(), the container calls the component's removeNotify() method. This usually results in a call to the peer's dispose() method. Depending on the particular component, removeNotify() may be overridden to perform additional work. Removing a Component from a Container does not destroy the Component. The next time the method addNotify() is called, the component must be recreated by the peer, with its previous characteristics. For instance, when a TextField is removed, the current text, plus the start and stop points for the current selection, are saved. These will be restored if you add the text field to its container again. For some components, like a Label, there is no need to retain any additional information. A component's peer needs to exist only when the user is interacting with it. If you are developing resource-intensive programs, you might want to consider drawing the components manually when they do not have the focus and using the peer only when they actually have input focus. This technique can save a considerable amount of memory resources but requires extra work on your part as a developer and goes beyond the scope of this book. The LightweightPeer interface appears to be designed to make this process easier: you could create a dummy button that doesn't do anything and uses the LightweightPeer. Whenever the mouse enters the button's space, you could quickly remove the http://localhost/java/javaref/awt/ch15_02.htm (3 of 4) [20/12/2001 11:09:52]
[Chapter 15] 15.2 The Peer Interfaces
dummy button and add a real button. The peer interfaces are listed in their entirety in the reference section. We won't list them here, primarily because you don't need to worry about them unless you're porting Java to a new platform. Each method in a peer interface corresponds exactly to the similarly named method in the matching component. LightweightPeer is the only exception, because it doesn't have a matching component, but that's easy to take care of: as you'd expect, LightweightPeer doesn't define any methods. (Of course, a peer that implements LightweightPeer would still need to implement the methods inherited from ComponentPeer, but those are inherited when you subclass Component.)
Toolkit
http://localhost/java/javaref/awt/ch15_02.htm (4 of 4) [20/12/2001 11:09:52]
Data Transfer
[Chapter 16] 16.2 Transferable Interface
Chapter 16 Data Transfer
16.2 Transferable Interface Objects that can be placed on a clipboard must implement the Transferable interface. This interface defines a number of methods that let an object describe how it presents itself to clipboard readers. That sounds complex, but it isn't really; these methods let a clipboard reader find out what data flavors are available and what Java types they represent. The significance of the Transferable interface is that it provides a way to get information about the object on the clipboard without knowing what the object actually is. When you read the clipboard, you don't necessarily know what kind of object is there. It might be some kind of text string, but it could just as likely be something bizarre. However, you shouldn't have to care. If you're looking for a String, you care only that the object exists in a stringFlavor representation. These methods let you ask the object what flavors it supports. For text strings, the data transfer package provides a StringSelection class that implements Transferable. At this point, if you want to transfer other kinds of objects, you'll have to create a class that implements Transferable yourself. It wouldn't be unreasonable for JavaSoft to provide other "selection" classes (for example, ImageSelection) in the future. Methods public abstract DataFlavor[] getTransferDataFlavors() The getTransferDataFlavors() method should return a sorted array of DataFlavors that you support. The most descriptive flavor should be the first element in the array and the least descriptive, last. For example, a textual object would place DataFlavor.plainTextFlavor last, because it has less information than DataFlavor.stringFlavor (which includes information like the length of the string) and much less information than a hypothetical flavor like DataFlavor.richTextFlavor. public abstract boolean isDataFlavorSupported(DataFlavor flavor) The isDataFlavorSupported() method should return true if the object supports the given flavor and false otherwise. public abstract Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException The getTransferData() method is the most complicated to implement. It should return an instance of the class representing the data in the given flavor. If flavor is not supported by http://localhost/java/javaref/awt/ch16_02.htm (1 of 2) [20/12/2001 11:09:52]
[Chapter 16] 16.2 Transferable Interface
this object, getTransferData() must throw the UnsupportedFlavorException. However, this method must be able to return a class for each flavor the object supports (i.e., each data flavor listed by getTransferDataFlavors()). The method could throw an IOException when returning with a Reader as the representation class. For example, if some data flavor required you to return a FileReader and the file doesn't exist, this method might throw an IOException.
DataFlavor
http://localhost/java/javaref/awt/ch16_02.htm (2 of 2) [20/12/2001 11:09:52]
ClipboardOwner Interface
[Chapter 16] 16.3 ClipboardOwner Interface
Chapter 16 Data Transfer
16.3 ClipboardOwner Interface Classes that need to place objects on a clipboard must implement the ClipboardOwner interface. An object becomes the clipboard owner by placing something on a Clipboard and remains owner as long as that object stays on the clipboard; it loses ownership when someone else writes to the clipboard. The ClipboardOwner interface provides a way to receive notification when you lose ownership--that is, when the object you placed on the clipboard is replaced by something else. Methods public abstract void lostOwnership(Clipboard clipboard, Transferable contents) The lostOwnership() method tells the owner of contents that it is no longer on the given clipboard. It is usually implemented as an empty stub but is available for situations in which you have to know.
Transferable Interface
http://localhost/java/javaref/awt/ch16_03.htm [20/12/2001 11:09:53]
Clipboard
[Chapter 16] 16.4 Clipboard
Chapter 16 Data Transfer
16.4 Clipboard The Clipboard class is a repository for a Transferable object and can be used for cut, copy, and paste operations. You can work with a private clipboard by creating your own instance of Clipboard, or you can work with the system clipboard by asking the Toolkit for it: Toolkit.getDefaultToolkit().getSystemClipboard() When working with the system clipboard, native applications have access to information created within Java programs and vice versa. Access to the system clipboard is controlled by the SecurityManager and is restricted within applets.
Clipboard Methods Variables protected ClipboardOwner owner The owner instance variable represents the current owner of contents. When something new is placed on the clipboard, the previous owner is notified by a call to the lostOwnership() method. The owner usually ignores this notification. However, the clipboard's contents are passed back to owner in case some special processing or comparison needs to be done. protected Transferable contents The contents instance variable is the object currently on the clipboard; it was placed on the clipboard by owner. To retrieve the current contents, use the getContents() method. Constructors public Clipboard(String name) The constructor for Clipboard allows you to create a private clipboard named name. This clipboard is not accessible outside of your program and has no security constraints placed upon it. Miscellaneous methods public String getName()
http://localhost/java/javaref/awt/ch16_04.htm (1 of 2) [20/12/2001 11:09:53]
[Chapter 16] 16.4 Clipboard
The getName() method fetches the clipboard's name. For private clipboards, this is the name given in the constructor. The name of the system clipboard is "System". public synchronized Transferable getContents(Object requester) The getContents() method allows you to retrieve the current contents of the clipboard. This is the method you would call when the user selects Paste from a menu. Once you have the Transferable data, you try to get the data in whatever flavor you want by calling the Transferable.getTransferData() method, possibly after calling Transferable.isDataFlavorSupported(). The requester represents the object that is requesting the clipboard's contents; it is usually just this, since the current object is making the request. public synchronized void setContents(Transferable contents, ClipboardOwner owner) The setContents() method changes the contents of the clipboard to contents and changes the clipboard's owner to owner. You would call this method when the user selects Cut or Copy from a menu. The owner parameter represents the object that owns contents. This object must implement the ClipboardOwner interface; it will be notified by a call to lostOwnership() when something else is placed on the clipboard.
ClipboardOwner Interface
http://localhost/java/javaref/awt/ch16_04.htm (2 of 2) [20/12/2001 11:09:53]
StringSelection
[Chapter 16] 16.5 StringSelection
Chapter 16 Data Transfer
16.5 StringSelection StringSelection is a convenience class that can be used for copy and paste operations on Unicode text strings (String). It implements both the ClipboardOwner and Transferable interfaces, so it can be used both as the contents of the clipboard and as its owner. For example, if s is a StringSelection, you can call Clipboard.setContents(s,s). StringSelection supports both stringFlavor and plainTextFlavor and doesn't do anything when it loses clipboard ownership.
StringSelection Methods Constructors public StringSelection(String data) The constructor creates an instance of StringSelection containing data. You can use this object to place the data on a clipboard. Miscellaneous methods public DataFlavor[] getTransferDataFlavors() The getTransferDataFlavors() method returns a two-element DataFlavor array consisting of DataFlavor.stringFlavor and DataFlavor.plainTextFlavor. This means that you can paste a StringSelection as either a Java String or as plain text (i.e., the MIME type plain/text). public boolean isDataFlavorSupported(DataFlavor flavor) The isDataFlavorSupported() method is returns true if flavor is either DataFlavor.stringFlavor or DataFlavor.plainTextFlavor; it returns false for any other flavor. public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException The getTransferData() method returns an object from which you can get the data on the clipboard; the object's type is determined by the flavor parameter. This method returns a String containing the data on the clipboard if flavor is DataFlavor.stringFlavor; it http://localhost/java/javaref/awt/ch16_05.htm (1 of 2) [20/12/2001 11:09:54]
[Chapter 16] 16.5 StringSelection
returns a StringBufferInputStream from which you can read the data on the clipboard if you ask for DataFlavor.plainTextFlavor. Otherwise, getTransferData() throws an UnsupportedFlavorException. public void lostOwnership(Clipboard clipboard, Transferable contents) The lostOwnership() method of StringSelection is an empty stub; it does nothing when you lose ownership. If you want to know when you've lost ownership of string data placed on the clipboard, write a subclass of StringSelection and override this method.
Clipboard
http://localhost/java/javaref/awt/ch16_05.htm (2 of 2) [20/12/2001 11:09:54]
UnsupportedFlavorException
[Chapter 16] 16.6 UnsupportedFlavorException
Chapter 16 Data Transfer
16.6 UnsupportedFlavorException The UnsupportedFlavorException exception is thrown when you ask Transferable.getTransferData() to give you data in a flavor that isn't supported by the object on the clipboard. For example, if the clipboard currently holds an image and you ask for the data in the stringFlavor, you will almost certainly get an UnsupportedFlavorException because it is unlikely that an image object will be able to give you its data as a String. You can either ignore the exception or display an appropriate message to the user.
UnsupportedFlavorException Method Constructor public UnsupportedFlavorException (DataFlavor flavor) The sole constructor creates an UnsupportedFlavorException with a detail message containing the human presentable name of flavor. To retrieve this message, call getMessage(), which this exception inherits from the Exception superclass (and which is required by the Throwable interface).
StringSelection
http://localhost/java/javaref/awt/ch16_06.htm [20/12/2001 11:09:55]
Reading and Writing the Clipboard
[Chapter 16] 16.7 Reading and Writing the Clipboard
Chapter 16 Data Transfer
16.7 Reading and Writing the Clipboard Now that you know about the different java.awt.datatransfer classes required to use the clipboard, let's put them all together in an example. Example 16.1 creates a TextField for input (copying), a read-only TextArea for output (pasting), and a couple of buttons to control its operation. Figure 16.1 shows the program's user interface. When the user clicks on the Copy button or presses Return in the TextField, the text in the TextField is copied to the Clipboard. When the user clicks on the Paste button, the contents of the clipboard are drawn in the TextArea. Since the clipboard is not private, you can copy or paste from anywhere on your desktop, not just this program. Example 16.1: Using the System Clipboard // Java 1.1 only import java.io.*; import java.awt.*; import java.awt.datatransfer.*; public class ClipMe extends Frame { TextField tf; TextArea ta; Button copy, paste; Clipboard clipboard = null; ClipMe() { super ("Clipping Example"); add (tf = new TextField("Welcome"), "North"); add (ta = new TextArea(), "Center"); ta.setEditable(false); Panel p = new Panel(); p.add (copy = new Button ("Copy")); p.add (paste = new Button ("Paste")); add (p, "South"); setSize (250, 250); } public static void main (String args[]) {
http://localhost/java/javaref/awt/ch16_07.htm (1 of 3) [20/12/2001 11:09:56]
[Chapter 16] 16.7 Reading and Writing the Clipboard
new ClipMe().show(); } public boolean handleEvent (Event e) { if (e.id == Event.WINDOW_DESTROY) { System.exit(0); return true; // never gets here } return super.handleEvent (e); } public boolean action (Event e, Object o) { if (clipboard == null) clipboard = getToolkit().getSystemClipboard(); if ((e.target == tf) || (e.target == copy)) { StringSelection data; data = new StringSelection (tf.getText()); clipboard.setContents (data, data); } else if (e.target == paste) { Transferable clipData = clipboard.getContents(this); String s; try { s = (String)(clipData.getTransferData( DataFlavor.stringFlavor)); } catch (Exception ee) { s = ee.toString(); } ta.setText(s); } return true; } } Figure 16.1: Using the system clipboard
http://localhost/java/javaref/awt/ch16_07.htm (2 of 3) [20/12/2001 11:09:56]
[Chapter 16] 16.7 Reading and Writing the Clipboard
We won't say anything about how the display is set up; that should be familiar. All the interesting stuff happens in the action method, which is called in response to a button click. We check which button the user clicked; if the user clicked the Copy button, we read the text field tf and use it to create a new StringSelection named data. If the user clicked the Paste button, we retrieve the data from the clipboard by calling getContents(). This gives us an object about which (strictly speaking) we know nothing, except that it implements Transferable. In this case, we're pretty sure that we're getting text from the clipboard, so we call getTransferData() and ask for the data in the stringFlavor form. We catch the exception that might occur if we're wrong about the data flavor. This program has no way of placing anything but text on the clipboard, but there's no guarantee that the user didn't cut some other kind of object from a native application. Once we have our String, we call the setText() method of the TextArea to tell it about the new string, and we are finished.
UnsupportedFlavorException
http://localhost/java/javaref/awt/ch16_07.htm (3 of 3) [20/12/2001 11:09:56]
Printing
[Chapter 17] 17.2 PrintJob Class
Chapter 17 Printing
17.2 PrintJob Class The abstract PrintJob class provides the basis for the platform-specific printing subclasses. Through PrintJob, you have access to properties like page size and resolution.
Constructor and Pseudo-Constructor public PrintJob () The PrintJob() constructor is public; however, the class is abstract, so you would never create a PrintJob instance directly. Since you can't call the PrintJob constructor directly, you need some other way of getting a print job to work with. The proper way to get an instance of PrintJob is to ask the Toolkit, which is described in Chapter 15, Toolkit and Peers. The getPrintJob() method requires a Frame as the first parameter, a String as the second parameter, and a Properties set as the third parameter. Here's how you might call it: PrintJob pjob = getToolkit().getPrintJob(aFrame, "Job Title", (Properties)null); The Frame is used to hold a print dialog box, asking the user to confirm or cancel the print job. (Whether or not you get the print dialog may be platform specific, but your programs should always assume that the dialog may appear.) The String is the job's title; it will be used to identify the job in the print queue and on the job's header page, if there is one. The Properties parameter is used to request printing options, like page reversal. The property names, and whether the requested properties are honored at all, are platform specific. UNIX systems use the following properties: awt.print.printer awt.print.paperSize awt.print.destination awt.print.orientation awt.print.options awt.print.fileName http://localhost/java/javaref/awt/ch17_02.htm (1 of 3) [20/12/2001 11:09:57]
[Chapter 17] 17.2 PrintJob Class
awt.print.numCopies Windows NT/95 ignores the properties sheet. If the properties sheet is null, as in the previous example, you get the system's default printing options. If the properties sheet is non-null, getPrintJob() modifies it to show the actual options used to print the job. You can use the modified properties sheet to find out what properties are recognized on your system and to save a set of printing options for use on a later print job. If you are printing multiple pages, each page should originate from the same print job. According to Sun's documentation, getPrintJob() ought to return null if the user cancels the print job. However, this is a problem. On some platforms (notably Windows NT/95), the print dialog box doesn't even appear until you call the getGraphics() method. In this case, getPrintJob() still returns a print job and never returns null. If the user cancels the job, getGraphics() returns null.
Methods public abstract Graphics getGraphics () The getGraphics() method returns an instance of Graphics that also implements PrintGraphics. This graphics context can then be used as the parameter to methods like paint(), print(), update(), or printAll() to print a single page. (All of these methods result in calls to paint(); in paint(), you draw whatever you want to print on the Graphics object.) On Windows NT/95 platforms, getGraphics() returns null if the user cancels the print job. public abstract Dimension getPageDimension () The getPageDimension() method returns the dimensions of the page in pixels, as a Dimension object. Since getGraphics() returns a graphics context only for a single page, it is the programmer's responsibility to decide when the current page is full, print the current page, and start a new page with a new Graphics object. The page size is chosen to roughly represent a screen but has no relationship to the page size or orientation. public abstract int getPageResolution () The getPageResolution() method returns the number of pixels per inch for drawing on the page. It is completely unclear what this means, since the number returned has no relationship to the printer resolution. It appears to be similar to the screen resolution. public abstract boolean lastPageFirst () The lastPageFirst() method lets you know if the user configured the printer to print pages in reverse order. If this returns true, you need to generate the last page first. If false, you should print the first page first. This is relevant only if you are trying to print a multipage document. public abstract void end ()
http://localhost/java/javaref/awt/ch17_02.htm (2 of 3) [20/12/2001 11:09:57]
[Chapter 17] 17.2 PrintJob Class
The end() method terminates the print job. This is the last method you should call when printing; it does any cleaning up that's necessary. public void finalize () The finalize() method is called by the garbage collector. In the event you forget to call end(), finalize() calls it for you. However, it is best to call end() as soon as you know you have finished printing; don't rely on finalize().
PrintGraphics Interface
http://localhost/java/javaref/awt/ch17_02.htm (3 of 3) [20/12/2001 11:09:57]
Component Methods
[Chapter 17] 17.3 Component Methods
Chapter 17 Printing
17.3 Component Methods The methods that start the printing process come from either the Component or Container class and are inherited by all their children. All components inherit the printAll() and print() methods. Containers also inherit the printComponents() method, in addition to printAll() and print(). A container should call printComponents() to print itself if it contains any components. Otherwise, it is sufficient to call printAll(). These methods end up calling paint(), which does the actual drawing.
PrintJob Class
http://localhost/java/javaref/awt/ch17_03.htm [20/12/2001 11:09:58]
Printing Example
[Chapter 17] 17.4 Printing Example
Chapter 17 Printing
17.4 Printing Example Now that you know about the different classes necessary to print, let's put it all together. Printing takes four steps: 1. Get the PrintJob: PrintJob pjob = getToolkit().getPrintJob(this, "Job Title", (Properties)null); 2. Get the graphics context from the PrintJob: Graphics pg = pjob.getGraphics(); 3. Print by calling printAll() or print(). When this method returns, you can call dispose() to send the page to the printer: printAll(pg); pg.dispose(); // This is like sending a form feed 4. Clean up after yourself: pjob.end(); The following code summarizes how to print: // Java 1.1 only PrintJob pjob = getToolkit().getPrintJob(this, "Print?", (Properties)null); if (pjob != null) { Graphics pg = pjob.getGraphics(); if (pg != null) { printAll(pg); pg.dispose(); } pjob.end(); } This code prints the current component: what you get from the printer should be a reasonable rendition of what you see on the screen. Note that we didn't need to modify paint() at all. That should always be the case if you want your printer output to look like your onscreen component.
Component Methods
http://localhost/java/javaref/awt/ch17_04.htm [20/12/2001 11:09:58]
Printing Arbitrary Content
[Chapter 17] 17.5 Printing Arbitrary Content
Chapter 17 Printing
17.5 Printing Arbitrary Content Of course, in many situations, you want to do more than print the appearance of a component. You often want to print the contents of some component, rather than the component itself. For example, you may want to print the text the user has typed into a text area, rather than the text area itself. Or you may want to print the contents of a spreadsheet, rather than the collection of components that compose the spreadsheet. Java 1.1 lets you print arbitrary content, which may include multipage documents. You aren't restricted to printing your components' appearance. In many ways, the steps required to print arbitrary content are similar to those we outlined previously. However, a few tricks are involved: 1. Get the PrintJob: PrintJob pjob = getToolkit().getPrintJob(this, "Job Title", (Properties)null); 2. Get the graphics context from the PrintJob: Graphics pg = pjob.getGraphics(); 3. Don't call printAll() or print(). These methods will try to draw your component on the page, which you don't want. Instead, get the dimensions of the page by calling getPageDimension(): pjob.getPageDimension(); 4. Set the font for your graphics context; then get the font metrics from your graphics context. Font times = new Font ("SansSerif", Font.PLAIN, 12); pg.setFont(times); FontMetrics tm = pg.getFontMetrics(times); 5. Draw whatever you want into the graphics context, using the methods of the Graphics class. If you are drawing text, it's your responsibility to do all the positioning, making sure that your text falls within the page boundaries. By the time you're through with this, you'll have the FontMetrics class memorized. 6. When you've finished drawing the current page, call dispose(); this sends the page to the printer and releases the resources tied up by the PrintGraphics object. pg.dispose(); // This is like sending a form feed 7. If you want to print more pages, return to step 2. 8. Clean up after yourself: pjob.end(); Remember to set a font for the PrintGraphics object explicitly! It doesn't have a default font. An example that loads and prints a text file is available from this book's Web page. http://localhost/java/javaref/awt/ch17_05.htm (1 of 2) [20/12/2001 11:09:59]
[Chapter 17] 17.5 Printing Arbitrary Content
Printing Example
http://localhost/java/javaref/awt/ch17_05.htm (2 of 2) [20/12/2001 11:09:59]
java.applet Reference
[Chapter 18] 18.2 Package diagrams
Chapter 18 java.applet Reference
18.2 Package diagrams The following figures provide a visual representation of the relationships between the classes in the AWT packages. java.awt, as the mother of all AWT packages, is better represented by two diagrams, one for the graphics classes and one for the component and layout classes. Figure 18.1: Component and Layout classes of the java.awt package.
http://localhost/java/javaref/awt/ch18_02.htm (1 of 7) [20/12/2001 11:10:03]
[Chapter 18] 18.2 Package diagrams
Figure 18.2: Graphics classes of java.awt package
http://localhost/java/javaref/awt/ch18_02.htm (2 of 7) [20/12/2001 11:10:03]
[Chapter 18] 18.2 Package diagrams
Figure 18.3: The java.awt.image package
http://localhost/java/javaref/awt/ch18_02.htm (3 of 7) [20/12/2001 11:10:03]
[Chapter 18] 18.2 Package diagrams
Figure 18.4: The java.awt.datatransfer package
Figure 18.5: The java.awt.event package
http://localhost/java/javaref/awt/ch18_02.htm (4 of 7) [20/12/2001 11:10:03]
[Chapter 18] 18.2 Package diagrams
Figure 18.6: The java.awt.peer package
http://localhost/java/javaref/awt/ch18_02.htm (5 of 7) [20/12/2001 11:10:03]
[Chapter 18] 18.2 Package diagrams
Figure 18.7: The java.applet package
http://localhost/java/javaref/awt/ch18_02.htm (6 of 7) [20/12/2001 11:10:03]
[Chapter 18] 18.2 Package diagrams
Introduction to the Reference Chapters
http://localhost/java/javaref/awt/ch18_02.htm (7 of 7) [20/12/2001 11:10:03]
AWTError
[Chapter 18] Applet
Chapter 18 java.applet Reference
Applet Name Applet
Description The Applet class provides the framework for delivering Java programs within web pages.
Class Definition public class java.applet.Applet extends java.awt.Panel { // Constructors public Applet(); // Instance Methods public void destroy(); public AppletContext getAppletContext(); public String getAppletInfo(); public AudioClip getAudioClip (URL url); public AudioClip getAudioClip (URL url, String filename); public URL getCodeBase(); public URL getDocumentBase();
http://localhost/java/javaref/awt/ch18_03.htm (1 of 8) [20/12/2001 11:10:08]
[Chapter 18] Applet
public Image getImage (URL url); public Image getImage (URL url, String filename); public public public public public public public public public public public public public
Locale getLocale(); String getParameter (String name); String[][] getParameterInfo(); void init(); boolean isActive(); void play (URL url); void play (URL url, String filename); void resize (int width, int height); void resize (Dimension dim); final void setStub (AppletStub stub); void showStatus (String message); void start(); void stop();
}
Constructors Applet public Applet() Description Constructs an Applet object.
Instance Methods destroy public void destroy() Description Called when the browser determines that it doesn't need to keep the applet around anymore.
getAppletContext public AppletContext getAppletContext() Returns The current AppletContext of the applet.
http://localhost/java/javaref/awt/ch18_03.htm (2 of 8) [20/12/2001 11:10:08]
[Chapter 18] Applet
getAppletInfo public String getAppletInfo() Returns A short information string about the applet to be shown to the user.
getAudioClip public AudioClip getAudioClip (URL url) Parameters url URL of an audio file. Returns Object that implements the AudioClip interface for playing audio files. Description Fetches an audio file to play with the AudioClip interface. public AudioClip getAudioClip (URL url , String filename) Parameters url Base URL of an audio file. filename Specific file, relative to url, that contains an audio file. Returns Object that implements AudioClip interface for playing audio file. Description Fetches an audio file to play with the AudioClip interface.
getCodeBase public URL getCodeBase() Returns The complete URL of the .class file that contains the applet.
http://localhost/java/javaref/awt/ch18_03.htm (3 of 8) [20/12/2001 11:10:08]
[Chapter 18] Applet
getDocumentBase public URL getDocumentBase() Returns The complete URL of the .html file that loaded the applet.
getImage public Image getImage (URL url) Parameters url URL of an image file. Returns Image to be displayed. Description Initiates the image loading process for the file located at the specified location. public Image getImage (URL url, String filename) Parameters url Base URL of an image file. filename Specific file, relative to url, that contains an image file. Returns Image to be displayed. Description Initiates the image loading process for the file located at the specified location.
getLocale public Locale getLocale() Returns Applet's locale. Overrides http://localhost/java/javaref/awt/ch18_03.htm (4 of 8) [20/12/2001 11:10:08]
[Chapter 18] Applet
Component.getLocale() Description Used for internationalization support.
getParameter public String getParameter (String name) Parameters name Name of parameter to get. Returns The value associated with the given parameter in the HTML file, or null. Description Allows you to get parameters from within the <APPLET> tag of the .html file that loaded the applet.
getParameterInfo public String[][] getParameterInfo() Returns Overridden to provide a series of three-string arrays that describes the parameters this applet reads.
init public void init() Description Called by the system when the applet is first loaded.
isActive public boolean isActive() Returns true if the applet is active, false otherwise.
http://localhost/java/javaref/awt/ch18_03.htm (5 of 8) [20/12/2001 11:10:08]
[Chapter 18] Applet
play public void play (URL url) Parameters url URL of an audio file . Description Plays an audio file once. public void play (URL url, String filename) Parameters url Base URL of an audio file . filename Specific file, relative to url, that contains an audio file. Description Plays an audio file once.
resize public void resize(int width, int height) Parameters width New width for the Applet. height New height for the Applet. Description Changes the size of the applet. public void resize (Dimension dim) Parameters dim New dimensions for the applet. Description http://localhost/java/javaref/awt/ch18_03.htm (6 of 8) [20/12/2001 11:10:08]
[Chapter 18] Applet
Changes the size of the applet.
setStub public final void setStub (AppletStub stub) Parameters stub Platform specific stubfor environment. Description Called by the system to setup AppletStub.
showStatus public void showStatus (String message) Parameters message Message to display to user. Description Displays a message on the status line of the browser.
start public void start() Description Called by the system every time the applet is displayed.
stop public void stop() Description Called by the system when it wants the applet to stop execution; typically, every time the user leaves the page that includes the applet.
http://localhost/java/javaref/awt/ch18_03.htm (7 of 8) [20/12/2001 11:10:08]
[Chapter 18] Applet
See Also AppletContext, AppletStub, AudioClip, Container, Dimension, Image, Locale, Panel, String, URL
Package diagrams
http://localhost/java/javaref/awt/ch18_03.htm (8 of 8) [20/12/2001 11:10:08]
AppletContext
[Chapter 18] AppletContext
Chapter 18 java.applet Reference
AppletContext Name AppletContext
Description AppletContext is an interface that provides the means to control the browser environment in which the applet is running.
Interface Definition public abstract interface java.applet.AppletContext { // Interface Methods public abstract Applet getApplet (String name); public abstract Enumeration getApplets(); public abstract AudioClip getAudioClip (URL url); public abstract Image getImage (URL url); public abstract void showDocument (URL url); public abstract void showDocument (URL url, String frame); public abstract void showStatus (String message); }
http://localhost/java/javaref/awt/ch18_04.htm (1 of 4) [20/12/2001 11:10:11]
[Chapter 18] AppletContext
Interface Methods getApplet public abstract Applet getApplet (String name) Parameters name Name of applet to locate. Returns Applet fetched. Description Gets a reference to another executing applet.
getApplets public abstract Enumeration getApplets() Returns List of applets executing. Description Gets references to all executing applets.
getAudioClip public abstract AudioClip getAudioClip (URL url) Parameters url Location of an audio file. Returns AudioClip fetched. Description Loads an audio file.
http://localhost/java/javaref/awt/ch18_04.htm (2 of 4) [20/12/2001 11:10:11]
[Chapter 18] AppletContext
getImage public abstract Image getImage (URL url) Parameters url Location of an image file. Returns Image fetched. Description Loads an image file.
showDocument public abstract void showDocument (URL url) Parameters url New web page to display. Description Changes the displayed web page. public abstract void showDocument (URL url, String frame) Parameters url New web page to display. frame Name of the frame in which to display the new page. Description Displays a web page in another frame.
showStatus public abstract void showStatus (String message) Parameters message
http://localhost/java/javaref/awt/ch18_04.htm (3 of 4) [20/12/2001 11:10:11]
[Chapter 18] AppletContext
Message to display. Description Displays a message on the status line of the browser.
See Also Applet, AudioClip, Enumeration, Image, Object, String, URL
Applet
http://localhost/java/javaref/awt/ch18_04.htm (4 of 4) [20/12/2001 11:10:11]
AppletStub
[Chapter 18] AppletStub
Chapter 18 java.applet Reference
AppletStub Name AppletStub
Description AppletStub is an interface that provides the means to get information from the run-time browser environment.
Interface Definition public abstract interface java.applet.AppletStub { // Interface Methods public abstract void appletResize (int width, int height); public abstract AppletContext getAppletContext(); public abstract URL getCodeBase(); public abstract URL getDocumentBase(); public abstract String getParameter (String name); public abstract boolean isActive(); }
http://localhost/java/javaref/awt/ch18_05.htm (1 of 3) [20/12/2001 11:10:12]
[Chapter 18] AppletStub
Interface Methods appletResize public abstract void appletResize (int width, int height) Parameters width Requested new width for applet. height Requested new height for applet. Description Changes the size of the applet.
getAppletContext public abstract AppletContext getAppletContext() Returns Current AppletContext of the applet.
getCodeBase public abstract URL getCodeBase() Returns Complete URL for the applet's .class file.
getDocumentBase public abstract URL getDocumentBase() Returns Complete URL for the applet's .html file.
getParameter public abstract String getParameter (String name) Parameters name http://localhost/java/javaref/awt/ch18_05.htm (2 of 3) [20/12/2001 11:10:12]
[Chapter 18] AppletStub
Name of a tag. Returns Value associated with the parameter. Description Gets a parameter value from the tag(s) of the applet.
isActive public abstract boolean isActive() Returns true if the applet is active, false otherwise Description Returns current state of the applet.
See Also AppletContext, Object, String, URL
AppletContext
http://localhost/java/javaref/awt/ch18_05.htm (3 of 3) [20/12/2001 11:10:12]
AudioClip
[Chapter 18] AudioClip
Chapter 18 java.applet Reference
AudioClip Name AudioClip
Description AudioClip is an interface for playing audio files.
Interface Definition public abstract interface java.applet.AudioClip { // Interface Methods public abstract void loop(); public abstract void play(); public abstract void stop(); }
Interface Methods loop public abstract void loop() Description
http://localhost/java/javaref/awt/ch18_06.htm (1 of 2) [20/12/2001 11:10:13]
[Chapter 18] AudioClip
Plays an audio clip continuously.
play public abstract void play() Description Plays an audio clip once from the beginning.
stop public abstract void stop() Description Stops playing an audio clip.
See Also Object
AppletStub
http://localhost/java/javaref/awt/ch18_06.htm (2 of 2) [20/12/2001 11:10:13]
AWTError
[Chapter 19] AWTEvent
Chapter 19 java.awt Reference
AWTEvent Name AWTEvent
Description The root class of all AWT events. Subclasses of this class are the replacement for java.awt.Event, which is only used for the Java 1.0.2 event model. In Java 1.1, event objects are passed from event source components to objects implementing a corresponding listener interface. Some event sources have a corresponding interface, too. For example, AdjustmentEvents are passed from Adjustable objects to AdjustmentListeners. Some event types do not have corresponding interfaces; for example, ActionEvents are passed from Buttons to ActionListeners, but there is no "Actionable" interface that Button implements.
http://localhost/java/javaref/awt/ch19_02.htm (1 of 6) [20/12/2001 11:10:15]
[Chapter 19] AWTEvent
Class Definition public abstract class java.awt.AWTEvent extends java.util.EventObject { // Constants public final static long ACTION_EVENT_MASK; public final static long ADJUSTMENT_EVENT_MASK; public final static long COMPONENT_EVENT_MASK; public final static long CONTAINER_EVENT_MASK; public final static long FOCUS_EVENT_MASK; public final static long ITEM_EVENT_MASK; public final static long KEY_EVENT_MASK; public final static long MOUSE_EVENT_MASK; public final static long MOUSE_MOTION_EVENT_MASK; public final static long RESERVED_ID_MAX; public final static long TEXT_EVENT_MASK; public final static long WINDOW_EVENT_MASK; // Variables protected boolean consumed; protected int id; // Constructors public AWTEvent (Event event); public AWTEvent (Object source, int id); // Instance Methods public int getID(); public String paramString(); public String toString(); // Protected Instance Methods protected void consume(); protected boolean isConsumed(); }
Constants ACTION_EVENT_MASK public static final long ACTION_EVENT_MASK The mask for action events.
http://localhost/java/javaref/awt/ch19_02.htm (2 of 6) [20/12/2001 11:10:15]
[Chapter 19] AWTEvent
ADJUSTMENT_EVENT_MASK public static final long ADJUSTMENT_EVENT_MASK The mask for adjustment events.
COMPONENT_EVENT_MASK public static final long COMPONENT_EVENT_MASK The mask for component events.
CONTAINER_EVENT_MASK public static final long CONTAINER_EVENT_MASK The mask for container events.
FOCUS_EVENT_MASK public static final long FOCUS_EVENT_MASK The mask for focus events.
ITEM_EVENT_MASK public static final long ITEM_EVENT_MASK The mask for item events.
KEY_EVENT_MASK public static final long KEY_EVENT_MASK The mask for key events.
MOUSE_EVENT_MASK public static final long MOUSE_EVENT_MASK The mask for mouse events.
http://localhost/java/javaref/awt/ch19_02.htm (3 of 6) [20/12/2001 11:10:15]
[Chapter 19] AWTEvent
MOUSE_MOTION_EVENT_MASK public static final long MOUSE_MOTION_EVENT_MASK The mask for mouse motion events.
RESERVED_ID_MAX public static final int The maximum reserved event id.
TEXT_EVENT_MASK public static final long TEXT_EVENT_MASK The mask for text events.
WINDOW_EVENT_MASK public static final long WINDOW_EVENT_MASK The mask for window events.
Variables consumed protected boolean consumed If consumed is true, the event will not be sent back to the peer. Semantic events will never be sent back to a peer; thus consumed is always true for semantic events.
id protected int id The type ID of this event.
Constructors
http://localhost/java/javaref/awt/ch19_02.htm (4 of 6) [20/12/2001 11:10:15]
[Chapter 19] AWTEvent
AWTEvent public AWTEvent (Event event) Parameters event A version 1.0.2 java.awt.Event object. Description Constructs a 1.1 java.awt.AWTEvent derived from a 1.0.2 java.awt.Event object. public AWTEvent (Object source, int id) Parameters source The object that the event originated from. id An event type ID. Description Constructs an AWTEvent object.
Instance Methods getID public int getID() Returns The type ID of the event.
paramString public String paramString() Returns A string with the current settings of AWTEvent. Description Helper method for toString() that generates a string of current settings.
http://localhost/java/javaref/awt/ch19_02.htm (5 of 6) [20/12/2001 11:10:15]
[Chapter 19] AWTEvent
toString public String toString() Returns A string representation of the AWTEvent object. Overrides Object.toString()
Protected Instance Methods consume protected void consume() Description Consumes the event so it is not sent back to its source.
isConsumed public boolean isConsumed() Returns A flag indicating whether this event has been consumed.
See Also ActionEvent, AdjustmentEvent, ComponentEvent, Event, EventObject, FocusEvent, ItemEvent, KeyEvent, MouseEvent, WindowEvent
AWTError
http://localhost/java/javaref/awt/ch19_02.htm (6 of 6) [20/12/2001 11:10:15]
AWTEventMulticaster
[Chapter 19] AWTEventMulticaster
Chapter 19 java.awt Reference
AWTEventMulticaster Name AWTEventMulticaster
Description This class multicasts events to event listeners. Each multicaster has two listeners, cunningly named a and b. When an event source calls one of the listener methods of the multicaster, the multicaster calls the same listener method on both a and b. Multicasters are built into trees using the static add() and remove() methods. In this way a single event can be sent to many listeners. Static methods make it easy to implement event multicasting in component subclasses. Each time an addListener() function is called in the component subclass, call the corresponding AWTEventMulticaster.add() method to chain together (or "tree up") listeners. Similarly, when a removeListener() function is called, AWTEventMulticaster.remove() can be called to remove a http://localhost/java/javaref/awt/ch19_03.htm (1 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
chained listener.
Class Definition public class java.awt.AWTEventMulticaster extends java.lang.Object implements java.awt.event.ActionListener, java.awt.event.AdjustmentListener, java.awt.event.ComponentListener, java.awt.event.ContainerListener, java.awt.event.FocusListener, java.awt.event.ItemListener, java.awt.event.KeyListener, java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.TextListener, java.awt.event.WindowListener { // Variables protected EventListener a; protected EventListener b; // Constructors protected AWTEventMulticaster(EventListener a, EventListener b); // Class Methods public static ActionListener add(ActionListener a, ActionListener b); public static AdjustmentListener add(AdjustmentListener a, AdjustmentListener b); public static ComponentListener add(ComponentListener a, ComponentListener b); public static ContainerListener add(ContainerListener a, ContainerListener b); public static FocusListener add(FocusListener a, FocusListener b); public static ItemListener add(ItemListener a, ItemListener b); public static KeyListener add(KeyListener a, KeyListener b); public static MouseListener add(MouseListener a, MouseListener b); public static MouseMotionListener add(MouseMotionListener a, MouseMotionListener b); public static TextListener add(TextListener a, TextListener b); public static WindowListener add(WindowListener a, WindowListener b); protected static EventListener addInternal(EventListener a, EventListener b); public static ActionListener remove(ActionListener l, ActionListener oldl); public static AdjustmentListener remove(AdjustmentListener l, AdjustmentListener oldl); public static ComponentListener remove(ComponentListener l, ComponentListener oldl); public static ContainerListener remove(ContainerListener l, ContainerListener oldl); public static FocusListener remove(FocusListener l, FocusListener oldl); public static ItemListener remove(ItemListener l, ItemListener oldl); public static KeyListener remove(KeyListener l, KeyListener oldl); public static MouseListener remove(MouseListener l, MouseListener oldl); public static MouseMotionListener remove(MouseMotionListener l, MouseMotionListener oldl); public static TextListener remove(TextListener l, TextListener oldl); public static WindowListener remove(WindowListener l, WindowListener; protected static EventListener removeInternal(EventListener l, EventListener oldl); http://localhost/java/javaref/awt/ch19_03.htm (2 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
// Instance Methods public void actionPerformed(ActionEvent e); public void adjustmentValueChanged(AdjustmentEvent e); public void componentAdded(ContainerEvent e); public void componentHidden(ComponentEvent e); public void componentMoved(ComponentEvent e); public void componentRemoved(ContainerEvent e); public void componentResized(ComponentEvent e); public void componentShown(ComponentEvent e); public void focusGained(FocusEvent e); public void focusLost(FocusEvent e); public void itemStateChanged(ItemEvent e); public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e); public void mouseClicked(MouseEvent e); public void mouseDragged(MouseEvent e); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e); public void mouseMoved(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseReleased(MouseEvent e); public void textValueChanged(TextEvent e); public void windowActivated(WindowEvent e); public void windowClosed(WindowEvent e); public void windowClosing(WindowEvent e); public void windowDeactivated(WindowEvent e); public void windowDeiconified(WindowEvent e); public void windowIconified(WindowEvent e); public void windowOpened(WindowEvent e); // Protected Instance Methods protected EventListener remove(EventListener oldl); protected void saveInternal(ObjectOutputStream s, String k) throws IOException; }
Variables a protected EventListener a One of the EventListeners this AWTEventMulticaster sends events to.
b protected EventListener b One of the EventListeners this AWTEventMulticaster sends events to.
http://localhost/java/javaref/awt/ch19_03.htm (3 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
Constructors AWTEventMulticaster protected AWTEventMulticaster (EventListener a, EventListener b) Parameters a A listener that receives events. b A listener that receives events. Description Constructs an AWTEventMulticaster that sends events it receives to the supplied listeners. The constructor is protected because it is only the class methods of AWTEventMulticaster that ever instantiate this class.
Class Methods add public static ActionListener add (ActionListener a, ActionListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. public static AdjustmentListener add (AdjustmentListener a, AdjustmentListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. public static ComponentListener add (ComponentListener a, ComponentListener b) Parameters a
http://localhost/java/javaref/awt/ch19_03.htm (4 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
An event listener. b An event listener. Returns A listener object that passes events to a and b. public static ContainerListener add (ContainerListener a, ContainerListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. public static FocusListener add (FocusListener a, FocusListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. public static ItemListener add (ItemListener a, ItemListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. public static KeyListener add (KeyListener a, KeyListener b) Parameters a An event listener. b
http://localhost/java/javaref/awt/ch19_03.htm (5 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
An event listener. Returns A listener object that passes events to a and b. public static MouseListener add (MouseListener a, MouseListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. public static MouseMotionListener add (MouseMotionListener a, MouseMotionListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. public static TextListener add (TextListener a, TextListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. public static WindowListener add (WindowListener a, WindowListener b) Parameters a An event listener. b An event listener. Returns
http://localhost/java/javaref/awt/ch19_03.htm (6 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
A listener object that passes events to a and b.
addInternal public static EventListener addInternal (EventListener a, EventListener b) Parameters a An event listener. b An event listener. Returns A listener object that passes events to a and b. Description This method is a helper for the add() methods.
remove public static ActionListener remove (ActionListener l, ActionListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static AdjustmentListener remove (AdjustmentListener l, AdjustmentListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static ComponentListener remove (ComponentListener l, ComponentListener oldl) Parameters l An event listener.
http://localhost/java/javaref/awt/ch19_03.htm (7 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static ContainerListener remove (ContainerListener l, ContainerListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static FocusListener remove (FocusListener l, FocusListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static ItemListener remove (ItemListener l, ItemListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static KeyListener remove (KeyListener l, KeyListener oldl) Parameters l An event listener. oldl An event listener.
http://localhost/java/javaref/awt/ch19_03.htm (8 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
Returns A listener object that multicasts to l but not oldl. public static MouseListener remove (MouseListener l, MouseListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static MouseMotionListener remove (MouseMotionListener l, MouseMotionListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static TextListener remove (TextListener l, TextListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. public static WindowListener remove (WindowListener l, WindowListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl.
http://localhost/java/javaref/awt/ch19_03.htm (9 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
public static WindowListener remove (WindowListener l, WindowListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl.
removeInternal public static EventListener removeInternal (EventListener l, EventListener oldl) Parameters l An event listener. oldl An event listener. Returns A listener object that multicasts to l but not oldl. Description This method is a helper for the remove() methods.
Instance Methods actionPerformed public void actionPerformed (ActionEvent e) Parameters e The action event that occurred. Description Handles the event by passing it on to listeners a and b.
adjustmentValueChanged public void adjustmentValueChanged (AdjustmentEvent e) Parameters e The adjustment event that occurred. http://localhost/java/javaref/awt/ch19_03.htm (10 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
Description Handles the event by passing it on to listeners a and b.
componentAdded public void componentAdded (ContainerEvent e) Parameters e The container event that occurred. Description Handles the event by passing it on to listeners a and b.
componentHidden public void componentHidden (ComponentEvent e) Parameters e The component event that occurred. Description Handles the event by passing it on to listeners a and b.
componentMoved public void componentMoved (ComponentEvent e) Parameters e The component event that occurred. Description Handles the event by passing it on to listeners a and b.
componentRemoved public void componentRemoved (ContainerEvent e) Parameters e The container event that occurred. Description Handles the event by passing it on to listeners a and b.
http://localhost/java/javaref/awt/ch19_03.htm (11 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
componentResized public void componentResized (ComponentEvent e) Parameters e The component event that occurred. Description Handles the event by passing it on to listeners a and b.
componentShown public void componentShown (ComponentEvent e) Parameters e The component event that occurred. Description Handles the event by passing it on to listeners a and b.
focusGained public void focusGained (FocusEvent e) Parameters e The focus event that occurred. Description Handles the event by passing it on to listeners a and b.
focusLost public void focusLost (FocusEvent e) Parameters e The focus event that occurred. Description Handles the event by passing it on to listeners a and b.
itemStateChanged public void itemStateChanged (ItemEvent e) Parameters e http://localhost/java/javaref/awt/ch19_03.htm (12 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
The item event that occurred. Description Handles the event by passing it on to listeners a and b.
keyPressed public void keyPressed (KeyEvent e) Parameters e The key event that occurred. Description Handles the event by passing it on to listeners a and b.
keyReleased public void keyReleased (KeyEvent e) Parameters e The key event that occurred. Description Handles the event by passing it on to listeners a and b.
keyTyped public void keyTyped (KeyEvent e) Parameters e The key event that occurred. Description Handles the event by passing it on to listeners a and b.
mouseClicked public void mouseClicked (MouseEvent e) Parameters e The mouse event that occurred. Description Handles the event by passing it on to listeners a and b.
http://localhost/java/javaref/awt/ch19_03.htm (13 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
mouseDragged public void mouseDragged (MouseEvent e) Parameters e The mouse event that occurred. Description Handles the event by passing it on to listeners a and b.
mouseEntered public void mouseEntered (MouseEvent e) Parameters e The mouse event that occurred. Description Handles the event by passing it on to listeners a and b.
mouseExited public void mouseExited (MouseEvent e) Parameters e The mouse event that occurred. Description Handles the event by passing it on to listeners a and b.
mouseMoved public void mouseMoved (MouseEvent e) Parameters e The mouse event that occurred. Description Handles the event by passing it on to listeners a and b.
mousePressed public void mousePressed (MouseEvent e) Parameters e http://localhost/java/javaref/awt/ch19_03.htm (14 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
The mouse event that occurred. Description Handles the event by passing it on to listeners a and b.
mouseReleased public void mouseReleased (MouseEvent e) Parameters e The mouse event that occurred. Description Handles the event by passing it on to listeners a and b.
textValueChanged public void textValueChanged (TextEvent e) Parameters e The text event that occurred. Description Handles the event by passing it on to listeners a and b.
windowActivated public void windowActivated (WindowEvent e) Parameters e The window event that occurred. Description Handles the event by passing it on to listeners a and b.
windowClosed public void windowClosed (WindowEvent e) Parameters e The window event that occurred. Description Handles the event by passing it on to listeners a and b.
http://localhost/java/javaref/awt/ch19_03.htm (15 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
windowClosing public void windowClosing (WindowEvent e) Parameters e The window event that occurred. Description Handles the event by passing it on to listeners a and b.
windowDeactivated public void windowDeactivated (WindowEvent e) Parameters e The window event that occurred. Description Handles the event by passing it on to listeners a and b.
windowDeiconified public void windowDeiconified (WindowEvent e) Parameters e The window event that occurred. Description Handles the event by passing it on to listeners a and b.
windowIconified public void windowIconified (WindowEvent e) Parameters e The window event that occurred. Description Handles the event by passing it on to listeners a and b.
windowOpened public void windowOpened (WindowEvent e) Parameters e http://localhost/java/javaref/awt/ch19_03.htm (16 of 17) [20/12/2001 11:10:19]
[Chapter 19] AWTEventMulticaster
The window event that occurred. Description Handles the event by passing it on to listeners a and b.
Protected Instance Methods remove protected EventListener remove(EventListener oldl) Parameters oldl The listener to remove. Returns The resulting EventListener. Description This method removes oldl from the AWTEventMulticaster and returns the resulting listener.
See Also ActionEvent, AdjustmentEvent, ComponentEvent, Event, EventListener, EventObject, FocusEvent, ItemEvent, KeyEvent, MouseEvent, WindowEvent
AWTEvent
http://localhost/java/javaref/awt/ch19_03.htm (17 of 17) [20/12/2001 11:10:19]
AWTException
[Chapter 19] AWTException
Chapter 19 java.awt Reference
AWTException Name AWTException
Description An AWTException; thrown to indicate an exceptional condition; must be caught or declared in a throws clause.
Class Definition public class java.awt.AWTException extends java.lang.Exception { // Constructors public AWTException (String message); }
Constructors
http://localhost/java/javaref/awt/ch19_04.htm (1 of 2) [20/12/2001 11:10:22]
[Chapter 19] AWTException
AWTException public AWTException (String message) Parameters message Detailed message.
See Also Exception, String
AWTEventMulticaster
http://localhost/java/javaref/awt/ch19_04.htm (2 of 2) [20/12/2001 11:10:22]
Adjustable
[Chapter 19] Adjustable
Chapter 19 java.awt Reference
Adjustable Name Adjustable
Description The Adjustable interface is useful for scrollbars, sliders, dials, and other components that have an adjustable numeric value. Classes that implement the Adjustable interface should send AdjustmentEvent objects to listeners that have registered via addAdjustmentListener(AdjustmentListener).
Interface Definition public abstract interface java.awt.Adjustable { // Constants public final static int HORIZONTAL = 0; public final static int VERTICAL = 1; // Interface Methods public abstract void addAdjustmentListener (AdjustmentListener l); public abstract int getBlockIncrement(); public abstract int getMaximum(); public abstract int getMinimum(); public abstract int getOrientation(); public abstract int getUnitIncrement(); http://localhost/java/javaref/awt/ch19_05.htm (1 of 5) [20/12/2001 11:10:25]
[Chapter 19] Adjustable
public public public public public public public public public
abstract abstract abstract abstract abstract abstract abstract abstract abstract
int getValue(); int getVisibleAmount(); void removeAdjustmentListener (AdjustmentListener l); void setBlockIncrement (int b); void setMaximum (int max); void setMinimum (int min); void setUnitIncrement (int u); void setValue (int v); void setVisibleAmount (int v);
}
Constants HORIZONTAL public static final int HORIZONTAL A constant representing horizontal orientation.
VERTICAL public static final int VERTICAL A constant representing vertical orientation.
Interface Methods addAdjustmentListener public abstract void addAdjustmentListener (ActionListener l) Parameters l An object that implements the AdjustmentListener interface. Description Add a listener for adjustment event.
getBlockIncrement public abstract int getBlockIncrement() Returns
http://localhost/java/javaref/awt/ch19_05.htm (2 of 5) [20/12/2001 11:10:25]
[Chapter 19] Adjustable
The amount to scroll when a paging area is selected.
getMaximum public abstract int getMaximum() Returns The maximum value that the Adjustable object can take.
getMinimum public abstract int getMinimum() Returns The minimum value that the Adjustable object can take.
getOrientation public abstract int getOrientation() Returns A value representing the direction of the Adjustable object.
getUnitIncrement public abstract int getUnitIncrement() Returns The unit amount to scroll.
getValue public abstract int getValue() Returns The current setting for the Adjustable object.
getVisibleAmount public abstract int getVisibleAmount() Returns The current visible setting (i.e., size) for the Adjustable object. http://localhost/java/javaref/awt/ch19_05.htm (3 of 5) [20/12/2001 11:10:25]
[Chapter 19] Adjustable
removeAdjustmentListener public abstract void removeAdjustmentListener (AdjustmentListener l) Parameters l One of the object's AdjustmentListeners. Description Remove an adjustment event listener.
setBlockIncrement public abstract void setBlockIncrement (int b) Parameters b New block increment amount. Description Changes the block increment amount for the Adjustable object.
setMaximum public abstract void setMaximum (int max) Parameters max New maximum value. Description Changes the maximum value for the Adjustable object.
setMinimum public abstract void setMinimum (int min) Parameters min New minimum value. Description Changes the minimum value for the Adjustable object. http://localhost/java/javaref/awt/ch19_05.htm (4 of 5) [20/12/2001 11:10:25]
[Chapter 19] Adjustable
setUnitIncrement public abstract void setUnitIncrement (int u) Parameters u New unit increment amount. Description Changes the unit increment amount for the Adjustable object.
setValue public abstract void setValue (int v) Parameters v New value. Description Changes the current value of the Adjustable object.
setVisibleAmount public abstract void setVisibleAmount (int v) Parameters v New amount visible. Description Changes the current visible amount of the Adjustable object.
See Also AdjustmentEvent, AdjustmentListener, Scrollbar
AWTException
http://localhost/java/javaref/awt/ch19_05.htm (5 of 5) [20/12/2001 11:10:25]
BorderLayout
[Chapter 19] BorderLayout
Chapter 19 java.awt Reference
BorderLayout Name BorderLayout
Description BorderLayout is a LayoutManager that provides the means to lay out components along the edges of a container. It divides the container into five regions, named North, East, South, West, and Center. Normally you won't call the LayoutManager's methods yourself. When you add() a Component to a Container, the Container calls the addLayoutComponent() method of its LayoutManager.
Class Definition public class java.awt.BorderLayout extends java.lang.Object implements java.awt.LayoutManager2, java.io.Serializable { // Constants public final static String CENTER; public final static String EAST; public final static String NORTH; public final static String SOUTH;
http://localhost/java/javaref/awt/ch19_06.htm (1 of 8) [20/12/2001 11:10:27]
[Chapter 19] BorderLayout
public final static String WEST; // Constructors public BorderLayout(); public BorderLayout (int hgap, int vgap); // Instance Methods public void addLayoutComponent (Component comp, Object constraints); public void addLayoutComponent (String name, Component component); public int getHgap(); public abstract float getLayoutAlignmentX(Container target); public abstract float getLayoutAlignmentY(Container target); public int getVgap(); public abstract void invalidateLayout(Container target); public void layoutContainer (Container target); public public public public
abstract Dimension maximumLayoutSize(Container target); Dimension minimumLayoutSize (Container target); Dimension preferredLayoutSize (Container target); void removeLayoutComponent (Component component);
public void setHgap (int hgap); public void setVgap (int vgap); public String toString(); }
Constants CENTER public final static String CENTER A constant representing center orientation.
EAST public final static String EAST A constant representing east orientation.
http://localhost/java/javaref/awt/ch19_06.htm (2 of 8) [20/12/2001 11:10:27]
[Chapter 19] BorderLayout
NORTH public final static String NORTH A constant representing north orientation.
SOUTH public final static String SOUTH A constant representing south orientation.
WEST public final static String WEST A constant representing west orientation.
Constructors BorderLayout public BorderLayout() Description Constructs a BorderLayout object. public BorderLayout (int hgap, int vgap) Parameters hgap Horizontal space between each component in the container. vgap Vertical space between each component in the container. Description Constructs a BorderLayout object with the values specified as the gaps between each component in the container managed by this instance of BorderLayout.
Instance Methods
http://localhost/java/javaref/awt/ch19_06.htm (3 of 8) [20/12/2001 11:10:27]
[Chapter 19] BorderLayout
addLayoutComponent public void addLayoutComponent (Component comp, Object constraints) Parameters comp The component being added. constraints An object describing the constraints on this component. Implements LayoutManager2.addLayoutComponent() Description Adds the component comp to a container subject to the given constraints. This is a more general version of addLayoutComponent(String, Component) method. It corresponds to java.awt.Container's add(Component, Object) method. In practice, it is used the same in version 1.1 as in Java 1.0.2, except with the parameters swapped: Panel p = new Panel(new BorderLayout()); p.add(new Button("OK"), BorderLayout.SOUTH);
addLayoutComponent public void addLayoutComponent (String name, Component component) Parameters name Name of region to add component to. component Actual component being added. Implements LayoutManager.addLayoutComponent() Description Adds a component to a container in region name. This has been replaced in version 1.1 with the more general addLayoutComponent(Component, Object).
http://localhost/java/javaref/awt/ch19_06.htm (4 of 8) [20/12/2001 11:10:27]
[Chapter 19] BorderLayout
getHgap public int getHgap() Returns The horizontal gap for this BorderLayout instance.
getLayoutAlignmentX public abstract float getLayoutAlignmentX (Container target) Parameters target The container to inspect. Returns The value .5 for all containers. Description This method returns the preferred alignment of the given container target. A return value of 0 is left aligned, .5 is centered, and 1 is right aligned.
getLayoutAlignmentY public abstract float getLayoutAlignmentY (Container target) Parameters target The container to inspect. Returns The value .5 for all containers. Description This method returns the preferred alignment of the given container target. A return value of 0 is top aligned, .5 is centered, and 1 is bottom aligned.
getVgap public int getVgap() Returns The vertical gap for this BorderLayout instance.
http://localhost/java/javaref/awt/ch19_06.htm (5 of 8) [20/12/2001 11:10:27]
[Chapter 19] BorderLayout
invalidateLayout public abstract void invalidateLayout (Container target) Parameters target The container to invalidate. Description Does nothing.
layoutContainer public void layoutContainer (Container target) Parameters target The container that needs to be redrawn. Implements LayoutManager.layoutContainer() Description Draws components contained within target.
maximumLayoutSize public abstract Dimension maximumLayoutSize (Container target) Parameters target The container to inspect. Returns A Dimension whose horizontal and vertical components are Integer.MAX_VALUE. Description For BorderLayout, a maximal Dimension is always returned.
minimumLayoutSize public Dimension minimumLayoutSize (Container target) Parameters target http://localhost/java/javaref/awt/ch19_06.htm (6 of 8) [20/12/2001 11:10:27]
[Chapter 19] BorderLayout
The container whose size needs to be calculated. Returns Minimum Dimension of the container target. Implements LayoutManager.minimumLayoutSize() Description Calculates minimum size of target. container.
preferredLayoutSize public Dimension preferredLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Preferred Dimension of the container target. Implements LayoutManager.preferredLayoutSize() Description Calculates preferred size of target container.
removeLayoutComponent public void removeLayoutComponent (Component component) Parameters component Component to stop tracking. Implements LayoutManager.removeLayoutComponent() Description Removes component from any internal tracking systems.
http://localhost/java/javaref/awt/ch19_06.htm (7 of 8) [20/12/2001 11:10:27]
[Chapter 19] BorderLayout
setHgap public void setHgap (int hgap) Parameters hgap The horizontal gap value. Description Sets the horizontal gap between components.
setVgap public void setVgap (int vgap) Parameters vgap The vertical gap value. Description Sets the vertical gap between components.
toString public String toString() Returns A string representation of the BorderLayout object. Overrides Object.toString()
See Also Component, Container, Dimension, LayoutManager, LayoutManager2, Object, String
Adjustable
http://localhost/java/javaref/awt/ch19_06.htm (8 of 8) [20/12/2001 11:10:27]
Button
[Chapter 19] Button
Chapter 19 java.awt Reference
Button Name Button
Description The Button is the familiar labeled button object. It inherits most of its functionality from Component. For example, to change the font of the Button, you would use Component's setFont() method. The Button sends java.awt.event.ActionEvent objects to its listeners when it is pressed.
Class Definition public class java.awt.Button extends java.awt.Component { // Constructors public Button(); public Button (String label); // Instance Methods public void addActionListener (ActionListener l); public void addNotify(); public String getActionCommand(); public String getLabel();
http://localhost/java/javaref/awt/ch19_07.htm (1 of 5) [20/12/2001 11:10:29]
[Chapter 19] Button
public void removeActionListener (ActionListener l); public void setActionCommand (String command); public synchronized void setLabel (String label); // Protected Instance Methods protected String paramString(); protected void processActionEvent (ActionEvent e); protected void processEvent (AWTEvent e); }
Constructors Button public Button() Description Constructs a Button object with no label. public Button (String label) Parameters label The text for the label on the button Description Constructs a Button object with text of label.
Instance Methods addActionListener public void addActionListener (ActionListener l) Parameters l An object that implements the ActionListener interface. Description Add a listener for the action event.
http://localhost/java/javaref/awt/ch19_07.htm (2 of 5) [20/12/2001 11:10:29]
[Chapter 19] Button
addNotify public void addNotify() Overrides Component.addNotify() Description Creates Button's peer.
getActionCommand public String getActionCommand() Returns Current action command string. Description Returns the string used for the action command.
getLabel public String getLabel() Returns Text of the Button's label.
removeActionListener public void removeActionListener (ActionListener l) Parameters l One of this Button's ActionListeners. Description Remove an action event listener.
setActionCommand public void setActionCommand (String command) Parameters http://localhost/java/javaref/awt/ch19_07.htm (3 of 5) [20/12/2001 11:10:29]
[Chapter 19] Button
command New action command string. Description Specify the string used for the action command.
setLabel public synchronized void setLabel (String label) Parameters label New text for label of Button. Description Changes the Button's label to label.
Protected Instance Methods paramString protected String paramString() Returns String with current settings of Button. Overrides Component.paramString() Description Helper method for toString() used to generate a string of current settings.
processActionEvent protected void processActionEvent (ActionEvent e) Parameters e The action event to process. Description Action events are passed to this method for processing. Normally, this method is called by
http://localhost/java/javaref/awt/ch19_07.htm (4 of 5) [20/12/2001 11:10:29]
[Chapter 19] Button
processEvent().
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description Low level AWTEvents are passed to this method for processing.
See Also ActionListener, Component, String
BorderLayout
http://localhost/java/javaref/awt/ch19_07.htm (5 of 5) [20/12/2001 11:10:29]
Canvas
[Chapter 19] Canvas
Chapter 19 java.awt Reference
Canvas Name Canvas
Description Canvas is a Component that provides a drawing area and is often used as a base class for new components.
Class Definition public class java.awt.Canvas extends java.awt.Component { // Constructors public Canvas(); // Instance Methods public void addNotify(); public void paint (Graphics g); }
http://localhost/java/javaref/awt/ch19_08.htm (1 of 2) [20/12/2001 11:10:30]
[Chapter 19] Canvas
Constructors Canvas public Canvas() Description Constructs a Canvas object.
Instance Methods addNotify public void addNotify() Overrides Component.addNotify() Description Creates Canvas's peer.
paint public void paint (Graphics g) Parameters g Graphics context of component. Description Empty method to be overridden in order to draw something in graphics context.
See Also Component, Graphics
Button
http://localhost/java/javaref/awt/ch19_08.htm (2 of 2) [20/12/2001 11:10:30]
CardLayout
[Chapter 19] CardLayout
Chapter 19 java.awt Reference
CardLayout Name CardLayout
Description The CardLayout LayoutManager provides the means to manage multiple components, displaying one at a time. Components are displayed in the order in which they are added to the layout, or in an arbitrary order by using an assignable name.
Class Definition public class java.awt.CardLayout extends java.lang.Object implements java.awt.LayoutManager2, java.io.Serializable { // Constructors public CardLayout(); public CardLayout (int hgap, int vgap); // Instance Methods
http://localhost/java/javaref/awt/ch19_09.htm (1 of 9) [20/12/2001 11:10:33]
[Chapter 19] CardLayout
public void addLayoutComponent (Component comp, Object constraints); public void addLayoutComponent (String name, Component component); public void first (Container parent); public int getHgap(); public abstract float getLayoutAlignmentX(Container target); public abstract float getLayoutAlignmentY(Container target); public int getVgap(); public abstract void invalidateLayout(Container target); public void last (Container parent); public void layoutContainer (Container target); public public public public public public
abstract Dimension maximumLayoutSize(Container target); Dimension minimumLayoutSize (Container target); void next (Container parent); Dimension preferredLayoutSize (Container target); void previous (Container parent); void removeLayoutComponent (Component component);
public void setHgap (int hgap); public void setVgap (int vgap); public void show (Container parent, String name); public String toString(); }
Constructors CardLayout public CardLayout() Description Constructs a CardLayout object. public CardLayout (int hgap, int vgap) Parameters hgap Horizontal space around left and right of container vgap Vertical space around top and bottom of container
http://localhost/java/javaref/awt/ch19_09.htm (2 of 9) [20/12/2001 11:10:33]
[Chapter 19] CardLayout
Description Constructs a CardLayout object with the values specified as the gaps around the container managed by this instance of CardLayout.
Instance Methods addLayoutComponent public void addLayoutComponent (Component comp, Object constraints) Parameters comp The component being added. constraints An object describing the constraints on this component. Implements LayoutManager2.addLayoutComponent() Description Adds the component comp to a container subject to the given constraints. This is a more generalized version of addLayoutComponent(String, Component). It corresponds to java.awt.Container's add(Component, Object). In practice, it is used the same in Java 1.1 as in Java 1.0.2, except with the parameters swapped: Panel p = new Panel(); p.setLayoutManager(new CardLayout()); p.add(new Button("OK"), "Don Julio");
addLayoutComponent public void addLayoutComponent (String name, Component component) Parameters name Name of the component to add. component The actual component being added. Implements LayoutManager.addLayoutComponent() http://localhost/java/javaref/awt/ch19_09.htm (3 of 9) [20/12/2001 11:10:33]
[Chapter 19] CardLayout
Description Places component under the layout's management, assigning it the given name. This has been replaced in version 1.1 with the more general addLayoutComponent(Component, Object).
first public void first (Container parent) Parameters parent The container whose displayed component is changing. Throws IllegalArgumentException If the LayoutManager of parent is not CardLayout. Description Sets the container to display the first component in parent.
getHgap public int getHgap() Returns The horizontal gap for this CardLayout instance.
getLayoutAlignmentX public abstract float getLayoutAlignmentX (Container target) Parameters target The container to inspect. Returns The value .5 for all containers. Description This method returns the preferred alignment of the given container target. A return value of 0 is left aligned, .5 is centered, and 1 is right aligned.
http://localhost/java/javaref/awt/ch19_09.htm (4 of 9) [20/12/2001 11:10:33]
[Chapter 19] CardLayout
getLayoutAlignmentY public abstract float getLayoutAlignmentY (Container target) Parameters target The container to inspect. Returns The value .5 for all containers. Description This method returns the preferred alignment of the given container target. A return value of 0 is top aligned, .5 is centered, and 1 is bottom aligned.
getVgap public int getVgap() Returns The vertical gap for this CardLayout instance.
invalidateLayout public abstract void invalidateLayout (Container target) Parameters target The container to invalidate. Description Does nothing.
last public void last (Container parent) Parameters parent The container whose displayed component is changing. Throws IllegalArgumentException http://localhost/java/javaref/awt/ch19_09.htm (5 of 9) [20/12/2001 11:10:33]
[Chapter 19] CardLayout
If the LayoutManager of parent is not CardLayout. Description Sets the container to display the final component in parent.
layoutContainer public void layoutContainer (Container target) Parameters target The container that needs to be redrawn. Implements LayoutManager.layoutContainer() Description Displays the currently selected component contained within target.
maximumLayoutSize public abstract Dimension maximumLayoutSize (Container target) Parameters target The container to inspect. Returns A Dimension whose horizontal and vertical components are Integer.MAX_VALUE. Description For CardLayout, a maximal Dimension is always returned.
minimumLayoutSize public Dimension minimumLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Minimum Dimension of the container target.
http://localhost/java/javaref/awt/ch19_09.htm (6 of 9) [20/12/2001 11:10:33]
[Chapter 19] CardLayout
Implements LayoutManager.minimumLayoutSize() Description Calculates minimum size of the target container.
next public void next (Container parent) Parameters parent The container whose displayed component is changing. Throws IllegalArgumentException If the LayoutManager of parent is not CardLayout. Description Sets the container to display the following component in the parent.
preferredLayoutSize public Dimension preferredLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Preferred Dimension of the container target. Implements LayoutManager.preferredLayoutSize() Description Calculates preferred size of the target container.
previous public void previous (Container parent) Parameters parent http://localhost/java/javaref/awt/ch19_09.htm (7 of 9) [20/12/2001 11:10:33]
[Chapter 19] CardLayout
The container whose displayed component is changing. Throws IllegalArgumentException If the LayoutManager of parent is not CardLayout. Description Sets the container to display the prior component in parent.
removeLayoutComponent public void removeLayoutComponent (Component component) Parameters component Component to stop tracking. Implements LayoutManager.removeLayoutComponent() Description Removes component from the layout manager's internal tables.
setHgap public void setHgap (int hgap) Parameters hgap The horizontal gap value. Description Sets the horizontal gap for the left and right of the container.
setVgap public void setVgap (int vgap) Parameters vgap The vertical gap value. Description
http://localhost/java/javaref/awt/ch19_09.htm (8 of 9) [20/12/2001 11:10:33]
[Chapter 19] CardLayout
Sets the vertical gap for the top and bottom of the container.
show public void show (Container parent, String name) Parameters parent The container whose displayed component is changing. name Name of component to display. Throws IllegalArgumentException If LayoutManager of parent is not CardLayout. Description Sets the container to display the component name in parent.
toString public String toString() Returns A string representation of the CardLayout object. Overrides Object.toString()
See Also Component, Container, Dimension, LayoutManager, LayoutManager2, Object, String
Canvas
http://localhost/java/javaref/awt/ch19_09.htm (9 of 9) [20/12/2001 11:10:33]
Checkbox
[Chapter 19] Checkbox
Chapter 19 java.awt Reference
Checkbox Name Checkbox
Description The Checkbox is a Component that provides a true or false toggle switch for user input.
Class Definition public class java.awt.Checkbox extends java.awt.Component implements java.awt.ItemSelectable { // Constructors public Checkbox(); public Checkbox (String label); public Checkbox (String label, boolean state); public Checkbox (String label, boolean state, CheckboxGroup group); public Checkbox (String label, CheckboxGroup group, boolean state); // Instance Methods public void addItemListener (ItemListener l); public void addNotify(); public CheckboxGroup getCheckboxGroup(); http://localhost/java/javaref/awt/ch19_10.htm (1 of 7) [20/12/2001 11:10:35]
[Chapter 19] Checkbox
public String getLabel(); public Object[] getSelectedObjects(); public boolean getState(); public public public public
void removeItemListener (ItemListener l); void setCheckboxGroup (CheckboxGroup group); synchronized void setLabel (String label); void setState (boolean state);
// Protected Instance Methods protected String paramString(); protected void processEvent (AWTEvent e); protected void processItemEvent (ItemEvent e); }
Constructors Checkbox public Checkbox() Description Constructs a Checkbox object with no label that is initially false. public Checkbox (String label) Parameters label Text to display with the Checkbox. Description Constructs a Checkbox object with the given label that is initially false. public Checkbox (String label, boolean state) Parameters label Text to display with the Checkbox. state Intial value of the Checkbox. Description Constructs a Checkbox with the given label, initialized to the given state. http://localhost/java/javaref/awt/ch19_10.htm (2 of 7) [20/12/2001 11:10:35]
[Chapter 19] Checkbox
public Checkbox (String label, boolean state, CheckboxGroup group) Parameters label Text to display with the Checkbox. state Intial value of the Checkbox. group The CheckboxGroup this Checkbox should belong to. Description Constructs a Checkbox with the given label, initialized to the given state and belonging to group. public Checkbox (String label, CheckboxGroup group, boolean state) Parameters label Text to display with the Checkbox. group The CheckboxGroup this Checkbox should belong to. state Intial value of the Checkbox. Description Constructs a Checkbox object with the given settings.
Instance Methods addItemListener public void addItemListener (ItemListener l) Parameters l The listener to be added. Implements ItemSelectable.addItemListener(ItemListener l) http://localhost/java/javaref/awt/ch19_10.htm (3 of 7) [20/12/2001 11:10:35]
[Chapter 19] Checkbox
Description Adds a listener for the ItemEvent objects this Checkbox generates.
addNotify public void addNotify() Overrides Component.addNotify() Description Creates Checkbox peer.
getCheckboxGroup public CheckboxGroup getCheckboxGroup() Returns The current CheckboxGroup associated with the Checkbox, if any.
getLabel public String getLabel() Returns The text associated with the Checkbox.
getSelectedObjects public Object[] getSelectedObjects() Implements ItemSelectable.getSelectedObjects() Description If the Checkbox is checked, returns an array with length 1 containing the label of the Checkbox; otherwise returns null.
getState public boolean getState() Returns
http://localhost/java/javaref/awt/ch19_10.htm (4 of 7) [20/12/2001 11:10:35]
[Chapter 19] Checkbox
The current state of the Checkbox.
removeItemListener public void removeItemListener (ItemListener l) Parameters l The listener to be removed. Implements ItemSelectable.removeItemListener (ItemListener l) Description Removes the specified ItemListener so it will not receive ItemEvent objects from this Checkbox.
setCheckboxGroup public void setCheckboxGroup (CheckboxGroup group) Parameters group New group in which to place the Checkbox. Description Associates the Checkbox with a different CheckboxGroup.
setLabel public synchronized void setLabel (String label) Parameters label New text to associate with Checkbox. Description Changes the text associated with the Checkbox.
setState public void setState (boolean state) Parameters
http://localhost/java/javaref/awt/ch19_10.htm (5 of 7) [20/12/2001 11:10:35]
[Chapter 19] Checkbox
state New state for the Checkbox. Description Changes the state of the Checkbox.
Protected Instance Methods paramString protected String paramString() Returns String with current settings of Checkbox. Overrides Component.paramString() Description Helper method for toString() to generate string of current settings.
processEvent protected void processEvent(AWTEvent e) Parameters e The event to process. Description Low level AWTEvents are passed to this method for processing.
processItemEvent protected void processItemEvent(ItemEvent e) Parameters e The item event to process. Description Item events are passed to this method for processing. Normally, this method is called by processEvent().
http://localhost/java/javaref/awt/ch19_10.htm (6 of 7) [20/12/2001 11:10:35]
[Chapter 19] Checkbox
See Also CheckboxGroup, Component, ItemEvent, ItemSelectable, String
CardLayout
http://localhost/java/javaref/awt/ch19_10.htm (7 of 7) [20/12/2001 11:10:35]
CheckboxGroup
[Chapter 19] CheckboxGroup
Chapter 19 java.awt Reference
CheckboxGroup Name CheckboxGroup
Description The CheckboxGroup class provides the means to group multiple Checkbox items into a mutual exclusion set, so that only one checkbox in the set has the value true at any time. The checkbox with the value true is the currently selected checkbox. Mutually exclusive checkboxes usually have a different appearance from regular checkboxes and are also called "radio buttons."
Class Definition public class java.awt.CheckboxGroup extends java.lang.Object implements java.io.Serializable { // Constructors public CheckboxGroup(); // Instance Methods public Checkbox getCurrent(); public Checkbox getSelectedCheckbox() public synchronized void setCurrent (Checkbox checkbox); http://localhost/java/javaref/awt/ch19_11.htm (1 of 3) [20/12/2001 11:10:37]
[Chapter 19] CheckboxGroup
public synchronized void setSelectedCheckbox (Checkbox checkbox); public String toString(); }
Constructors CheckboxGroup public CheckboxGroup() Description Constructs a CheckboxGroup object.
Instance Methods getCurrent public Checkbox getCurrent() Returns The currently selected Checkbox within the CheckboxGroup. Description Replaced by the more aptly named getSelectedCheckbox().
getSelectedCheckbox public Checkbox getSelectedCheckbox() Returns The currently selected Checkbox within the CheckboxGroup.
setCurrent public synchronized void setCurrent (Checkbox checkbox) Parameters checkbox The Checkbox to select. Description
http://localhost/java/javaref/awt/ch19_11.htm (2 of 3) [20/12/2001 11:10:37]
[Chapter 19] CheckboxGroup
Changes the currently selected Checkbox within the CheckboxGroup. Description Replaced by setSelectedCheckbox(Checkbox).
setSelectedCheckbox public synchronized void setSelectedCheckbox (Checkbox checkbox) Parameters checkbox The Checkbox to select. Description Changes the currently selected Checkbox within the CheckboxGroup.
toString public String toString() Returns A string representation of the CheckboxGroup object. Overrides Object.toString()
See Also Checkbox, Object, String
Checkbox
http://localhost/java/javaref/awt/ch19_11.htm (3 of 3) [20/12/2001 11:10:37]
CheckboxMenuItem
[Chapter 19] CheckboxMenuItem
Chapter 19 java.awt Reference
CheckboxMenuItem Name CheckboxMenuItem
Description The CheckboxMenuItem class represents a menu item with a boolean state.
Class Definition public class java.awt.CheckboxMenuItem extends java.awt.MenuItem implements java.awt.ItemSelectable { // Constructors public CheckboxMenuItem(); public CheckboxMenuItem (String label); public CheckboxMenuItem (String label, boolean state); // Instance Methods public void addItemListener (ItemListener l); public void addNotify(); http://localhost/java/javaref/awt/ch19_12.htm (1 of 5) [20/12/2001 11:10:39]
[Chapter 19] CheckboxMenuItem
public Object[] getSelectedObjects(); public boolean getState(); public String paramString(); public void removeItemListener (ItemListener l); public synchronized void setState (boolean condition); // Protected Instance Methods protected void processEvent (AWTEvent e); protected void processItemEvent (ItemEvent e); }
Constructors CheckboxMenuItem public CheckboxMenuItem() Description Constructs a CheckboxMenuItem object with no label. public CheckboxMenuItem (String label) Parameters label Text that appears on CheckboxMenuItem. Description Constructs a CheckboxMenuItem object whose value is initially false. public CheckboxMenuItem (String label, boolean state) Parameters label Text that appears on CheckboxMenuItem. state The initial state of the menu item. Description Constructs a CheckboxMenuItem object with the specified label and state.
http://localhost/java/javaref/awt/ch19_12.htm (2 of 5) [20/12/2001 11:10:39]
[Chapter 19] CheckboxMenuItem
Instance Methods addItemListener public void addItemListener (ItemListener l) Parameters l The listener to be added. Implements ItemSelectable.addItemListener(ItemListener l) Description Adds a listener for the ItemEvent objects this CheckboxMenuItem fires off.
addNotify public void addNotify() Overrides MenuItem.addNotify() Description Creates CheckboxMenuItem's peer.
getSelectedObjects public Object[] getSelectedObjects() Implements ItemSelectable.getSelectedObjects() Description If the CheckboxMenuItem is checked, returns an array with length 1 containing the label of the CheckboxMenuItem; otherwise returns null.
getState public boolean getState() Returns
http://localhost/java/javaref/awt/ch19_12.htm (3 of 5) [20/12/2001 11:10:39]
[Chapter 19] CheckboxMenuItem
The current state of the CheckboxMenuItem.
paramString public String paramString() Returns A string with current settings of CheckboxMenuItem. Overrides MenuItem.paramString() Description Helper method for toString() to generate string of current settings.
removeItemListener public void removeItemListener (ItemListener l) Parameters l The listener to be removed. Implements ItemSelectable.removeItemListener (ItemListener l) Description Removes the specified ItemListener so it will not receive ItemEvent objects from this CheckboxMenuItem.
setState public synchronized void setState (boolean condition) Parameters condition New state for the CheckboxMenuItem. Description Changes the state of the CheckboxMenuItem.
http://localhost/java/javaref/awt/ch19_12.htm (4 of 5) [20/12/2001 11:10:39]
[Chapter 19] CheckboxMenuItem
Protected Instance Methods processEvent protected void processEvent(AWTEvent e) Parameters e The event to process. Overrides MenuItem.processEvent(AWTEvent) Description Low level AWTEvents are passed to this method for processing.
processItemEvent protected void processItemEvent(ItemEvent e) Parameters e The item event to process. Description Item events are passed to this method for processing. Normally, this method is called by processEvent().
See Also ItemEvent, ItemSelectable, MenuItem, String
CheckboxGroup
http://localhost/java/javaref/awt/ch19_12.htm (5 of 5) [20/12/2001 11:10:39]
Choice
[Chapter 19] Choice
Chapter 19 java.awt Reference
Choice Name Choice
Description The Choice is a Component that provides a drop-down list of choices to choose from.
Class Definition public class java.awt.Choice extends java.awt.Component implements java.awt.ItemSelectable { // Constructors public Choice(); // Instance Methods public synchronized void add (String item); public synchronized void addItem (String item); public void addItemListener (ItemListener l); public void addNotify(); public int countItems(); public String getItem (int index); http://localhost/java/javaref/awt/ch19_13.htm (1 of 8) [20/12/2001 11:10:41]
[Chapter 19] Choice
public int getItemCount(); public int getSelectedIndex(); public synchronized String getSelectedItem(); public synchronized Object[] getSelectedObjects(); public synchronized void insert (String item, int index); public synchronized void remove (int position); public synchronized void remove (String item); public synchronized void removeAll(); public void removeItemListener (ItemListener l); public synchronized void select (int pos); public synchronized void select (String str); // Protected Instance Methods protected String paramString(); protected void processEvent (AWTEvent e); protected void processItemEvent (ItemEvent e); }
Constructors Choice public Choice() Description Constructs a Choice object.
Instance Methods add public synchronized void add (String item) Parameters item Text for new entry. Throws NullPointerException
http://localhost/java/javaref/awt/ch19_13.htm (2 of 8) [20/12/2001 11:10:41]
[Chapter 19] Choice
If item is null. Description Adds a new entry to the available choices.
addItem public synchronized void addItem (String item) Parameters item Text for new entry. Throws NullPointerException If item is null. Description Replaced by add(String).
addItemListener public void addItemListener (ItemListener l) Parameters l The listener to be added. Implements ItemSelectable.addItemListener(ItemListener l) Description Adds a listener for the ItemEvent objects this Choice generates.
addNotify public void addNotify() Overrides Component.addNotify() Description Creates Choice's peer.
http://localhost/java/javaref/awt/ch19_13.htm (3 of 8) [20/12/2001 11:10:41]
[Chapter 19] Choice
countItems public int countItems() Returns Number of items in the Choice. Description Replaced by getItemCount().
getItem public String getItem (int index) Parameters index Position of entry. Returns A string for an entry at a given position. Throws ArrayIndexOutOfBoundsException If index is invalid; indices start at zero.
getItemCount public int getItemCount() Returns Number of items in the Choice.
getSelectedIndex public int getSelectedIndex() Returns Position of currently selected entry.
http://localhost/java/javaref/awt/ch19_13.htm (4 of 8) [20/12/2001 11:10:41]
[Chapter 19] Choice
getSelectedItem public synchronized String getSelectedItem() Returns Currently selected entry as a String.
getSelectedObjects public synchronized Object[] getSelectedObjects() Implements ItemSelectable.getSelectedObjects() Description A single-item array containing the current selection.
insert public synchronized void insert (String item, int index) Parameters item The string to add. index The position for the new string. Throws IllegalArgumentException If index is less than zero. Description Inserts item in the given position.
remove public synchronized void remove (int position) Parameters position The index of an entry in the Choice component.
http://localhost/java/javaref/awt/ch19_13.htm (5 of 8) [20/12/2001 11:10:41]
[Chapter 19] Choice
Description Removes the entry in the given position. public synchronized void remove (String string) Parameters string Text of an entry within the Choice component. Throws IllegalArgumentException If string is not in the Choice. Description Makes the first entry that matches string the selected item.
removeAll public synchronized void removeAll() Description Removes all the entries from the Choice.
removeItemListener public void removeItemListener (ItemListener l) Parameters l The listener to be removed. Implements ItemSelectable.removeItemListener (ItemListener l) Description Removes the specified ItemListener so it will not receive ItemEvent objects from this Choice.
http://localhost/java/javaref/awt/ch19_13.htm (6 of 8) [20/12/2001 11:10:41]
[Chapter 19] Choice
select public synchronized void select (int pos) Parameters pos The index of an entry in the Choice component. Throws IllegalArgumentException If the position is not valid. Description Makes the entry in the given position. public synchronized void select (String str) Parameters str Text of an entry within the Choice component. Description Makes the first entry that matches str the selected item for the Choice.
Protected Instance Methods paramString protected String paramString() Returns A string with current settings of Choice. Overrides Component.paramString() Description Helper method for toString() to generate string of current settings.
http://localhost/java/javaref/awt/ch19_13.htm (7 of 8) [20/12/2001 11:10:41]
[Chapter 19] Choice
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description Low level AWTEvents are passed to this method for processing.
processItemEvent protected void processItemEvent (ItemEvent e) Parameters e The item event to process. Description Item events are passed to this method for processing. Normally, this method is called by processEvent().
See Also Component, ItemSelectable, String
CheckboxMenuItem
http://localhost/java/javaref/awt/ch19_13.htm (8 of 8) [20/12/2001 11:10:41]
Color
[Chapter 19] Color
Chapter 19 java.awt Reference
Color Name Color
Description The Color class represents a specific color to the system.
Class Definition public final class java.awt.Color extends java.lang.Object implements java.io.Serializable { // Constants public static public static public static public static public static public static public static public static public static public static public static public static public static
final final final final final final final final final final final final final
Color Color Color Color Color Color Color Color Color Color Color Color Color
black; blue; cyan; darkGray; gray; green; lightGray; magenta; orange; pink; red; white; yellow;
http://localhost/java/javaref/awt/ch19_14.htm (1 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
// Constructors public Color (int rgb); public Color (int red, int green, int blue); public Color (float red, float green, float blue); // Class Methods public static Color decode (String name); public static Color getColor (String name); public static Color getColor (String name, Color defaultColor); public static Color getColor (String name, int defaultColor); public static Color getHSBColor (float hue, float saturation, float brightness); public static int HSBtoRGB (float hue, float saturation, float brightness); public static float[] RGBtoHSB (int red, int green, int blue, float hsbvalues[]); // Instance Methods public Color brighter(); public Color darker(); public boolean equals (Object object); public int getBlue(); public int getGreen(); public int getRed(); public int getRGB(); public int hashCode(); public String toString(); }
Constants black public static final Color black The color black.
blue public static final Color blue The color blue.
cyan public static final Color cyan The color cyan.
http://localhost/java/javaref/awt/ch19_14.htm (2 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
darkGray public static final Color darkGray The color dark gray.
gray public static final Color gray The color gray.
green public static final Color green The color green.
lightGray public static final Color lightGray The color light gray.
magenta public static final Color magenta The color magenta.
orange public static final Color orange The color orange.
pink public static final Color pink The color pink.
red public static final Color red The color red.
http://localhost/java/javaref/awt/ch19_14.htm (3 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
white public static final Color white The color white.
yellow public static final Color yellow The color yellow.
Constructors Color public Color (int rgb) Parameters rgb Composite color value Description Constructs a Color object with the given rgb value. public Color (int red, int green, int blue) Parameters red Red component of color in the range[0, 255] green Green component of color in the range[0, 255] blue Blue component of color in the range[0, 255] Description Constructs a Color object with the given red, green, and blue values. public Color (float red, float green, float blue) Parameters red Red component of color in the range[0.0, 1.0] green Green component of color in the range[0.0, 1.0] http://localhost/java/javaref/awt/ch19_14.htm (4 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
blue Blue component of color in the range[0.0, 1.0] Description Constructs a Color object with the given red, green, and blue values.
Class Methods decode public static Color decode (String nm) Parameters nm A String representing a color as a 24-bit integer. Returns The color requested. Throws NumberFormatException If nm cannot be converted to a number. Description Gets color specified by the given string.
getColor public static Color getColor (String name) Parameters name The name of a system property indicating which color to fetch. Returns Color instance of name requested, or null if the name is invalid. Description Gets color specified by the system property name. public static Color getColor (String name, Color defaultColor) Parameters name The name of a system property indicating which color to fetch. defaultColor http://localhost/java/javaref/awt/ch19_14.htm (5 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
Color to return if name is not found in properties, or invalid. Returns Color instance of name requested, or defaultColor if the name is invalid. Description Gets color specified by the system property name. public static Color getColor (String name, int defaultColor) Parameters name The name of a system property indicating which color to fetch. defaultColor Color to return if name is not found in properties, or invalid. Returns Color instance of name requested, or defaultColor if the name is invalid. Description Gets color specified by the system property name. The default color is specified as a 32-bit RGB value.
getHSBColor public static Color getHSBColor (float hue, float saturation, float brightness) Parameters hue Hue component of Color to create, in the range[0.0, 1.0]. saturation Saturation component of Color to create, in the range[0.0, 1.0]. brightness Brightness component of Color to create, in the range[0.0, 1.0]. Returns Color instance for values provided. Description Create an instance of Color by using hue, saturation, and brightness instead of red, green, and blue values.
HSBtoRGB public static int HSBtoRGB (float hue, float saturation, float brightness) Parameters hue
http://localhost/java/javaref/awt/ch19_14.htm (6 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
Hue component of Color to convert, in the range[0.0, 1.0]. saturation Saturation component of Color to convert, in the range[0.0, 1.0]. brightness Brightness component of Color to convert, in the range[0.0, 1.0]. Returns Color value for hue, saturation, and brightness provided. Description Converts a specific hue, saturation, and brightness to a Color and returns the red, green, and blue values in a composite integer value.
RGBtoHSB public static float[] RGBtoHSB (int red, int green, int blue, float[] hsbvalues) Parameters red Red component of Color to convert, in the range[0, 255]. green Green component of Color to convert, in the range[0, 255]. blue Blue component of Color to convert, in the range[0, 255]. hsbvalues Three element array in which to put the result. This array is used as the method's return object. If null, a new array is allocated. Returns Hue, saturation, and brightness values for Color provided, in elements 0, 1, and 2 (respectively) of the returned array. Description Allows you to convert specific red, green, blue value to the hue, saturation, and brightness equivalent.
Instance Methods brighter public Color brighter() Returns Brighter version of current color.
http://localhost/java/javaref/awt/ch19_14.htm (7 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
Description Creates new Color that is somewhat brighter than current.
darker public Color darker() Returns Darker version of current color. Description Creates new Color that is somewhat darker than current.
equals public boolean equals (Object object) Parameters object The object to compare. Returns true if object represents the same color, false otherwise. Overrides Object.equals(Object) Description Compares two different Color instances for equivalence.
getBlue public int getBlue() Returns Blue component of current color.
getGreen public int getGreen() Returns Green component of current color.
http://localhost/java/javaref/awt/ch19_14.htm (8 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
getRed public int getRed() Returns Red component of current color.
getRGB public int getRGB() Returns Current color as a composite value. Description Gets integer value of current color.
hashCode public int hashCode() Returns A hashcode to use when storing Color in a Hashtable. Overrides Object.hashCode() Description Generates a hashcode for the Color.
toString public String toString() Returns A string representation of the Color object. Overrides Object.toString()
See Also Object, Properties, Serializable, String
Choice
http://localhost/java/javaref/awt/ch19_14.htm (9 of 10) [20/12/2001 11:10:44]
[Chapter 19] Color
http://localhost/java/javaref/awt/ch19_14.htm (10 of 10) [20/12/2001 11:10:44]
[Chapter 19] Component
Chapter 19 java.awt Reference
Component Name Component
Description The Component class is the parent of all non-menu GUI components.
http://localhost/java/javaref/awt/ch19_15.htm (1 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
Class Definition public abstract class java.awt.Component extends java.lang.Object implements java.awt.image.ImageObserver implements java.awt.MenuContainer implements java.io.Serializable { // Constants public final static float BOTTOM_ALIGNMENT; public final static float CENTER_ALIGNMENT; public final static float LEFT_ALIGNMENT; public final static float RIGHT_ALIGNMENT; public final static float TOP_ALIGNMENT; // Variables protected Locale locale; // Constructors protected Component(); // Instance Methods public boolean action (Event e, Object o); public synchronized void add (PopupMenu popup); public synchronized void addComponentListener (ComponentListener l); public synchronized void addFocusListener (FocusListener l); public synchronized void addKeyListener (KeyListener l); public synchronized void addMouseListener (MouseListener l); public synchronized void addMouseMotionListener (MouseMotionListener l); public void addNotify(); public Rectangle bounds(); public int checkImage (Image image, ImageObserver observer); public int checkImage (Image image, int width, int height, ImageObserver observer); public boolean contains (int x, int y); public boolean contains (Point p); public Image createImage (ImageProducer producer); public Image createImage (int width, int height); public void deliverEvent (Event e); public void disable(); http://localhost/java/javaref/awt/ch19_15.htm (2 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
public final void dispatchEvent (AWTEvent e) public void doLayout(); public void enable(); public void enable (boolean condition); public float getAlignmentX(); public float getAlignmentY(); public Color getBackground(); public Rectangle getBounds(); public synchronized ColorModel getColorModel(); public Component getComponentAt (int x, int y); public Component getComponentAt (Point p); public public public public public
Cursor getCursor(); Font getFont(); FontMetrics getFontMetrics (Font f); Color getForeground(); Graphics getGraphics();
public Locale getLocale(); public Point getLocation(); public Point getLocationOnScreen(); public Dimension getMaximumSize(); public Dimension getMinimumSize(); public String getName(); public Container getParent(); public ComponentPeer getPeer(); public Dimension getPreferredSize(); public Dimension getSize(); public Toolkit getToolkit(); public final Object getTreeLock(); public boolean gotFocus (Event e, Object o); public boolean handleEvent (Event e); public void hide(); public boolean imageUpdate (Image image, int infoflags, int x, int y, int width, int height); public boolean inside (int x, int y); public void invalidate(); public boolean isEnabled(); public boolean isFocusTraversable(); public boolean isShowing();
http://localhost/java/javaref/awt/ch19_15.htm (3 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
public boolean isValid(); public boolean isVisible(); public boolean keyDown (Event e, int key); public boolean keyUp (Event e, int key); public public public public
void void void void
layout(); list(); list (PrintStream out); list (PrintStream out, int indentation);
public void list (PrintWriter out); public void list (PrintWriter out, int indentation); public Component locate (int x, int y); public Point location(); public boolean lostFocus (Event e, Object o); public Dimension minimumSize(); public boolean mouseDown (Event e, int x, int y); public boolean mouseDrag (Event e, int x, int y); public boolean mouseEnter (Event e, int x, int y); public boolean mouseExit (Event e, int x, int y); public boolean mouseMove (Event e, int x, int y); public boolean mouseUp (Event e, int x, int y); public void move (int x, int y); public void nextFocus(); public void paint (Graphics g); public void paintAll (Graphics g); public boolean postEvent (Event e); public Dimension preferredSize(); public boolean prepareImage (Image image, ImageObserver observer); public boolean prepareImage (Image image, int width, int height, ImageObserver observer); public void print (Graphics g); public void printAll (Graphics g); public synchronized void remove (MenuComponent popup); public synchronized void removeComponentListener (ComponentListener l); public synchronized void removeFocusListener (FocusListener l); public synchronized void removeKeyListener (KeyListener l); public synchronized void removeMouseListener (MouseListener l); public synchronized void removeMouseMotionListener
http://localhost/java/javaref/awt/ch19_15.htm (4 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
(MouseMotionListener l); public void removeNotify(); public void repaint(); public void repaint (long tm); public void repaint (int x, int y, int width, int height); public void repaint (long tm, int x, int y, int width, int height); public void requestFocus(); public void reshape (int x, int y, int width, int height); public void resize (Dimension d); public void resize (int width, int height); public void setBackground (Color c); public void setBounds (int x, int y, int width, int height); public void setBounds (Rectangle r); public synchronized void setCursor (Cursor cursor); public void setEnabled (boolean b); public synchronized void setFont (Font f); public void setForeground (Color c); public void setLocale (Locale l); public void setLocation (int x, int y); public void setLocation (Point p); public void setName (String name); public void setSize (int width, int height); public void setSize (Dimension d); public void setVisible (boolean b); public void show(); public void show (boolean condition); public Dimension size(); public String toString(); public void transferFocus(); public void update (Graphics g); public void validate(); // Protected Instance Methods protected final void disableEvents (long eventsToDisable); protected final void enableEvents (long eventsToEnable); protected String paramString(); protected void processComponentEvent (ComponentEvent e); protected void processEvent (AWTEvent e); protected void processFocusEvent (FocusEvent e); http://localhost/java/javaref/awt/ch19_15.htm (5 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
protected void processKeyEvent (KeyEvent e); protected void processMouseEvent (MouseEvent e); protected void processMouseMotionEvent (MouseEvent e); }
Constants BOTTOM_ALIGNMENT public final static float BOTTOM_ALIGNMENT Constant representing bottom alignment in getAlignmentY().
CENTER_ALIGNMENT public final static float CENTER_ALIGNMENT Constant representing center alignment in getAlignmentX() and getAlignmentY().
LEFT_ALIGNMENT public final static float LEFT_ALIGNMENT Constant representing left alignment in getAlignmentX().
RIGHT_ALIGNMENT public final static float RIGHT_ALIGNMENT Constant representing right alignment in getAlignmentX().
TOP_ALIGNMENT public final static float TOP_ALIGNMENT Constant representing top alignment in getAlignmentY().
Variables
http://localhost/java/javaref/awt/ch19_15.htm (6 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
locale protected Locale locale Description The locale for the component. Used for internationalization support.
Constructors Component protected Component() Description This constructor creates a "lightweight" component. This constructor allows Component to be directly subclassed using code written entirely in Java.
Instance Methods action public boolean action (Event e, Object o) Parameters e Event instance identifying what triggered the call to this method. o Argument specific to the component subclass that generated the event. Returns true if event handled, false to propagate it to parent container. Description Method called when user performs some action in Component. This method is a relic of the old 1.0.2 event model and is replaced by the process...Event() methods.
add public synchronized void add (PopupMenu popup) Parameters
http://localhost/java/javaref/awt/ch19_15.htm (7 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
popup The menu to add. Description After the PopupMenu is added to a component, it can be shown in the component's coordinate space.
addComponentListener public void addComponentListener (ComponentListener l) Description Adds a listener for the ComponentEvent objects this Component generates.
addFocusListener public void addFocusListener (FocusListener l) Description Adds a listener for the FocusEvent objects this Component generates.
addKeyListener public void addKeyListener (KeyListener l) Description Adds a listener for the KeyEvent objects this Component generates.
addMouseListener public void addMouseListener (MouseListener l) Description Adds a listener for the MouseEvent objects this Component generates.
addMouseMotionListener public void addMouseMotionListener (MouseMotionListener l) Description Adds a listener for the motion MouseEvent objects this Component generates.
http://localhost/java/javaref/awt/ch19_15.htm (8 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
addNotify public void addNotify() Description Creates peer of Component's subclass.
bounds public Rectangle bounds() Returns Gets bounding rectangle of Component. Description A Rectangle that returns the outer limits of the Component. Replaced by getBounds() in 1.1.
checkImage public int checkImage (Image image, ImageObserver observer) Parameters image Image to check. observer The object an image will be rendered onto. Returns ImageObserver Flags ORed together indicating the image's status. Description Checks status of image construction. public int checkImage (Image image, int width, int height, ImageObserver observer) Parameters image Image to check. width Horizontal size image will be scaled to. height http://localhost/java/javaref/awt/ch19_15.htm (9 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
Vertical size image will be scaled to. observer Object image will be rendered onto. Returns ImageObserver flags ORed together indicating the image's status. Description Checks status of image construction.
contains public boolean contains (int x, int y) Parameters x The x coordinate, in this Component's coordinate system. y The y coordinate, in this Component's coordinate system. Returns true if the Component contains the point; false otherwise. public boolean contains (Point p) Parameters p The point to be tested, in this Component's coordinate system. Returns true if the Component contains the point; false otherwise.
createImage public Image createImage (ImageProducer producer) Parameters producer Class that implements ImageProducer interface to create the new image. Returns Newly created image instance.
http://localhost/java/javaref/awt/ch19_15.htm (10 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
Description Creates an Image based upon an ImageProducer. public Image createImage (int width, int height) Parameters width Horizontal size for in-memory Image. height Vertical size for in-memory Image. Returns Newly created image instance. Description Creates an empty in-memory Image for double buffering; to draw on the image, use its graphics context.
deliverEvent public void deliverEvent (Event e) Parameters e Event instance to deliver. Description Delivers event to the component for processing.
disable public void disable() Description Disables component so that it is unresponsive to user interactions. Replaced by setEnabled(false).
dispatchEvent public final void dispatchEvent (AWTEvent e) Parameters
http://localhost/java/javaref/awt/ch19_15.htm (11 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
e The AWTEvent to process. Description Tells the component to deal with the AWTEvent e.
doLayout public void doLayout() Description Lays out component. This method is a replacement for layout().
enable public void enable() Description Enables component so that it is responsive to user interactions. Use setEnabled(true) instead. public void enable (boolean condition) Parameters condition true to enable the component; false to disable it. Description Enables or disables the component based upon condition. Use setEnabled(boolean) instead.
getAlignmentX public float getAlignmentX() Returns A number between 0 and 1 representing the horizontal alignment of this component. Description One of the constants LEFT_ALIGNMENT, CENTER_ALIGNMENT, or RIGHT_ALIGNMENT may be returned. CENTER_ALIGNMENT is returned by default.
http://localhost/java/javaref/awt/ch19_15.htm (12 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
getAlignmentY public float getAlignmentY() Returns A number between 0 and 1 representing the vertical alignment of this component. Description One of the constants TOP_ALIGNMENT, CENTER_ALIGNMENT, or BOTTOM_ALIGNMENT may be returned. CENTER_ALIGNMENT is returned by default.
getBackground public Color getBackground() Returns Background color of the component.
getBounds public Rectangle getBounds() Returns Gets bounding rectangle of Component. Description Returns a Rectangle that returns the outer limits of the Component.
getColorModel public synchronized ColorModel getColorModel() Returns ColorModel used to display the current component.
getComponentAt public Component getComponentAt (int x, int y) Parameters x The x coordinate, in this Component's coordinate system. y http://localhost/java/javaref/awt/ch19_15.htm (13 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
The y coordinate, in this Component's coordinate system. Returns Returns the Component containing the given point. public Component getComponentAt (Point p) Parameters p The point to be tested, in this Component's coordinate system. Returns Returns the Component containing the given point.
getCursor public Cursor getCursor() Returns Current cursor of the component.
getFont public Font getFont() Returns Current font of the component.
getFontMetrics public FontMetrics getFontMetrics (Font f) Parameters f A Font object, whose platform specific information is desired. Returns Size information for the given Font.
http://localhost/java/javaref/awt/ch19_15.htm (14 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
getForeground public Color getForeground() Returns Foreground color of component.
getGraphics public Graphics getGraphics() Throws InternalException If acquiring graphics context is unsupported. Returns Component's graphics context.
getLocale public Locale getLocale() Throws IllegalComponentStateException If the component does not have a locale or it has not been added to a hierarchy that does. Returns Component's locale.
getLocation public Point getLocation() Returns Position of component. Description Gets the current position of this Component in its parent's coordinate space.
getLocationOnScreen public Point getLocationOnScreen()
http://localhost/java/javaref/awt/ch19_15.htm (15 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
Returns Position of component. Description Gets the current position of this Component in the screen's coordinate space.
getMaximumSize public Dimension getMaximumSize() Returns The maximum dimensions of the component. Description By default, a maximal Dimension is returned.
getMinimumSize public Dimension getMinimumSize() Returns The minimum dimensions of the component.
getName public String getName() Returns This component's name.
getParent public Container getParent() Returns Parent Container of Component. Description Gets container that this Component is held in.
http://localhost/java/javaref/awt/ch19_15.htm (16 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
getPeer public ComponentPeer getPeer() Returns Peer of Component.
getPreferredSize public Dimension getPreferredSize() Returns The preferred dimensions of the component.
getSize public Dimension getSize() Returns Dimensions of component. Description Gets width and height of component.
getToolkit public Toolkit getToolkit() Returns Toolkit of Component.
getTreeLock public final Object getTreeLock() Returns The AWT tree locking object. Description Returns the object used for tree locking and layout operations.
http://localhost/java/javaref/awt/ch19_15.htm (17 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
gotFocus public boolean gotFocus (Event e, Object o) Parameters e Event instance identifying what triggered the call to this method. o Argument specific to the component subclass that generated the event. Returns true if event handled, false to propagate it to parent container. Description Called when Component gets input focus. This method is not used in the 1.1 event model.
handleEvent public boolean handleEvent (Event e) Parameters e Event instance identifying what triggered the call to this method. Returns true if event handled, false to propagate it to parent container. Description High-level event handling routine that calls helper routines. Replaced by processEvent(AWTEvent).
hide public void hide() Description Hides component from view. Replaced by setVisible(false).
imageUpdate public boolean imageUpdate (Image image, int infoflags, int x, int y, int width, int height) Parameters
http://localhost/java/javaref/awt/ch19_15.htm (18 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
image Image being loaded. infoflags ImageObserver flags ORed together of available information. x x coordinate of upper-left corner of Image. y y coordinate of upper-left corner of Image. width Horizontal dimension of Image. height Vertical dimension of Image. Returns true if Image fully loaded, false otherwise. Implements ImageObserver.imageUpdate() Description An asynchronous update interface for receiving notifications about Image information as it is loaded. Meaning of parameters changes with values of flags.
inside public boolean inside (int x, int y) Parameters x Horizontal position. y Vertical position. Returns true if the point (x, y) falls within the component's bounds, false otherwise. Description Checks if coordinates are within bounding box of Component. Replaced by contains(int, int).
http://localhost/java/javaref/awt/ch19_15.htm (19 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
invalidate public void invalidate() Description Sets the component's valid state to false.
isEnabled public boolean isEnabled() Returns true if enabled, false otherwise. Description Checks to see if the Component is currently enabled.
isFocusTraversable public boolean isFocusTraversable() Returns true if this Component can be traversed using Tab and Shift-Tab, false otherwise. Description Checks to see if the Component is navigable using the keyboard.
isShowing public boolean isShowing() Returns true if showing, false otherwise. Description Checks to see if the Component is currently showing.
isValid public boolean isValid() Returns true if valid, false otherwise. Description http://localhost/java/javaref/awt/ch19_15.htm (20 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
Checks to see if the Component is currently valid.
isVisible public boolean isVisible() Returns true if visible, false otherwise. Description Checks to see if the Component is currently visible.
keyDown public boolean keyDown (Event e, int key) Parameters e Event instance identifying what triggered the call to this method. key Integer representation of key pressed. Returns true if event handled, false to propagate it to parent container. Description Method called whenever the user presses a key. Replaced by processKeyEvent(KeyEvent).
keyUp public boolean keyUp (Event e, int key) Parameters e Event instance identifying what triggered the call to this method. key Integer representation of key released. Returns true if event handled, false to propagate it to parent container. Description
http://localhost/java/javaref/awt/ch19_15.htm (21 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
Method called whenever the user releases a key. Replaced by processKeyEvent(KeyEvent).
layout public void layout() Description Lays out component. Replaced by doLayout().
list public void list() Description Prints the contents of the Component to System.out. public void list (PrintStream out) Parameters out Output stream to send results to. Description Prints the contents of the Component to a PrintStream. public void list (PrintStream out, int indentation) Parameters out Output stream to send results to. indentation Indentation to use when printing. Description Prints the contents of the Component indented to a PrintStream. public void list (PrintWriter out) Parameters out Output stream to send results to. Description
http://localhost/java/javaref/awt/ch19_15.htm (22 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
Prints the contents of the Component to a PrintWriter. public void list (PrintWriter out, int indentation) Parameters out Output stream to send results to. indentation Indentation to use when printing. Description Prints the contents of the Component indented to a PrintWriter.
locate public Component locate (int x, int y) Parameters x Horizontal position. y Vertical position. Returns Component if the point (x, y) falls within the component, null otherwise. Description Replaced by getComponentAt(int, int).
location public Point location() Returns Position of component. Description Gets the current position of this Component in its parent's coordinate space. Replaced by getLocation().
http://localhost/java/javaref/awt/ch19_15.htm (23 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
lostFocus public boolean lostFocus (Event e, Object o) Parameters e Event instance identifying what triggered the call to this method. o Argument specific to the component subclass that generated the event. Returns true if event handled, false to propagate it to parent container. Description Method called when Component loses input focus. Replaced by processFocusEvent(FocusEvent).
minimizeSize public Dimension minimumSize() Returns The minimum dimensions of the component. Replaced by getMinimumSize().
mouseDown public boolean mouseDown (Event e, int x, int y) Parameters e Event instance identifying what triggered the call to this method. x Horizontal position of the mouse within Component when Event initiated y Vertical position of the mouse within Component when Event initiated Returns true if event handled, false to propagate it to parent container. Description Method called when the user presses a mouse button over Component. Replaced by
http://localhost/java/javaref/awt/ch19_15.htm (24 of 42) [20/12/2001 11:10:53]
[Chapter 19] Component
processMouseEvent(MouseEvent).
mouseDrag public boolean mouseDrag (Event e, int x, int y) Parameters e Event instance identifying what triggered the call to this method. x Horizontal position of the mouse within Component when Event initiated y Vertical position of the mouse within Component when Event initiated Returns true if event handled, false to propagate it to parent container. Description Method called when the user is pressing a mouse button and moves the mouse. Replaced by processMouseMotionEvent(MouseEvent).
mouseEnter public boolean mouseEnter (Event e, int x, int y) Parameters e Event instance identifying what triggered the call to this method. x Horizontal position of the mouse within Component when Event initiated y Vertical position of the mouse within Component when Event initiated Returns true if event handled, false to propagate it to parent container. Description Method called when the mouse enters Component. Replaced by processMouseEvent(MouseEvent).
http://localhost/java/javaref/awt/ch19_15.htm (25 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
mouseExit public boolean mouseExit (Event e, int x, int y) Parameters e Event instance identifying what triggered the call to this method. x Horizontal position of the mouse within Component when Event initiated y Vertical position of the mouse within Component when Event initiated Returns true if event handled, false to propagate it to parent container. Description Method called when the mouse exits Component. Replaced by processMouseEvent(MouseEvent).
mouseMove public boolean mouseMove (Event e, int x, int y) Parameters e Event instance identifying what triggered the call to this method. x Horizontal position of the mouse within Component when Event initiated y Vertical position of the mouse within Component when Event initiated Returns true if event handled, false to propagate it to parent container. Description Method called when the user is not pressing a mouse button and moves the mouse. Replaced by processMouseMotionEvent(MouseEvent).
http://localhost/java/javaref/awt/ch19_15.htm (26 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
mouseUp public boolean mouseUp (Event e, int x, int y) Parameters e Event instance identifying what triggered the call to this method. x Horizontal position of the mouse within Component when Event initiated y Vertical position of the mouse within Component when Event initiated Returns true if event is handled, false to propagate it to the parent container. Description Method called when user releases mouse button over Component. Replaced by processMouseEvent(MouseEvent).
move public void move (int x, int y) Parameters x New horizontal position for component. y New vertical position for component. Description Relocates component. Replaced by setLocation(int, int).
nextFocus public void nextFocus() Description Moves focus from current component to next one in parent container. Replaced by transferFocus().
http://localhost/java/javaref/awt/ch19_15.htm (27 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
paint public void paint (Graphics g) Parameters g Graphics context of component. Description Empty method to be overridden to draw something in the graphics context.
paintAll public void paintAll (Graphics g) Parameters g Graphics context of component. Description Method to validate component and paint its peer if it is visible.
postEvent public boolean postEvent (Event e) Parameters e Event instance to post to component Returns If Event is handled, true is returned. Otherwise, false is returned. Description Tells Component to deal with Event.
preferredSize public Dimension preferredSize() Returns The preferred dimensions of the component. Replaced by getPreferredSize().
http://localhost/java/javaref/awt/ch19_15.htm (28 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
prepareImage public boolean prepareImage (Image image, ImageObserver observer) Parameters image Image to start loading. observer Component on which image will be rendered. Returns true if Image is fully loaded, false otherwise. Description Forces Image to start loading. public boolean prepareImage (Image image, int width, int height, ImageObserver observer) Parameters image Image to start loading. width Horizontal size of the Image after scaling. height Vertical size of the Image after scaling. observer Component on which image will be rendered. Returns true if Image is fully loaded, false otherwise. Description Forces Image to start loading.
print public void print (Graphics g) Parameters g Graphics context.
http://localhost/java/javaref/awt/ch19_15.htm (29 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
Description Empty method to be overridden to print something into the graphics context.
printAll public void printAll (Graphics g) Parameters g Graphics context. Description Method to print this component and its children.
remove public void remove (MenuComponent popup) Parameters popup The menu to remove. Description After adding a PopupMenu, you can use this method to remove it.
removeComponentListener public void removeComponentListener (ComponentListener l) Description Removes the specified ComponentListener from this Component.
removeFocusListener public void removeFocusListener (FocusListener l) Description Removes the specified FocusListener from this Component.
http://localhost/java/javaref/awt/ch19_15.htm (30 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
removeKeyListener public void removeKeyListener (KeyListener l) Description Removes the specified KeyListener from this Component.
removeMouseListener public void removeMouseListener (MouseListener l) Description Removes the specified MouseListener from this Component.
removeMouseMotionListener public void removeMouseMotionListener (MouseMotionListener l) Description Removes the specified MouseMotionListener from this Component.
removeNotify public void removeNotify() Description Removes peer of Component's subclass.
repaint public void repaint() Description Requests scheduler to redraw the component as soon as possible. public void repaint (long tm) Parameters tm Millisecond delay allowed before repaint. Description
http://localhost/java/javaref/awt/ch19_15.htm (31 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
Requests scheduler to redraw the component within a time period. public void repaint (int x, int y, int width, int height) Parameters x Horizontal origin of bounding box to redraw. y Vertical origin of bounding box to redraw. width Width of bounding box to redraw. height Height of bounding box to redraw. Description Requests scheduler to redraw a portion of component as soon as possible. public void repaint (long tm, int x, int y, int width, int height) Parameters tm Millisecond delay allowed before repaint. x Horizontal origin of bounding box to redraw. y Vertical origin of bounding box to redraw. width Width of bounding box to redraw. height Height of bounding box to redraw. Description Requests scheduler to redraw a portion of component within a time period.
requestFocus public void requestFocus() Description
http://localhost/java/javaref/awt/ch19_15.htm (32 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
Requests the input focus for this Component.
reshape public void reshape (int x, int y, int width, int height) Parameters x New horizontal position for component. y New vertical position for component. width New width for component. height New height for component. Description Relocates and resizes component. Replaced by setBounds(int, int, int, int).
resize public void resize (Dimension d) Parameters d New dimensions for the component. Description Resizes component. Replaced by setSize(Dimension). public void resize (int width, int height) Parameters width New width for component. height New height for component. Description Resizes component. Replaced by setSize(int, int).
http://localhost/java/javaref/awt/ch19_15.htm (33 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
setBackground public void setBackground (Color c) Parameters c New background color. Description Changes the component's background color.
setBounds public void setBounds (int x, int y, int width, int height) Parameters x New horizontal position for component. y New vertical position for component. width New width for component. height New height for component. Description Relocates and resizes the component. public void setBounds (Rectangle r) Parameters r New coordinates for component. Description Relocates and resizes component.
http://localhost/java/javaref/awt/ch19_15.htm (34 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
setCursor public synchronized void setCursor (Cursor cursor) Parameters cursor The new cursor for the component. Description Changes the component's cursor.
setEnabled public void setEnabled (boolean b) Parameters b true to enable the component, false to disable it. Description Enables or disables the component. Replaces enable(), enable(boolean), and disable().
setFont public synchronized void setFont (Font f) Parameters f Font to change component to. Description Changes the font of the component.
setForeground public void setForeground (Color c) Parameters c New foreground color. Description Changes the foreground color of component's area.
http://localhost/java/javaref/awt/ch19_15.htm (35 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
setLocale public void setLocale (Locale l) Parameters l The locale object for the component. Description Sets the Component's locale.
setLocation public void setLocation (int x, int y) Parameters x New horizontal position for component. y New vertical position for component. Description Relocates the component. public void setLocation (Point p) Parameters p New position for component. Description Relocates the component.
setName public void setName (String name) Parameters name New name for component. Description
http://localhost/java/javaref/awt/ch19_15.htm (36 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
Sets the component's name.
setSize public void setSize (int width, int height) Parameters width New width for component. height New height for component. Description Resizes the component. public void setSize (Dimension d) Parameters d New dimensions for the component. Description Resizes the component.
setVisible public void setVisible (boolean b) Parameters b true to show component, false to hide it. Description Shows or hides the component based on the b parameter.
show public void show() Description Replaced by setVisible(true).
http://localhost/java/javaref/awt/ch19_15.htm (37 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
public void show (boolean condition) Parameters condition true to show the component, false to hide it. Description Replaced by setVisible(boolean).
size public Dimension size() Returns Dimensions of the component. Description Gets width and height of the component. Replaced by getSize().
toString public String toString() Returns A string representation of the Component object. Overrides Object.toString()
transferFocus public void transferFocus() Description Transfers focus to the next component in the container hierarchy.
update public void update (Graphics g) Parameters g Graphics context of component. http://localhost/java/javaref/awt/ch19_15.htm (38 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
Description Called to update the component's display area.
validate public void validate() Description Sets the component's valid state to true.
Protected Instance Methods disableEvents protected final void disableEvents (long eventsToDisable) Parameters eventsToDisable A value representing certain kinds of events. This can be constructed by ORing the event mask constants defined in java.awt.AWTEvent. Description By default, a component receives events corresponding to the event listeners that have registered. If a component should not receive events of a certain type, even if there is a listener registered for that type of event, this method can be used to disable that event type.
enableEvents protected final void enableEvents (long eventsToEnable) Parameters eventsToEnable A value representing certain kinds of events. This can be constructed by ORing the event mask constants defined in java.awt.AWTEvent. Description By default, a component receives events corresponding to the event listeners that have registered. If a component should receive other types of events as well, this method can be used to request them.
http://localhost/java/javaref/awt/ch19_15.htm (39 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
paramString protected String paramString() Returns A String with the current settings of the Component. Description Helper method for toString() to generate a string of current settings.
processComponentEvent protected void processComponentEvent(ComponentEvent e) Parameters e The event to process. Description Component events are passed to this method for processing. Normally, this method is called by processEvent().
processEvent protected void processEvent(AWTEvent e) Parameters e The event to process. Description Low level AWTEvents are passed to this method for processing.
processFocusEvent protected void processFocusEvent(FocusEvent e) Parameters e The event to process. Description Focus events are passed to this method for processing. Normally, this method is called by
http://localhost/java/javaref/awt/ch19_15.htm (40 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
processEvent().
processKeyEvent protected void processKeyEvent(KeyEvent e) Parameters e The event to process. Description Key events are passed to this method for processing. Normally, this method is called by processEvent().
processMouseEvent protected void processMouseEvent(MouseEvent e) Parameters e The event to process. Description Mouse events are passed to this method for processing. Normally, this method is called by processEvent().
processMouseMotionEvent protected void processMouseMotionEvent(MouseEvent e) Parameters e The event to process. Description Mouse motion events are passed to this method for processing. Normally, this method is called by processEvent().
See Also Button, Canvas, Checkbox, Choice, Color, ColorModel, ComponentPeer, Container, Dimension, Event, Font, FontMetrics, Graphics, ImageObserver, ImageProducer, Label, List, MenuContainer, Object, Point, PrintStream, Rectangle, Scrollbar, http://localhost/java/javaref/awt/ch19_15.htm (41 of 42) [20/12/2001 11:10:54]
[Chapter 19] Component
Serializable, String, TextComponent, Toolkit
Color
http://localhost/java/javaref/awt/ch19_15.htm (42 of 42) [20/12/2001 11:10:54]
Container
[Chapter 19] Container
Chapter 19 java.awt Reference
Container Name Container
Description The Container class serves as a general purpose holder of other Component objects.
Class Definition public abstract class java.awt.Container extends java.awt.Component { // Constructors protected Container(); // Instance Methods public Component add (Component component); public Component add (Component component, int position); public void add (Component comp, Object constraints); http://localhost/java/javaref/awt/ch19_16.htm (1 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
public void add (Component comp, Object constraints, int position); public Component add (String name, Component component); public void addContainerListener (ContainerListener l); public void addNotify(); public int countComponents(); public void deliverEvent (Event e); public void doLayout(); public float getAlignmentX(); public float getAlignmentY(); public Component getComponent (int n); public Component getComponentAt (int x, int y); public Component getComponentAt (Point p); public int getComponentCount(); public Component[] getComponents(); public Insets getInsets(); public LayoutManager getLayout(); public Dimension getMaximumSize(); public Dimension getMinimumSize(); public Dimension getPreferredSize(); public Insets insets(); public void invalidate(); public boolean isAncestorOf (Component c); public void layout(); public void list (PrintStream out, int indentation); public void list (PrintWriter out, int indentation); public Component locate (int x, int y); public Dimension minimumSize(); public void paint (Graphics g); public void paintComponents (Graphics g); public Dimension preferredSize(); public void print (Graphics g); public void printComponents (Graphics g); public void remove (int index); public void remove (Component component); public void removeAll(); public void removeContainerListener (ContainerListener l);
http://localhost/java/javaref/awt/ch19_16.htm (2 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
public void removeNotify(); public void setLayout (LayoutManager manager); public void validate(); // Protected Instance Methods protected void addImpl (Component comp, Object constraints, int index); protected String paramString(); protected void processContainerEvent (ContainerEvent e); protected void processEvent (AWTEvent e); protected void validateTree(); }
Constructors Container protected Container() Description This constructor creates a "lightweight" container. This constructor allows Container to be subclassed using code written entirely in Java.
Instance Methods add public Component add (Component component) Parameters component Component to add to container. Returns Component just added. Throws IllegalArgumentException if you add component to itself. Description Adds component as the last component in the container. public Component add (Component component, int position) http://localhost/java/javaref/awt/ch19_16.htm (3 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
Parameters component Component to add to container. position Position of component; -1 adds the component as the last in the container. Returns Component just added. Throws ArrayIndexOutOfBoundsException If position invalid. IllegalArgumentException If you add Component to itself. Description Adds component to container at a certain position. public void add (Component component, Object constraints) Parameters component Component to add to container. constraints An object describing constraints on the component being added. Description Adds component to container subject to contraints. public void add (Component component, Object constraints, int index) Parameters component Component to add to container. constraints An object describing constraints on the component being added. index The position of the component in the container's list. http://localhost/java/javaref/awt/ch19_16.htm (4 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
Description Adds component to container subject to contraints at position index. public Component add (String name, Component component) Parameters name Name of component being added. This parameter is often significant to the layout manager of the container (e.g "North", "Center"). component Component to add to container. Returns Component just added. Throws IllegalArgumentException If you add component to itself. Description Adds the component to the container with the given name. Replaced by the more general add(Component, Object).
addContainerListener public void addContainerListener (ContainerListener l) Parameters l An object that implements the ContainerListener interface. Description Add a listener for the container events.
addNotify public void addNotify() Overrides Component.addNotify() Description
http://localhost/java/javaref/awt/ch19_16.htm (5 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
Creates Container's peer and peers of contained components.
countComponents public int countComponents() Returns Number of components within Container.
deliverEvent public void deliverEvent (Event e) Parameters e Event instance to deliver. Overrides Component.deliverEvent(Event) Description Tries to locate the component contained in the container that should receive the event.
doLayout public void doLayout() Description Lays out the container. This method is a replacement for layout().
getAlignmentX public float getAlignmentX() Returns A number between 0 and 1 representing the horizontal alignment of this component. Overrides Component.getAlignmentX() Description If the container's layout manager implements LayoutManager2, this method returns the getLayoutAlignmentX() value of the layout manager. Otherwise the getAlignmentX() http://localhost/java/javaref/awt/ch19_16.htm (6 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
value of Component is returned.
getAlignmentY public float getAlignmentY() Returns A number between 0 and 1 representing the vertical alignment of this component. Overrides Component.getAlignmentY() Description If the container's layout manager implements LayoutManager2, this method returns the getLayoutAlignmentY() value of the layout manager. Otherwise the getAlignmentY() value of Component is returned.
getComponent public synchronized Component getComponent (int position) Parameters position Position of component to get. Throws ArrayIndexOutOfBoundsException If position is invalid. Returns Component at designated position within Container.
getComponentAt public Component getComponentAt (int x, int y) Parameters x The x coordinate, in this Container's coordinate system. y The y coordinate, in this Container's coordinate system. Returns http://localhost/java/javaref/awt/ch19_16.htm (7 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
Returns the Component containing the give point. public Component getComponentAt (Point p) Parameters p The point to be tested, in this Container's coordinate system. Returns Returns the Component containing the give point.
getComponentCount public int getComponentCount() Returns Returns the number of components in the container.
getComponents public Component[] getComponents() Returns Array of components within the container.
getInsets public Insets getInsets() Returns The insets of the container.
getLayout public LayoutManager getLayout() Returns LayoutManager of Container.
http://localhost/java/javaref/awt/ch19_16.htm (8 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
getMaximumSize public Dimension getMaximumSize() Overrides Component.getMaximumSize() Returns The maximum dimensions of the component.
getMinimumSize public Dimension getMinimumSize() Overrides Component.getMinimumSize() Returns The minimum dimensions of the component.
getPreferredSize public Dimension getPreferredSize() Returns The preferred dimensions of the component.
insets public Insets insets() Returns Current Insets of Container. Replaced by getInsets().
invalidate public void invalidate() Overrides Component.invalidate() Description
http://localhost/java/javaref/awt/ch19_16.htm (9 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
Sets the container's valid state to false.
isAncestorOf public boolean isAncestorOf (Component c) Parameters c The component in question. Returns If c is contained in the container's hierarchy, returns true; otherwise false.
layout public void layout() Overrides Component.layout() Description Replaced by doLayout().
list public void list (PrintStream out, int indentation) Parameters out Output Stream to send results to. indentation Indentation to use when printing. Overrides Component.list(PrintStream, int) Description Recursively lists all components in Container. public void list (PrintWriter out, int indentation) Parameters
http://localhost/java/javaref/awt/ch19_16.htm (10 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
out Output Writer to send results to. indentation Indentation to use when printing. Overrides Component.list(PrintWriter, int) Description Recursively lists all components in Container.
locate public Component locate (int x, int y) Parameters x Horizontal position to check. y Vertical position to check. Returns Component within Container at given coordinates, or Container. Overrides Component.locate(int, int) Description Replaced by getComponentAt(int, int).
minimizeSize public Dimension minimumSize() Returns Minimum dimensions of contained objects. Overrides Component.minimumSize() Description Replaced by getMinimumSize().
http://localhost/java/javaref/awt/ch19_16.htm (11 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
paint public void paint (Graphics g) Parameters g Graphics context of container. Overrides Component.paint() Description This method tells any lightweight components that are children of this container to paint themselves.
paintComponents public void paintComponents (Graphics g) Parameters g Graphics context of Container. Description Paints the different components in Container.
preferredSize public Dimension preferredSize() Returns Preferred dimensions of contained objects. Overrides Component.preferredSize() Description Replaced by getPreferredSize().
http://localhost/java/javaref/awt/ch19_16.htm (12 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
print public void print (Graphics g) Parameters g Graphics context of container. Overrides Component.print() Description This method tells any lightweight components that are children of this container to print themselves.
printComponents public void printComponents (Graphics g) Parameters g Graphics context of Container. Description Prints the different components in Container.
remove public void remove (int index) Parameters index Index of the component to remove. Description Removes the component in position index from Container. public void remove (Component component) Parameters component Component to remove.
http://localhost/java/javaref/awt/ch19_16.htm (13 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
Description Removes component from Container.
removeAll public void removeAll() Description Removes all components from Container.
removeContainerListener public void removeContainerListener (ContainerListener l) Parameters l One of this Container's ContainerListeners. Description Remove a container event listener.
removeNotify public void removeNotify() Overrides Component.removeNotify() Description Removes Container's peer and peers of contained components.
setLayout public void setLayout (LayoutManager manager) Parameters manager New LayoutManager for Container. Description Changes LayoutManager of Container.
http://localhost/java/javaref/awt/ch19_16.htm (14 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
validate public void validate() Overrides Component.validate() Description Sets Container's valid state to true and recursively validates its children.
Protected Instance Methods addImpl protected void addImpl (Component comp, Object constraints, int index) Parameters comp The component to add. constraints Constraints on the component. index Position at which to add this component. Pass -1 to add the component at the end. Description This method adds a component subject to the given constraints at a specific position in the container's list of components. It is a helper method for the various overrides of add().
paramString protected String paramString() Returns String with current settings of Container. Overrides Component.paramString() Description Helper method for toString() to generate string of current settings.
http://localhost/java/javaref/awt/ch19_16.htm (15 of 17) [20/12/2001 11:10:58]
[Chapter 19] Container
processContainerEvent protected void processContainerEvent (ContainerEvent e) Parameters e The event to process. Description Container events are passed to this method for processing. Normally, this method is called by processEvent().
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Overrides Component.processEvent() Description Low level AWTEvents are passed to this method for processing.
validateTree protected void validateTree() Description Descends recursively into the Container's components and recalculates layout for any subtrees that are marked invalid.
See Also Component, Dimension, Event, Graphics, Insets, LayoutManager, Panel, PrintStream, String, Window
Component
http://localhost/java/javaref/awt/ch19_16.htm (16 of 17) [20/12/2001 11:10:58]
Cursor
[Chapter 19] Container
http://localhost/java/javaref/awt/ch19_16.htm (17 of 17) [20/12/2001 11:10:58]
[Chapter 19] Cursor
Chapter 19 java.awt Reference
Cursor Name Cursor
Description The Cursor class represents the mouse pointer. It encapsulates information that used to be in java.awt.Frame in the 1.0.2 release.
Class Definition public class java.awt.Cursor extends java.lang.Object implements java.io.Serializable { // Constants public final static int CROSSHAIR_CURSOR; public final static int DEFAULT_CURSOR; public final static int E_RESIZE_CURSOR; public final static int HAND_CURSOR; public final static int MOVE_CURSOR; public final static int N_RESIZE_CURSOR; public final static int NE_RESIZE_CURSOR; public final static int NW_RESIZE_CURSOR; public final static int S_RESIZE_CURSOR; public final static int SE_RESIZE_CURSOR; http://localhost/java/javaref/awt/ch19_17.htm (1 of 5) [20/12/2001 11:11:00]
[Chapter 19] Cursor
public final static int SW_RESIZE_CURSOR; public final static int TEXT_CURSOR; public final static int W_RESIZE_CURSOR; public final static int WAIT_CURSOR; // Class Variables protected static Cursor[] predefined; // Class Methods public static Cursor getDefaultCursor(); public static Cursor getPredefinedCursor (int type); // Constructors public Cursor (int type); // Instance Methods public int getType(); }
Constants CROSSHAIR_CURSOR public final static int CROSSHAIR_CURSOR Constant representing a cursor that looks like a crosshair.
DEFAULT_CURSOR public final static int DEFAULT_CURSOR Constant representing the platform's default cursor.
E_RESIZE_CURSOR public final static int E_RESIZE_CURSOR Constant representing the cursor for resizing an object on the left.
HAND_CURSOR public final static int HAND_CURSOR Constant representing a cursor that looks like a hand.
http://localhost/java/javaref/awt/ch19_17.htm (2 of 5) [20/12/2001 11:11:00]
[Chapter 19] Cursor
MOVE_CURSOR public final static int MOVE_CURSOR Constant representing a cursor used to move an object.
N_RESIZE_CURSOR public final static int N_RESIZE_CURSOR Constant representing a cursor for resizing an object on the top.
NE_RESIZE_CURSOR public final static int NE_RESIZE_CURSOR Constant representing a cursor for resizing an object on the top left corner.
NW_RESIZE_CURSOR public final static int NW_RESIZE_CURSOR Constant representing a cursor for resizing an object on the top right corner.
S_RESIZE_CURSOR public final static int S_RESIZE_CURSOR Constant representing a cursor for resizing an object on the bottom.
SE_RESIZE_CURSOR public final static int SE_RESIZE_CURSOR Constant representing a cursor for resizing an object on the bottom left corner.
SW_RESIZE_CURSOR public final static int SW_RESIZE_CURSOR Constant representing a cursor for resizing an object on the bottom right corner.
http://localhost/java/javaref/awt/ch19_17.htm (3 of 5) [20/12/2001 11:11:00]
[Chapter 19] Cursor
TEXT_CURSOR public final static int TEXT_CURSOR Constant representing a cursor used within text.
W_RESIZE_CURSOR public final static int W_RESIZE_CURSOR Constant representing a cursor for resizing an object on the right side.
WAIT_CURSOR public final static int WAIT_CURSOR Constant representing a cursor that indicates the program is busy.
Class Variables predefined protected static Cursor[] predefined An array of cursor instances corresponding to the predefined cursor types.
Class Methods getDefaultCursor public static Cursor getDefaultCursor() Returns The default system cursor.
getPredefinedCursor public static Cursor getPredefinedCursor (int type) Parameters type One of the type constants defined in this class. Returns http://localhost/java/javaref/awt/ch19_17.htm (4 of 5) [20/12/2001 11:11:00]
[Chapter 19] Cursor
A Cursor object with the specified type.
Constructors Cursor public Cursor (int type) Parameters type One of the type constants defined in this class. Description Constructs a Cursor object with the specified type.
Instance Methods getType public int getType() Returns The type of cursor.
See Also Frame
Container
http://localhost/java/javaref/awt/ch19_17.htm (5 of 5) [20/12/2001 11:11:00]
Dialog
[Chapter 19] Dialog
Chapter 19 java.awt Reference
Dialog Name Dialog
Description The Dialog class provides a special type of display window that is used for pop-up messages and acquiring input from the user. Unlike most other components, dialogs are hidden by default; you must call show() to display them. Dialogs are always associated with a parent Frame. A Dialog may be either modal or non-modal; a modal dialog attracts all input typed by the user. The default layout for a Dialog is BorderLayout.
Class Definition public class java.awt.Dialog extends java.awt.Window { // Constructors public Dialog (Frame parent); public Dialog (Frame parent, boolean modal); public Dialog (Frame parent, String title); public Dialog (Frame parent, String title, boolean modal); http://localhost/java/javaref/awt/ch19_18.htm (1 of 6) [20/12/2001 11:11:03]
[Chapter 19] Dialog
// Instance Methods public void addNotify(); public String getTitle(); public boolean isModal(); public boolean isResizable(); public void setModal (boolean b); public synchronized void setResizable (boolean resizable); public synchronized void setTitle (String title); public void show(); // Protected Instance Methods protected String paramString(); }
Constructors Dialog public Dialog (Frame parent) Parameters parent Frame that is to act as the parent of Dialog. Throws IllegalArgumentException If parent is null. Description Constructs a Dialog object. public Dialog (Frame parent, boolean modal) Parameters parent Frame that is to act as the parent of Dialog. modal true if the Dialog is modal; false otherwise. Throws IllegalArgumentException http://localhost/java/javaref/awt/ch19_18.htm (2 of 6) [20/12/2001 11:11:03]
[Chapter 19] Dialog
If parent is null. Description Replaced with Dialog(Frame, String, boolean). public Dialog (Frame parent, String title) Parameters parent Frame that is to act as parent of Dialog. title Initial title to use for Dialog. Throws IllegalArgumentException If parent is null. Description Constructs a Dialog object with given characteristics. public Dialog (Frame parent, String title, boolean modal) Parameters parent Frame that is to act as parent of Dialog. title Initial title to use for Dialog. modal true if the Dialog is modal; false otherwise. Throws IllegalArgumentException If parent is null. Description Constructs a Dialog object with given characteristics.
http://localhost/java/javaref/awt/ch19_18.htm (3 of 6) [20/12/2001 11:11:03]
[Chapter 19] Dialog
Instance Methods addNotify public void addNotify() Overrides Window.addNotify() Description Creates Dialog's peer and peers of contained components.
getTitle public String getTitle() Returns The current title for the Dialog.
isModal public boolean isModal() Returns true if modal, false otherwise.
isResizable public boolean isResizable() Returns true if resizable, false otherwise.
setModal public void setModal (boolean b) Parameters b true makes the Dialog modal; false if the Dialog should be modeless. Description
http://localhost/java/javaref/awt/ch19_18.htm (4 of 6) [20/12/2001 11:11:03]
[Chapter 19] Dialog
Changes the modal state of the Dialog.
setResizable public synchronized void setResizable (boolean resizable) Parameters resizable true makes the Dialog resizable; false if the Dialog cannot be resized. Description Changes the resize state of the Dialog.
setTitle public synchronized void setTitle (String title) Parameters title New title for the Dialog. Description Changes the title of the Dialog.
show public void show() Overrides Window.show() Description If the dialog is hidden, this method shows it. If the dialog is already visible, this method brings it to the front.
Protected Instance Methods paramString protected String paramString() Returns
http://localhost/java/javaref/awt/ch19_18.htm (5 of 6) [20/12/2001 11:11:03]
[Chapter 19] Dialog
String with current settings of Dialog. Overrides Container.paramString() Description Helper method for toString() to generate string of current settings.
See Also FileDialog, Frame, String, Window, WindowEvent, WindowListener
Cursor
http://localhost/java/javaref/awt/ch19_18.htm (6 of 6) [20/12/2001 11:11:03]
Dimension
[Chapter 19] Dimension
Chapter 19 java.awt Reference
Dimension Name Dimension
Description The Dimension class encapsulates width and height in a single object.
Class Definition public class java.awt.Dimension extends java.lang.Object implements java.io.Serializable { // Variables public int height; public int width; // Constructors public Dimension(); public Dimension (int width, int height); public Dimension (Dimension d); // Instance Methods public boolean equals (Object obj); http://localhost/java/javaref/awt/ch19_19.htm (1 of 4) [20/12/2001 11:11:05]
[Chapter 19] Dimension
public Dimension getSize(); public void setSize (Dimension d); public void setSize (int width, int height); public String toString(); }
Variables height public int height The height of the Dimension.
width public int width The width of the Dimension.
Constructors Dimension public Dimension() Description Constructs an empty Dimension object. public Dimension (int width, int height) Parameters width Initial width of the object height Initial height of the object Description Constructs a Dimension object with an initial dimension of width x height. public Dimension (Dimension d)
http://localhost/java/javaref/awt/ch19_19.htm (2 of 4) [20/12/2001 11:11:05]
[Chapter 19] Dimension
Parameters d Initial dimensions of the object Description Constructs a Dimension object that is a clone of d.
Instance Methods equals public boolean equals (Object obj) Parameters obj The object to compare. Returns true if this Dimension is equivalent to obj; false otherwise. Overrides Object.equals(Object) Description Compares two Dimension instances.
getSize public Dimension getSize() Returns The size of the Dimension.
setSize public void setSize (Dimension d) Parameters d The new size. Description
http://localhost/java/javaref/awt/ch19_19.htm (3 of 4) [20/12/2001 11:11:05]
[Chapter 19] Dimension
Changes the size of the Dimension. public void setSize (int width, int height) Parameters width The new width. height The new height. Description Changes the size of the Dimension.
toString public String toString() Returns A string representation of the Dimension object. Overrides Object.toString()
See Also Object, String, Serializable
Dialog
http://localhost/java/javaref/awt/ch19_19.htm (4 of 4) [20/12/2001 11:11:05]
Event
[Chapter 19] Event
Chapter 19 java.awt Reference
Event Name Event
Description The Event class represents events that happen within the Java environment in a platform independent way. Events typically represent user actions, like typing a key or clicking the mouse. Although this class has been updated for the 1.1 release, it is only used for the 1.0 event model. When using the 1.1 event model, all events are represented by subclasses of java.awt.AWTEvent.
Class Definition public class java.awt.Event extends java.lang.Object implements java.io.Serializable { // Constants public static final int ACTION_EVENT; public static final int ALT_MASK; public static final int BACK_SPACE; public static final int CAPS_LOCK; public static final int CTRL_MASK; public static final int DELETE; http://localhost/java/javaref/awt/ch19_20.htm (1 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
public static final int DOWN; public static final int END; public static final int ENTER; public public public public public public public public public public public public public public public
static static static static static static static static static static static static static static static
final final final final final final final final final final final final final final final
int int int int int int int int int int int int int int int
ESCAPE; F1; F2; F3; F4; F5; F6; F7; F8; F9; F10; F11; F12; GOT_FOCUS; HOME;
public public public public public public public public public public public public public public public public public
static static static static static static static static static static static static static static static static static
final final final final final final final final final final final final final final final final final
int int int int int int int int int int int int int int int int int
INSERT; KEY_ACTION; KEY_ACTION_RELEASE; KEY_PRESS; KEY_RELEASE; LEFT; LIST_DESELECT; LIST_SELECT; LOAD_FILE; LOST_FOCUS; META_MASK; MOUSE_DOWN; MOUSE_DRAG; MOUSE_ENTER; MOUSE_EXIT; MOUSE_MOVE; MOUSE_UP;
public static final int NUM_LOCK; public static final int PAUSE; public static final int PGDN; public static final int PGUP; public public public public
static static static static
final final final final
int int int int
PRINT_SCREEN; RIGHT; SAVE_FILE; SCROLL_ABSOLUTE;
http://localhost/java/javaref/awt/ch19_20.htm (2 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
public static final int SCROLL_BEGIN; public static final int SCROLL_END; public static final int SCROLL_LINE_DOWN; public static final int SCROLL_LINE_UP; public public public public
static static static static
final final final final
int int int int
SCROLL_LOCK; SCROLL_PAGE_DOWN; SCROLL_PAGE_UP; SHIFT_MASK;
public public public public public public public
static static static static static static static
final final final final final final final
int int int int int int int
TAB; UP; WINDOW_DEICONIFY; WINDOW_DESTROY; WINDOW_EXPOSE; WINDOW_ICONIFY; WINDOW_MOVED;
// Variables public Object arg; public int clickCount; public Event evt; public int id; public int key; public int modifiers; public Object target; public long when; public int x; public int y; // Constructors public Event (Object target, int id, Object arg); public Event (Object target, long when, int id, int x, int y, int key, int modifiers); public Event (Object target, long when, int id, int x, int y, int key, int modifiers, Object arg); // Instance Methods public boolean controlDown(); public boolean metaDown(); public boolean shiftDown(); public String toString(); public void translate (int x, int y); // Protected Instance Methods protected String paramString();
http://localhost/java/javaref/awt/ch19_20.htm (3 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
}
Constants ACTION_EVENT public static final int ACTION_EVENT ID constant for Action Event.
ALT_MASK public static final int ALT_MASK Mask for ALT key.
BACK_SPACE public static final int BACK_SPACE ID constant for Backspace.
CAPS_LOCK public static final int CAPS_LOCK ID constant for Caps Lock key.
CTRL_MASK public static final int CTRL_MASK Mask for Control key.
DELETE public static final int DELETE ID constant for Delete.
DOWN public static final int DOWN ID constant for the down arrow key. http://localhost/java/javaref/awt/ch19_20.htm (4 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
END public static final int END ID constant for End key.
ENTER public static final int ENTER ID constant for Enter key.
ESCAPE public static final int ESCAPE ID constant for Escape key.
F1 public static final int F1 ID constant for F1 key.
F2 public static final int F2 ID constant for F2 key.
F3 public static final int F3 ID constant for F3 key.
F4 public static final int F4 ID constant for F4 key.
http://localhost/java/javaref/awt/ch19_20.htm (5 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
F5 public static final int F5 ID constant for F5 key.
F6 public static final int F6 ID constant for F6 key.
F7 public static final int F7 ID constant for F7 key.
F8 public static final int F8 ID constant for F8 key.
F9 public static final int F9 ID constant for F9 key.
F10 public static final int F10 ID constant for F10 key.
F11 public static final int F11 ID constant for F11 key.
http://localhost/java/javaref/awt/ch19_20.htm (6 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
F12 public static final int F12 ID constant for F12 key.
GOT_FOCUS public static final int GOT_FOCUS ID constant for getting input focus Event.
HOME public static final int HOME ID constant for Home key.
INSERT public static final int INSERT ID constant for Insert key.
KEY_ACTION public static final int KEY_ACTION ID constant for Special Key Down Event.
KEY_ACTION_RELEASE public static final int KEY_ACTION_RELEASE ID constant for Special Key Up Event.
KEY_PRESS public static final int KEY_PRESS ID constant for Key Down Event.
http://localhost/java/javaref/awt/ch19_20.htm (7 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
KEY_RELEASE public static final int KEY_RELEASE ID constant for Key Up Event.
LEFT public static final int LEFT ID constant for the left arrow key.
LIST_DESELECT public static final int LIST_DESELECT ID constant for List DeSelect Event.
LIST_SELECT public static final int LIST_SELECT ID constant for List Select Event.
LOAD_FILE public static final int LOAD_FILE ID constant for File Load Event.
LOST_FOCUS public static final int LOST_FOCUS ID constant for losing input focus Event.
META_MASK public static final int META_MASK Mask for ALT key.
http://localhost/java/javaref/awt/ch19_20.htm (8 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
MOUSE_DOWN public static final int MOUSE_DOWN ID constant for Mouse Down Event.
MOUSE_DRAG public static final int MOUSE_DRAG ID constant for Mouse Drag Event.
MOUSE_ENTER public static final int MOUSE_ENTER ID constant for Mouse Enter Event.
MOUSE_EXIT public static final int MOUSE_EXIT ID constant for Mouse Exit Event.
MOUSE_MOVE public static final int MOUSE_MOVE ID constant for Mouse Move Event.
MOUSE_UP public static final int MOUSE_UP ID constant for Mouse Up Event.
NUM_LOCK public static final int NUM_LOCK ID constant for Num Lock key.
http://localhost/java/javaref/awt/ch19_20.htm (9 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
PAUSE public static final int PAUSE ID constant for Pause key.
PGDN public static final int PGDN ID constant for PageDown key.
PGUP public static final int PGUP ID constant for PageUp key.
PRINT_SCREEN public static final int PRINT_SCREEN ID constant for Print Screen key.
RIGHT public static final int RIGHT ID constant for the right arrow key.
SAVE_FILE public static final int SAVE_FILE ID constant for File Save Event.
SCROLL_ABSOLUTE public static final int SCROLL_ABSOLUTE ID constant for Absolute Scroll Event.
http://localhost/java/javaref/awt/ch19_20.htm (10 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
SCROLL_BEGIN public static final int SCROLL_ BEGIN ID constant for Begin Scroll Event.
SCROLL_END public static final int SCROLL_ END ID constant for End Scroll Event.
SCROLL_LINE_DOWN public static final int SCROLL_LINE_DOWN ID constant for Line Down Scroll Event.
SCROLL_LINE_UP public static final int SCROLL_LINE_UP ID constant for Line Up Scroll Event.
SCROLL_LOCK public static final int SCROLL_LOCK Mask for Scroll Lock key.
SCROLL_PAGE_DOWN public static final int SCROLL_PAGE_DOWN ID constant for Page Down Scroll Event.
SCROLL_PAGE_UP public static final int SCROLL_PAGE_UP ID constant for Page Up Scroll Event.
http://localhost/java/javaref/awt/ch19_20.htm (11 of 18) [20/12/2001 11:11:10]
[Chapter 19] Event
SHIFT_MASK public static final int SHIFT_MASK Mask for SHIFT key.
TAB public static final int TAB ID constant for Tab key.
UP public static final int UP ID constant for the up arrow key.
WINDOW_DEICONIFY public static final int WINDOW_DEICONIFY ID constant for Window DeIconify Event.
WINDOW_DESTROY public static final int WINDOW_DESTROY ID constant for Window Destroy Event.
WINDOW_EXPOSE public static final int WINDOW_EXPOSE ID constant for Window Expose Event.
WINDOW_ICONIFY public static final int WINDOW_ICONIFY ID constant for Window Iconify Event.
http://localhost/java/javaref/awt/ch19_20.htm (12 of 18) [20/12/2001 11:11:11]
[Chapter 19] Event
WINDOW_MOVED public static final int WINDOW_MOVED ID constant for Window Move Event.
Variables arg public Object arg A variable argument that is specific to the event type.
clickCount public int clickCount The number of consecutive MOUSE_DOWN events.
evt public Event evt A means of passing a linked list of events as one.
id public int id The ID constant that identifies the Event type.
key public int key Integer value of key pressed, or ID constant identifying a special key.
modifiers public int modifiers The state of the shift/alt/control/meta keys, formed by ORing the masks for the appropriate keys.
http://localhost/java/javaref/awt/ch19_20.htm (13 of 18) [20/12/2001 11:11:11]
[Chapter 19] Event
target public Object target The Object that generated the event.
when public long when The time the event happened.
x public int x The x position at which the event happened.
y public int y The y position at which the event happened.
Constructors Event public Event (Object target, int id, Object arg) Parameters target The component to which the Event should be delivered id The identifier of Event arg The Object that is the cause of the event Description Constructs an Event object with the given values. public Event (Object target, long when, int id, int x, int y, int key, int modifiers)
http://localhost/java/javaref/awt/ch19_20.htm (14 of 18) [20/12/2001 11:11:11]
[Chapter 19] Event
Parameters target The component to which the Event should be delivered when The time the event happened id The identifier of Event x The x position at which the event happened y The y position at which the event happened key Integer value of key pressed, or a constant identifying a special key modifiers The state of the shift/alt/control/meta keys Description Constructs an Event object with the given values. public Event (Object target, long when, int id, int x, int y, int key, int modifiers, Object arg) Parameters target The component to which the Event should be delivered when The time the event happened id The identifier of Event x The x position at which the event happened y The y position at which the event happened key
http://localhost/java/javaref/awt/ch19_20.htm (15 of 18) [20/12/2001 11:11:11]
[Chapter 19] Event
Integer value of key pressed, or a constant identifying a special key modifiers The state of the shift/alt/control/meta keys arg The Object that is the cause of the event Description Constructs an Event object with the given values.
Instance Methods controlDown public boolean controlDown() Returns true if the control key was down when the event was triggered, false otherwise. Description Checks current settings for modifiers of the Event.
metaDown public boolean metaDown() Returns true if the meta key was down when the event was triggered, false otherwise. Description Checks current settings for modifiers of the Event.
shiftDown public boolean shiftDown() Returns true if the shift key was down when the event was triggered, false otherwise. Description Checks current settings for modifiers of the Event.
http://localhost/java/javaref/awt/ch19_20.htm (16 of 18) [20/12/2001 11:11:11]
[Chapter 19] Event
toString public String toString() Returns A string representation of the Event object. Overrides Object.toString()
translate public void translate (int x, int y) Parameters x Amount to move Event in horizontal direction. y Amount to move Event in vertical direction. Description Translates x and y coordinates of Event instance by x and y.
Protected Instance Methods paramString protected String paramString() Returns String with current settings of Event. Description Helper method for toString() to generate string of current settings.
See Also AWTEvent, Component, Object, String
Dimension
http://localhost/java/javaref/awt/ch19_20.htm (17 of 18) [20/12/2001 11:11:11]
EventQueue
[Chapter 19] Event
http://localhost/java/javaref/awt/ch19_20.htm (18 of 18) [20/12/2001 11:11:11]
[Chapter 19] EventQueue
Chapter 19 java.awt Reference
EventQueue Name EventQueue
Description The EventQueue class is a facility for queuing Java 1.1 AWT events, either for the system or for some other purpose. You rarely need to create your own event queue; for most purposes, you will want to work with the system's event queue, which you acquire using the Toolkit.
Class Definition public class EventQueue extends Object { // Constructor public EventQueue(); // Instance Methods public synchronized AWTEvent getNextEvent() throws InterruptedException; public synchronized AWTEvent peekEvent(); public synchronized AWTEvent peekEvent (int id); public synchronized void postEvent (AWTEvent theEvent); }
Constructor
http://localhost/java/javaref/awt/ch19_21.htm (1 of 3) [20/12/2001 11:11:12]
[Chapter 19] EventQueue
EventQueue public EventQueue() Description Creates an EventQueue for your own use.
Instance Methods getNextEvent public synchronized AWTEvent getNextEvent() throws InterruptedException Throws InterruptedException If the thread is interrupted before an event is posted to the queue. Returns AWTEvent taken from the event queue. Description Removes the next event from the event queue and returns it. If there are no events in the queue, this method will block until another thread posts one.
peekEvent public synchronized AWTEvent peekEvent() Returns Next AWTEvent on the event queue. Description Returns a reference to the next event on the queue without removing it from the queue. public synchronized AWTEvent peekEvent (int id) Parameters id Type of event to find. Returns AWTEvent with the given type id; null if no event with the given type is currently in the queue. Description Returns an event with the given type if one exists, but doesn't remove the event from the queue.
http://localhost/java/javaref/awt/ch19_21.htm (2 of 3) [20/12/2001 11:11:12]
[Chapter 19] EventQueue
See Also AWTEvent, Event
Event
http://localhost/java/javaref/awt/ch19_21.htm (3 of 3) [20/12/2001 11:11:12]
FileDialog
[Chapter 19] FileDialog
Chapter 19 java.awt Reference
FileDialog Name FileDialog
Description The FileDialog class provides file selection capabilities for opening or saving files. Because FileDialog is a subclass of Dialog, a FileDialog is always associated with a Frame and is hidden by default. FileDialogs are always modal (i.e., they always attract all user input). In addition, FileDialogs have a load/save mode; the LOAD mode is for selecting files for an application to load, SAVE is for selecting a filename to save.
Class Definition public class java.awt.FileDialog extends java.awt.Dialog { // Constants public final static int LOAD; public final static int SAVE; // Constructors
http://localhost/java/javaref/awt/ch19_22.htm (1 of 6) [20/12/2001 11:11:17]
[Chapter 19] FileDialog
public FileDialog (Frame parent); public FileDialog (Frame parent, String title); public FileDialog (Frame parent, String title, int mode); // Instance Methods public void addNotify(); public String getDirectory(); public String getFile(); public FilenameFilter getFilenameFilter(); public int getMode(); public synchronized void setDirectory (String directory); public synchronized void setFile (String file); public synchronized void setFilenameFilter (FilenameFilter filter); public void setMode(int mode); // Protected Instance Methods protected String paramString(); }
Constants LOAD public final static int LOAD Constant to specify the FileDialog's load mode.
SAVE public final static int SAVE Constant to specify the FileDialog's save mode.
Constructors FileDialog public FileDialog (Frame parent) Parameters parent Frame that is to act as parent of FileDialog.
http://localhost/java/javaref/awt/ch19_22.htm (2 of 6) [20/12/2001 11:11:17]
[Chapter 19] FileDialog
Description Constructs a FileDialog object in LOAD mode. public FileDialog (Frame parent, String title) Parameters parent Frame that is to act as parent of FileDialog. title Title to use for FileDialog. Description Constructs a FileDialog object in LOAD mode. public FileDialog (Frame parent, String title, int mode) Parameters parent Frame that is to act as parent of Dialog. title Title to use for FileDialog. mode The constant LOAD or SAVE, specifying the dialog's mode. Description Constructs a FileDialog object in the given mode.
Instance Methods addNotify public void addNotify() Overrides Dialog.addNotify() Description Creates FileDialog's peer for the native platform.
http://localhost/java/javaref/awt/ch19_22.htm (3 of 6) [20/12/2001 11:11:17]
[Chapter 19] FileDialog
getDirectory public String getDirectory() Returns The current directory for the FileDialog.
getFile public String getFile() Returns The current file selected by the FileDialog.
getFilenameFilter public FilenameFilter getFilenameFilter() Returns The current filename filter for the FileDialog.
getMode public int getMode() Returns The current mode of the FileDialog.
setDirectory public synchronized void setDirectory (String directory) Parameters directory Directory to be displayed by the FileDialog. Description Changes the directory displayed in the FileDialog.
http://localhost/java/javaref/awt/ch19_22.htm (4 of 6) [20/12/2001 11:11:17]
[Chapter 19] FileDialog
setFile public synchronized void setFile (String file) Parameters file Initial file string for FileDialog. Description Change the default file selected by the FileDialog.
setFilenameFilter public synchronized void setFilenameFilter (FilenameFilter filter) Parameters filter Initial filter for FileDialog. Description Changes the current filename filter of the FileDialog.
setMode public void setMode (int mode) Parameters mode The constant LOAD or SAVE, specifying the dialog's mode. Description Change the mode of the file dialog.
Protected Instance Methods paramString protected String paramString() Returns String with current settings of FileDialog. Overrides http://localhost/java/javaref/awt/ch19_22.htm (5 of 6) [20/12/2001 11:11:17]
[Chapter 19] FileDialog
Dialog.paramString() Description Helper method for toString() to generate string of current settings.
See Also Dialog, FilenameFilter, String
EventQueue
http://localhost/java/javaref/awt/ch19_22.htm (6 of 6) [20/12/2001 11:11:17]
FlowLayout
[Chapter 19] FlowLayout
Chapter 19 java.awt Reference
FlowLayout Name FlowLayout
Description The FlowLayout LayoutManager provides the means to lay out components in a row by row fashion. As each row fills up, the components continue on the next row.
Class Definition public class java.awt.FlowLayout extends java.lang.Object implements java.awt.LayoutManager, java.io.Serializable { // Constants public static final int CENTER; public static final int LEFT; public static final int RIGHT; // Constructors public FlowLayout(); public FlowLayout (int alignment);
http://localhost/java/javaref/awt/ch19_23.htm (1 of 7) [20/12/2001 11:11:21]
[Chapter 19] FlowLayout
public FlowLayout (int alignment, int hgap, int vgap); // Instance Methods public void addLayoutComponent (String name, Component component); public int getAlignment(); public int getHgap(); public public public public public
int getVgap(); void layoutContainer (Container target); Dimension minimumLayoutSize (Container target); Dimension preferredLayoutSize (Container target); void removeLayoutComponent (Component component);
public void setAlignment (int align); public void setHgap (int hgap); public void setVgap (int vgap); public String toString(); }
Constants CENTER public static final int CENTER The default alignment for a FlowLayout object; rows of components are centered within the container.
LEFT public static final int LEFT An alignment for a FlowLayout object; rows of components start on the left side of the container.
RIGHT public static final int RIGHT An alignment for a FlowLayout object; rows of components start on the right side of the container.
Constructors
http://localhost/java/javaref/awt/ch19_23.htm (2 of 7) [20/12/2001 11:11:21]
[Chapter 19] FlowLayout
FlowLayout public FlowLayout() Description Constructs a FlowLayout object with CENTER alignment. public FlowLayout (int alignment) Parameters alignment Alignment of components within the container. Description Constructs a FlowLayout object with the given alignment. public FlowLayout (int alignment, int hgap, int vgap) Parameters alignment Alignment of components within container hgap Horizontal space between each component in a row vgap Vertical space between each row Description Constructs a FlowLayout object with the given alignment and the values specified as the gaps between each component in the container managed by this instance of FlowLayout.
Instance Methods addLayoutComponent public void addLayoutComponent (String name, Component component) Parameters name Name of component to add. component
http://localhost/java/javaref/awt/ch19_23.htm (3 of 7) [20/12/2001 11:11:21]
[Chapter 19] FlowLayout
Actual component being added. Implements LayoutManager.addLayoutComponent() Description Does nothing.
getAlignment public int getAlignment() Returns The alignment constant for this FlowLayout.
getHgap public int getHgap() Returns The horizontal gap between components.
getVgap public int getVgap() Returns The vertical gap between components.
layoutContainer public void layoutContainer (Container target) Parameters target The container that needs to be redrawn. Implements LayoutManager.layoutContainer() Description Draws the components contained within the target container.
http://localhost/java/javaref/awt/ch19_23.htm (4 of 7) [20/12/2001 11:11:21]
[Chapter 19] FlowLayout
minimumLayoutSize public Dimension minimumLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Minimum Dimension of container target Implements LayoutManager.minimumLayoutSize() Description Calculates minimum size of target container.
preferredLayoutSize public Dimension preferredLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Preferred Dimension of container target Implements LayoutManager.preferredLayoutSize() Description Calculates preferred size of target container.
removeLayoutComponent public void removeLayoutComponent (Component component) Parameters component Component to stop tracking. Implements LayoutManager.removeLayoutComponent() http://localhost/java/javaref/awt/ch19_23.htm (5 of 7) [20/12/2001 11:11:21]
[Chapter 19] FlowLayout
Description Does nothing.
setAlignment public void setAlignment(int align) Parameters alignment Alignment of components within container Description Sets the alignment for the FlowLayout.
setHgap public void setHgap(int hgap) Parameters hgap The horizontal gap value. Description Sets the horizontal gap between components.
setVgap public void setVgap(int vgap) Parameters vgap The vertical gap value. Description Sets the vertical gap between components.
toString public String toString() Returns A string representation of the FlowLayout object. http://localhost/java/javaref/awt/ch19_23.htm (6 of 7) [20/12/2001 11:11:21]
[Chapter 19] FlowLayout
Overrides Object.toString()
See Also Component, Container, Dimension, LayoutManager, Object, Serializable, String
FileDialog
http://localhost/java/javaref/awt/ch19_23.htm (7 of 7) [20/12/2001 11:11:21]
Font
[Chapter 19] Font
Chapter 19 java.awt Reference
Font Name Font
Description The Font class represents a specific font to the system.
Class Definition public class java.awt.Font extends java.lang.Object implements java.io.Serializable { // Constants public static final int BOLD; public static final int ITALIC; public static final int PLAIN; // Variables protected String name; protected int size; protected int style; // Constructors http://localhost/java/javaref/awt/ch19_24.htm (1 of 7) [20/12/2001 11:11:22]
[Chapter 19] Font
public Font (String name, int style, int size); // Class Methods public static Font decode (String str); public static Font getFont (String name) public static Font getFont (String name, Font defaultFont) // Instance Methods public boolean equals (Object object); public String getFamily(); public String getName(); public public public public public public public public
FontPeer getPeer(); int getSize(); int getStyle(); int hashCode(); boolean isBold(); boolean isItalic(); boolean isPlain(); String toString();
}
Constants BOLD public static final int BOLD Constant for specifying bold fonts.
ITALIC public static final int ITALIC Constant for specifying fonts.
PLAIN public static final int PLAIN Constant for specifying plain fonts.
http://localhost/java/javaref/awt/ch19_24.htm (2 of 7) [20/12/2001 11:11:22]
[Chapter 19] Font
Variables name protected String name The font's logical name.
size protected int size The font size; allegedly in points, though probably not true typographer's points.
style protected int style The font style, e.g., bold or italic or a combination thereof.
Constructors Font public Font (String name, int style, int size) Parameters name The name of the desired font. style One of the style flags (PLAIN, BOLD, or ITALIC) or a combination. size The size of the font to create. Description Constructs a Font object with the given characteristics.
Class Methods
http://localhost/java/javaref/awt/ch19_24.htm (3 of 7) [20/12/2001 11:11:22]
[Chapter 19] Font
decode public static Font decode (String str) Parameters str The string describing the font. Returns Font instance requested, or default if str is invalid. Description Gets font specified by str.
getFont public static Font getFont (String name) Parameters name The name of a system property specifying a font to fetch. Returns Font instance for name requested, or null if name is invalid. Description Gets font specified by the system property name. public static Font getFont (String name, Font defaultFont) Parameters name The name of a system property specifying a font to fetch. defaultFont Font to return if name not found in properties. Returns Font instance of name requested, or defaultFont if name is invalid Description Gets font specified by the system property name.
http://localhost/java/javaref/awt/ch19_24.htm (4 of 7) [20/12/2001 11:11:22]
[Chapter 19] Font
Instance Methods equals public boolean equals (Object object) Parameters object The object to compare. Returns true if the objects are equivalent fonts (same name, style, and point size), false otherwise. Overrides Object.equals(Object) Description Compares two different Font instances for equivalence.
getFamily public String getFamily() Returns Retrieves the actual name of the font.
getName public String getName() Returns Retrieves the logical name of the font.
getPeer public FontPeer getPeer() Returns The font's peer.
http://localhost/java/javaref/awt/ch19_24.htm (5 of 7) [20/12/2001 11:11:22]
[Chapter 19] Font
getSize public int getSize() Returns Retrieves the size parameter from creation
getStyle public int getStyle() Returns Retrieves the style parameter from creation.
hashCode public int hashCode() Returns A hashcode to use when using the Font as a key in a Hashtable. Overrides Object.hashCode() Description Generates a hashcode for the Font.
isBold public boolean isBold() Returns true if Font style is bold, false otherwise.
isItalic public boolean isItalic() Returns true if Font style is italic, false otherwise.
http://localhost/java/javaref/awt/ch19_24.htm (6 of 7) [20/12/2001 11:11:22]
[Chapter 19] Font
isPlain public boolean isPlain() Returns true if Font style is neither bold nor italic, false otherwise.
toString public String toString() Returns A string representation of the Font object. Overrides Object.toString()
See Also FontMetrics, Object, Properties, String
FlowLayout
http://localhost/java/javaref/awt/ch19_24.htm (7 of 7) [20/12/2001 11:11:22]
FontMetrics
[Chapter 19] FontMetrics
Chapter 19 java.awt Reference
FontMetrics Name FontMetrics
Description The FontMetrics class provides the means to calculate actual width and height of text if drawn on the screen.
Class Definition public abstract class java.awt.FontMetrics extends java.lang.Object implements java.io.Serializable { // Variables protected Font font; // Constructors protected FontMetrics (Font font); // Instance Methods public int bytesWidth (byte data[], int offset, int length); public int charsWidth (char data[], int offset, int length); public int charWidth (char character); http://localhost/java/javaref/awt/ch19_25.htm (1 of 6) [20/12/2001 11:11:25]
[Chapter 19] FontMetrics
public public public public public public public public public public public public public
int charWidth (int character); int getAscent(); int getDescent(); Font getFont(); int getHeight(); int getLeading(); int getMaxAdvance(); int getMaxAscent(); int getMaxDecent(); int getMaxDescent(); int[] getWidths(); int stringWidth (String string); String toString();
}
Variables font protected Font font The Font object whose metrics are represented by this object.
Constructors FontMetrics protected FontMetrics (Font font) Parameters font The Font object whose metrics you want. Description Constructs a platform specific FontMetrics object for the given font.
Instance Methods bytesWidth public int bytesWidth (byte data[], int offset, int length) Parameters http://localhost/java/javaref/awt/ch19_25.htm (2 of 6) [20/12/2001 11:11:25]
[Chapter 19] FontMetrics
data[] Array of characters to lookup. offset Initial character position. length Number of characters to lookup. Returns Advance width of characters in the array, starting with offset and ending with offset+length, in pixels. Throws ArrayIndexOutOfBoundsException If offset or length is invalid.
charsWidth public int charsWidth (char data[], int offset, int length) Parameters data[] Array of characters to lookup. offset Initial character position. length Number of characters to lookup. Returns Advance width of characters in the array, starting with offset and ending with offset+length-1, in pixels. Throws ArrayIndexOutOfBoundsException If offset or length is invalid.
charWidth public int charWidth (char character) Parameters
http://localhost/java/javaref/awt/ch19_25.htm (3 of 6) [20/12/2001 11:11:25]
[Chapter 19] FontMetrics
character character to lookup Returns Advanced pixel width of character. public int charWidth (int character) Parameters character int value of character to lookup Returns Advanced pixel width of character.
getAscent public int getAscent() Returns Amount of space above the baseline required for the tallest character in the font.
getDescent public int getDescent() Returns Amount of space below the baseline required for the lowest descender (e.g., the tail on "p") in the font.
getFont public Font getFont() Returns The Font whose metrics are represented by this object.
getHeight public int getHeight() Returns
http://localhost/java/javaref/awt/ch19_25.htm (4 of 6) [20/12/2001 11:11:25]
[Chapter 19] FontMetrics
The sum of getDescent(), getAscent(), and getLeading(); recommended total space between baselines.
getLeading public int getLeading() Returns Retrieves recommended amount of space between lines of text.
getMaxAdvance public int getMaxAdvance() Returns Retrieves advance pixel width of widest character in the font.
getMaxAscent public int getMaxAscent() Returns Retrieves maximum amount of space above the baseline required for the tallest character within the font's FontMetrics. May differ from getAscent() for characters with diacritical marks.
getMaxDecent public int getMaxDecent() Returns Retrieves the maximum amount of space below the baseline required for the deepest character for the font. Description A misspelling of getMaxDescent().
getMaxDescent public int getMaxDescent() Returns Retrieves the maximum amount of space below the baseline required for the deepest character for the font.
http://localhost/java/javaref/awt/ch19_25.htm (5 of 6) [20/12/2001 11:11:25]
[Chapter 19] FontMetrics
getWidths public int[] getWidths() Returns 255 element array of character widths. Description Retrieves an integer array of the advance widths of the first 255 characters in the FontMetrics' font.
stringWidth public int stringWidth (String string) Parameters string Character string to lookup. Returns Advance pixel width of string.
toString public String toString() Returns A string representation of the FontMetrics object. Overrides Object.toString()
See Also Font, Object, String
Font
http://localhost/java/javaref/awt/ch19_25.htm (6 of 6) [20/12/2001 11:11:25]
Frame
[Chapter 19] Frame
Chapter 19 java.awt Reference
Frame Name Frame
Description The Frame class is a special type of Window that will appear like other high-level programs in your windowing environment. It adds a MenuBar, window title, and window gadgets (like resize, maximize, minimize, window menu) to the basic Window object. Frames are initially invisible; call show() to display them. Frames may also be associated with an Image to be used as an icon. The Frame class includes many constants to represent different cursor styles. All styles aren't necessarily available on any platform. In 1.1, these constants are defined in java.awt.Cursor.
Class Definition public class java.awt.Frame extends java.awt.Window implements java.awt.MenuContainer { // Constants public final static int CROSSHAIR_CURSOR; public final static int DEFAULT_CURSOR;
http://localhost/java/javaref/awt/ch19_26.htm (1 of 8) [20/12/2001 11:11:27]
[Chapter 19] Frame
public public public public public public public public public public public public
final final final final final final final final final final final final
static static static static static static static static static static static static
int int int int int int int int int int int int
E_RESIZE_CURSOR; HAND_CURSOR; MOVE_CURSOR; N_RESIZE_CURSOR; NE_RESIZE_CURSOR; NW_RESIZE_CURSOR; S_RESIZE_CURSOR; SE_RESIZE_CURSOR; SW_RESIZE_CURSOR; TEXT_CURSOR; W_RESIZE_CURSOR; WAIT_CURSOR;
// Constructors public Frame(); public Frame (String title); // Instance Methods public void addNotify(); public synchronized void dispose(); public public public public public public
int getCursorType(); Image getIconImage(); MenuBar getMenuBar(); String getTitle(); boolean isResizable(); synchronized void remove (MenuComponent component);
public public public public public
synchronized synchronized synchronized synchronized synchronized
void void void void void
setCursor (int cursorType); setIconImage (Image image); setMenuBar (MenuBar bar); setResizable (boolean resizable); setTitle (String title);
// Protected Instance Methods protected String paramString(); }
Constants CROSSHAIR_CURSOR public final static int CROSSHAIR_CURSOR Constant representing a cursor that looks like a crosshair.
http://localhost/java/javaref/awt/ch19_26.htm (2 of 8) [20/12/2001 11:11:27]
[Chapter 19] Frame
DEFAULT_CURSOR public final static int DEFAULT_CURSOR Constant representing the platform's default cursor.
E_RESIZE_CURSOR public final static int E_RESIZE_CURSOR Constant representing the cursor for resizing an object on the left.
HAND_CURSOR public final static int HAND_CURSOR Constant representing a cursor that looks like a hand.
MOVE_CURSOR public final static int MOVE_CURSOR Constant representing a cursor used to move an object.
N_RESIZE_CURSOR public final static int N_RESIZE_CURSOR Constant representing a cursor for resizing an object on the top.
NE_RESIZE_CURSOR public final static int NE_RESIZE_CURSOR Constant representing a cursor for resizing an object on the top left corner.
NW_RESIZE_CURSOR public final static int NW_RESIZE_CURSOR Constant representing a cursor for resizing an object on the top right corner.
http://localhost/java/javaref/awt/ch19_26.htm (3 of 8) [20/12/2001 11:11:27]
[Chapter 19] Frame
S_RESIZE_CURSOR public final static int S_RESIZE_CURSOR Constant representing a cursor for resizing an object on the bottom.
SE_RESIZE_CURSOR public final static int SE_RESIZE_CURSOR Constant representing a cursor for resizing an object on the bottom left corner.
SW_RESIZE_CURSOR public final static int SW_RESIZE_CURSOR Constant representing a cursor for resizing an object on the bottom right corner.
TEXT_CURSOR public final static int TEXT_CURSOR Constant representing a cursor used within text.
W_RESIZE_CURSOR public final static int W_RESIZE_CURSOR Constant representing a cursor for resizing an object on the right side.
WAIT_CURSOR public final static int WAIT_CURSOR Constant representing a cursor that indicates the program is busy.
Constructors Frame public Frame() Description Constructs a Frame object, with no title.
http://localhost/java/javaref/awt/ch19_26.htm (4 of 8) [20/12/2001 11:11:27]
[Chapter 19] Frame
public Frame (String title) Parameters title Initial title to use for Frame. Description Constructs a Frame object, with the given title.
Instance Methods addNotify public void addNotify() Overrides Window.addNotify() Description Creates Frame's peer and peers of contained components.
dispose public synchronized void dispose() Overrides Window.dispose() Description Releases the resources of the Frame.
getCursorType public int getCursorType() Returns The constant for the current cursor. Replaced by Component.getCursor()
getIconImage public Image getIconImage() Returns http://localhost/java/javaref/awt/ch19_26.htm (5 of 8) [20/12/2001 11:11:27]
[Chapter 19] Frame
The image used as the icon, or null if there is no icon for this frame.
getMenuBar public MenuBar getMenuBar() Returns The Frame's current menu bar, or null if there is no menu bar for this frame.
getTitle public String getTitle() Returns The current title for the Frame, or null if there is no title for this frame.
isResizable public boolean isResizable() Returns true if resizable, false otherwise.
remove public synchronized void remove (MenuComponent component) Parameters component MenuBar to remove from Frame. Implements MenuContainer.remove() Description Removes component from Frame if component is the Frame's menu bar.
setCursor public synchronized void setCursor (int cursorType) Parameters
http://localhost/java/javaref/awt/ch19_26.htm (6 of 8) [20/12/2001 11:11:27]
[Chapter 19] Frame
cursorType One of Frame's cursor constants. Throws IllegalArgumentException If cursorType invalid. Description Changes the cursor of the Frame. Replaced by Component.setCursor(Cursor).
setIconImage public synchronized void setIconImage (Image image) Parameters image New image to use for the Frame's icon. Description Changes the icon's image for the Frame.
setMenuBar public synchronized void setMenuBar (MenuBar bar) Parameters bar New MenuBar to use for the Frame. Description Changes the menu bar of the Frame.
setResizable public synchronized void setResizable (boolean resizable) Parameters resizable true to make the frame resizable, false to prevent resizing. Description Changes the resize state of the Frame.
http://localhost/java/javaref/awt/ch19_26.htm (7 of 8) [20/12/2001 11:11:27]
[Chapter 19] Frame
setTitle public synchronized void setTitle (String title) Parameters title New title to use for the Frame. Description Changes the title of the Frame.
Protected Instance Methods paramString protected String paramString() Returns String with current settings of Frame. Overrides Container.paramString() Description Helper method for toString() to generate a string of current settings.
See Also Container, Image, MenuBar, MenuContainer, String, Window
FontMetrics
http://localhost/java/javaref/awt/ch19_26.htm (8 of 8) [20/12/2001 11:11:27]
Graphics
[Chapter 19] Graphics
Chapter 19 java.awt Reference
Graphics Name Graphics
Description The Graphics class is an abstract class that represents an object on which you can draw. The concrete classes that are actually used to represent graphics objects are platform dependent, but because they extend the Graphics class, must implement the methods here.
Class Definition public abstract class java.awt.Graphics extends java.lang.Object { // Constructors protected Graphics(); // Instance Methods public abstract void clearRect (int x, int y, int width, int height); public abstract void clipRect (int x, int y, int width, int height); public abstract void copyArea (int x, int y, int width, int height, int deltax, int deltay); public abstract Graphics create(); public Graphics create (int x, int y, int width, int height); public abstract void dispose(); public void draw3DRect (int x, int y, int width, int height, boolean raised); public abstract void drawArc (int x, int y, int width, int height, http://localhost/java/javaref/awt/ch19_27.htm (1 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
int startAngle, int arcAngle); public void drawBytes (byte text[], int offset, int length, int x, int y); public void drawChars (char text[], int offset, int length, int x, int y); public abstract boolean drawImage (Image image, int x, int y, ImageObserver observer); public abstract boolean drawImage (Image image, int x, int y, int width, int height, ImageObserver observer); public abstract boolean drawImage (Image image, int x, int y, Color backgroundColor, ImageObserver observer); public abstract boolean drawImage (Image image, int x, int y, int width, int height, Color backgroundColor, ImageObserver observer); public abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer); public abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer); public abstract void drawLine (int x1, int y1, int x2, int y2); public abstract void drawOval (int x, int y, int width, int height); public abstract void drawPolygon (int xPoints[], int yPoints[], int numPoints); public void drawPolygon (Polygon p); public abstract void drawPolyline(int[ ] xPoints, int[ ] yPoints, int nPoints); public void drawRect (int x, int y, int width, int height); public abstract void drawRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight); public abstract void drawString (String text, int x, int y); public void fill3DRect (int x, int y, int width, int height, boolean raised); public abstract void fillArc (int x, int y, int width, int height, int startAngle, int arcAngle); public abstract void fillOval (int x, int y, int width, int height); public abstract void fillPolygon (int xPoints[], int yPoints[], int numPoints); public void fillPolygon (Polygon p); public abstract void fillRect (int x, int y, int width, int height); public abstract void fillRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight); public void finalize(); public abstract Shape getClip(); public public public public
abstract abstract abstract abstract
Rectangle getClipBounds(); Rectangle getClipRect(); Color getColor(); Font getFont();
http://localhost/java/javaref/awt/ch19_27.htm (2 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
public FontMetrics getFontMetrics(); public abstract FontMetrics getFontMetrics (Font font); public abstract void setClip (int x, int y, int width, int height); public public public public public public public
abstract void setClip (Shape clip); abstract void setColor (Color color); abstract void setFont (Font font); abstract void setPaintMode(); abstract void setXORMode (Color xorColor); String toString(); abstract void translate (int x, int y);
}
Constructors Graphics protected Graphics() Description Called by constructors of platform specific subclasses.
Instance Methods clearRect public abstract void clearRect (int x, int y, int width, int height) Parameters x x coordinate of origin of area to clear. y y coordinate of origin of area to clear. width size in horizontal direction to clear. height size in vertical direction to clear. Description Resets a rectangular area to the background color.
http://localhost/java/javaref/awt/ch19_27.htm (3 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
clipRect public abstract void clipRect (int x, int y, int width, int height) Parameters x x coordinate of origin of clipped area. y y coordinate of origin of clipped area. width size in horizontal direction to clip. height size in vertical direction to clip. Description Reduces the drawing area to the intersection of the current drawing area and the rectangular area defined by x, y, width, and height.
copyArea public abstract void copyArea (int x, int y, int width, int height, int deltax, int deltay) Parameters x x coordinate of origin of area to copy. y y coordinate of origin of area to copy. width size in horizontal direction to copy. height size in vertical direction to copy. deltax offset in horizontal direction to copy area to. deltay offset in vertical direction to copy area to. Description Copies a rectangular area to a new area, whose top left corner is (x+deltax, y+deltay).
http://localhost/java/javaref/awt/ch19_27.htm (4 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
create public abstract Graphics create() Returns New graphics context. Description Creates a second reference to the same graphics context. public Graphics create (int x, int y, int width, int height) Parameters x x coordinate of origin of new graphics context. y y coordinate of origin of new graphics context. width size in horizontal direction. height size in vertical direction. Returns New graphics context Description Creates a second reference to a subset of the same graphics context.
dispose public abstract void dispose() Description Frees system resources used by graphics context.
draw3DRect public void draw3DRect (int x, int y, int width, int height, boolean raised) Parameters x x coordinate of the rectangle origin. y
http://localhost/java/javaref/awt/ch19_27.htm (5 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
y coordinate of the rectangle origin width Width of the rectangle to draw. height Height of the rectangle to draw. raised Determines if rectangle drawn is raised or not; true for a raised rectangle. Description Draws an unfilled 3-D rectangle from (x, y) of size width x height.
drawArc public abstract void drawArc (int x, int y, int width, int height, int startAngle, int arcAngle) Parameters x x coordinate of the bounding rectangle's origin. y y coordinate of the bounding rectangle's origin width Width of the bounding rectangle for the arc. height Height of the bounding rectangle for the arc. startAngle Angle at which arc begins, in degrees arcAngle length of arc, in degrees Description Draws an unfilled arc from startAngle to arcAngle within bounding rectangle from (x, y) of size width x height. Zero degrees is at three o'clock; positive angles are counter clockwise.
drawBytes public void drawBytes (byte text[], int offset, int length, int x, int y) Parameters text Text to draw, as a byte array. offset http://localhost/java/javaref/awt/ch19_27.htm (6 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
Starting position within text to draw. length Number of bytes to draw. x x coordinate of baseline origin. y y coordinate of baseline origin. Throws ArrayIndexOutOfBoundsException If offset or length is invalid. Description Draws text on screen, starting with text[offset] and ending with text[offset+length-1].
drawChars public void drawChars (char text[], int offset, int length, int x, int y) Parameters text Text to draw, as a char array. offset Starting position within text to draw. length Number of bytes to draw. x x coordinate of baseline origin. y y coordinate of baseline origin. Throws ArrayIndexOutOfBoundsException If offset or length is invalid. Description Draws text on screen, starting with text[offset] and ending with text[offset+length-1].
http://localhost/java/javaref/awt/ch19_27.htm (7 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
drawImage public abstract boolean drawImage (Image image, int x, int y, ImageObserver observer) Parameters image Image to draw. x x coordinate of image origin. y y coordinate of image origin. observer Object that watches for image information; almost always this. Returns true if the image has fully loaded when the method returns, false otherwise. Description Draws image to screen at (x, y), at its original size. Drawing may be asynchronous. If image is not fully loaded when the method returns, observer is notified when additional information made available. public abstract boolean drawImage (Image image, int x, int y, int width, int height, ImageObserver observer) Parameters image Image to draw. x x coordinate of image origin. y y coordinate of image origin. width New image size in horizontal direction. height New image size in vertical direction. observer Object that watches for image information; almost always this. Returns true if the image has fully loaded when the method returns, false otherwise. Description http://localhost/java/javaref/awt/ch19_27.htm (8 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
Draws image to screen at (x, y), scaled to width x height. Drawing may be asynchronous. If image is not fully loaded when the method returns, observer is notified when additional information made available. public abstract boolean drawImage (Image image, int x, int y, Color backgroundColor, ImageObserver observer) Parameters image Image to draw. x x coordinate of image origin. y y coordinate of image origin. backgroundColor Color to show through image where transparent. observer Object that watches for image information; almost always this. Returns true if the image has fully loaded when the method returns, false otherwise. Description Draws image to screen at (x, y), at its original size. Drawing may be asynchronous. If image is not fully loaded when the method returns, observer is notified when additional information made available. The background color is visible through any transparent pixels. public abstract boolean drawImage (Image image, int x, int y, int width, int height, Color backgroundColor, ImageObserver observer) Parameters image Image to draw. x x coordinate of image origin. y y coordinate of image origin. width New image size in horizontal direction. height
http://localhost/java/javaref/awt/ch19_27.htm (9 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
New image size in vertical direction. backgroundColor Color to show through image where transparent. observer Object that watches for image information; almost always this. Returns true if the image has fully loaded when the method returns, false otherwise. Description Draws image to screen at (x, y), scaled to width x height. Drawing may be asynchronous. If image is not fully loaded when the method returns, observer is notified when additional information made available. The background color is visible through any transparent pixels. public abstract boolean drawImage (Image image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) Parameters image Image to draw. dx1 x coordinate of one corner of destination (device) rectangle. dy1 y coordinate of one corner of destination (device) rectangle. dx2 x coordinate of the opposite corner of destination (device) rectangle. dy2 y coordinate of the opposite corner of destination (device) rectangle. sx1 x coordinate of one corner of source (image) rectangle. sy1 y coordinate of one corner of source (image) rectangle. sx2 x coordinate of the opposite corner of source (image) rectangle. sy2 y coordinate of the opposite corner of source (image) rectangle. observer Object that watches for image information; almost always this.
http://localhost/java/javaref/awt/ch19_27.htm (10 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
Returns true if the image has fully loaded when the method returns, false otherwise. Description Draws the part of image described by dx1, dy1, dx2, and dy2 to the screen into the rectangle described by sx1, sy1, sx2, and sy2. Drawing may be asynchronous. If image is not fully loaded when the method returns, observer is notified when additional information is made available. public abstract boolean drawImage (Image image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color backgroundColor, ImageObserver observer) Parameters image Image to draw. dx1 x coordinate of one corner of destination (device) rectangle. dy1 y coordinate of one corner of destination (device) rectangle. dx2 x coordinate of the opposite corner of destination (device) rectangle. dy2 y coordinate of the opposite corner of destination (device) rectangle. sx1 x coordinate of one corner of source (image) rectangle. sy1 y coordinate of one corner of source (image) rectangle. sx2 x coordinate of the opposite corner of source (image) rectangle. sy2 y coordinate of the opposite corner of source (image) rectangle. backgroundColor Color to show through image where transparent. observer Object that watches for image information; almost always this. Returns true if the image has fully loaded when the method returns, false otherwise. Description
http://localhost/java/javaref/awt/ch19_27.htm (11 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
Draws the part of image described by dx1, dy1, dx2, and dy2 to the screen into the rectangle described by sx1, sy1, sx2, and sy2. Drawing may be asynchronous. If image is not fully loaded when the method returns, observer is notified when additional information made available. The background color is visible through any transparent pixels.
drawLine public abstract void drawLine (int x1, int y1, int x2, int y2) Parameters x1 x coordinate of one point on line. y1 y coordinate of one point on line. x2 x coordinate of the opposite point on line. y2 y coordinate of the opposite point on line. Description Draws a line connecting (x1, y1) and (x2, y2).
drawOval public abstract void drawOval (int x, int y, int width, int height) Parameters x x coordinate of bounding rectangle origin. y y coordinate of bounding rectangle origin width Width of bounding rectangle to draw in. height Height of bounding rectangle to draw in. Description Draws an unfilled oval within bounding rectangle from (x, y) of size width x height.
http://localhost/java/javaref/awt/ch19_27.htm (12 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
drawPolygon public abstract void drawPolygon (int xPoints[], int yPoints[], int numPoints) Parameters xPoints[] The array of x coordinates for each point. yPoints[] The array of y coordinates for each point. numPoints The number of elements in both xPoints and yPoints arrays to use. Description Draws an unfilled polygon based on first numPoints elements in xPoints and yPoints. public void drawPolygon (Polygon p) Parameters p Points of object to draw. Description Draws an unfilled polygon based on points within the Polygon p.
drawPolyline public abstract void drawPolyline (int xPoints[], int yPoints[], int nPoints) Parameters xPoints[] The array of x coordinates for each point. yPoints[] The array of y coordinates for each point. nPoints The number of elements in both xPoints and yPoints arrays to use. Description Draws a series of line segments based on first numPoints elements in xPoints and yPoints.
http://localhost/java/javaref/awt/ch19_27.htm (13 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
drawRect public void drawRect (int x, int y, int width, int height) Parameters x x coordinate of rectangle origin. y y coordinate of rectangle origin width Width of rectangle to draw. height Height of rectangle to draw. Description Draws an unfilled rectangle from (x, y) of size width x height.
drawRoundRect public abstract void drawRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight) Parameters x x coordinate of bounding rectangle origin. y y coordinate of bounding rectangle origin width Width of rectangle to draw. height Height of rectangle to draw. arcWidth Width of arc of rectangle corner. arcHeight Height of arc of rectangle corner. Description Draws an unfilled rectangle from (x, y) of size width x height with rounded corners.
http://localhost/java/javaref/awt/ch19_27.htm (14 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
drawString public abstract void drawString (String text, int x, int y) Parameters text Text to draw. x x coordinate of baseline origin. y y coordinate of baseline origin. Description Draws text on screen.
fill3DRect public void fill3DRect (int x, int y, int width, int height, boolean raised) Parameters x x coordinate of rectangle origin. y y coordinate of rectangle origin width Width of rectangle to draw. height Height of rectangle to draw. raised true to draw a rectangle that appears raised; false to draw a rectangle that appears depressed. Description Draws a filled 3-D rectangle from (x, y) of size width x height.
fillArc public abstract void fillArc (int x, int y, int width, int height, int startAngle, int arcAngle) Parameters x x coordinate of bounding rectangle origin.
http://localhost/java/javaref/awt/ch19_27.htm (15 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
y y coordinate of bounding rectangle origin width Width of bounding rectangle to draw in. height Height of bounding rectangle to draw in. startAngle Starting angle of arc. arcAngle The extent of the arc, measured from startAngle Description Draws a filled arc from startAngle to arcAngle within bounding rectangle from (x, y) of size width x height. Zero degrees is at three o'clock; positive angles are counter clockwise.
fillOval public abstract void fillOval (int x, int y, int width, int height) Parameters x x coordinate of bounding rectangle origin. y y coordinate of bounding rectangle origin width Width of bounding rectangle to draw in. height Height of bounding rectangle to draw in. Description Draws filled oval within bounding rectangle from (x, y) of size width x height.
fillPolygon public abstract void fillPolygon (int xPoints[], int yPoints[], int numPoints) Parameters xPoints[] The array of x coordinates for each point. yPoints[]
http://localhost/java/javaref/awt/ch19_27.htm (16 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
The array of y coordinates for each point. numPoints The number of elements in both xPoints and yPoints arrays to use. Throws ArrayIndexOutOfBoundsException If numPoints > xPoints.length or numPoints > yPoints.length. Description Draws filled polygon based on first numPoints elements in xPoints and yPoints. public void fillPolygon (Polygon p) Parameters p Points of object to draw. Description Draws filled polygon based on points within the Polygon p.
fillRect public abstract void fillRect (int x, int y, int width, int height) Parameters x x coordinate of rectangle origin. y y coordinate of rectangle origin width Width of rectangle to draw. height Height of rectangle to draw. Description Draws filled rectangle from (x, y) of size width x height.
fillRoundRect public abstract void fillRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight) Parameters x x coordinate of bounding rectangle origin. http://localhost/java/javaref/awt/ch19_27.htm (17 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
y y coordinate of bounding rectangle origin width Width of rectangle to draw. height Height of rectangle to draw. arcWidth Width of arc of rectangle corner. arcHeight Height of arc of rectangle corner. Description Draws a filled rectangle from (x, y) of size width x height with rounded corners.
finalize public void finalize() Overrides Object.finalize() Description Tells the garbage collector to dispose of graphics context.
getClip public abstract Shape getClip () Returns Shape describing the clipping are of the graphics context.
getClipBounds public abstract Rectangle getClipBounds() Returns Rectangle describing the clipping area of the graphics context.
getClipRect public abstract Rectangle getClipRect() Returns http://localhost/java/javaref/awt/ch19_27.htm (18 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
Replaced by getClipBounds().
getColor public abstract Color getColor() Returns The current drawing Color of the graphics context.
getFont public abstract Font getFont() Returns The current Font of the graphics context.
getFontMetrics public FontMetrics getFontMetrics() Returns The FontMetrics of the current font of the graphics context. public abstract FontMetrics getFontMetrics (Font font) Parameters font Font to get metrics for. Returns The FontMetrics of the given font for the graphics context.
setClip public abstract void setClip (int x, int y, int width, int height) Parameters x x coordinate of rectangle y y coordinate of rectangle width width of rectangle
http://localhost/java/javaref/awt/ch19_27.htm (19 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
height height of rectangle Description Changes current clipping region to the specified rectangle. public abstract void setClip (Shape clip) Parameters clip The new clipping shape. Description Changes current clipping region to the specified shape.
setColor public abstract void setColor (Color color) Parameters color New color. Description Changes current drawing color of graphics context.
setFont public abstract void setFont (Font font) Parameters font New font. Description Changes current font of graphics context.
setPaintMode public abstract void setPaintMode() Description Changes painting mode to normal mode.
http://localhost/java/javaref/awt/ch19_27.htm (20 of 21) [20/12/2001 11:11:34]
[Chapter 19] Graphics
setXORMode public abstract void setXORMode (Color xorColor) Parameters xorColor XOR mode drawing color. Description Changes painting mode to XOR mode; in this mode, drawing the same object in the same color at the same location twice has no net effect.
toString public String toString() Returns A string representation of the Graphics object. Overrides Object.toString()
translate public void translate (int x, int y) Parameters x x coordinate of new drawing origin. y y coordinate of new drawing origin. Description Moves the origin of drawing operations to (x, y).
See Also Color, Font, FontMetrics, Image, ImageObserver, Object, Polygon, Rectangle, Shape, String
Frame
http://localhost/java/javaref/awt/ch19_27.htm (21 of 21) [20/12/2001 11:11:34]
GridBagConstraints
[Chapter 19] GridBagConstraints
Chapter 19 java.awt Reference
GridBagConstraints Name GridBagConstraints
Description The GridBagConstraints class provides the means to control the layout of components within a Container whose LayoutManager is GridBagLayout.
Class Definition public class java.awt.GridBagConstraints extends java.lang.Object implements java.lang.Cloneable, java.io.Serializable { // Constants public final public final public final public final public final public final public final public final
static static static static static static static static
int int int int int int int int
BOTH; CENTER; EAST; HORIZONTAL; NONE; NORTH; NORTHEAST; NORTHWEST;
http://localhost/java/javaref/awt/ch19_28.htm (1 of 7) [20/12/2001 11:11:37]
[Chapter 19] GridBagConstraints
public public public public public public public
final final final final final final final
static static static static static static static
int int int int int int int
RELATIVE; REMAINDER; SOUTH; SOUTHEAST; SOUTHWEST; VERTICAL; WEST;
// Variables public int anchor; public int fill; public int gridheight; public int gridwidth; public int gridx; public int gridy; public Insets insets; public int ipadx; public int ipady; public double weightx public double weighty // Constructors public GridBagConstraints(); // Instance Methods public Object clone(); }
Constants BOTH public final static int BOTH Constant for possible fill value.
CENTER public final static int CENTER Constant for possible anchor value.
http://localhost/java/javaref/awt/ch19_28.htm (2 of 7) [20/12/2001 11:11:37]
[Chapter 19] GridBagConstraints
EAST public final static int EAST Constant for possible anchor value.
HORIZONTAL public final static int HORIZONTAL Constant for possible fill value.
NONE public final static int NONE Constant for possible fill value.
NORTH public final static int NORTH Constant for possible anchor value.
NORTHEAST public final static int NORTHEAST Constant for possible anchor value.
NORTHWEST public final static int NORTHWEST Constant for possible anchor value.
RELATIVE public final static int RELATIVE Constant for possible gridx, gridy, gridwidth, or gridheight value.
http://localhost/java/javaref/awt/ch19_28.htm (3 of 7) [20/12/2001 11:11:37]
[Chapter 19] GridBagConstraints
REMAINDER public final static int REMAINDER Constant for possible gridwidth or gridheight value.
SOUTH public final static int SOUTH Constant for possible anchor value.
SOUTHEAST public final static int SOUTHEAST Constant for possible anchor value.
SOUTHWEST public final static int SOUTHWEST Constant for possible anchor value.
VERTICAL public final static int VERTICAL Constant for possible fill value.
WEST public final static int WEST Constant for possible anchor value.
Variables anchor public int anchor Specifies the alignment of the component in the event that it is smaller than the space allotted for it by the layout manager; e.g., CENTER centers the object within the region.
http://localhost/java/javaref/awt/ch19_28.htm (4 of 7) [20/12/2001 11:11:37]
[Chapter 19] GridBagConstraints
fill public int fill The component's resize policy if additional space available.
gridheight public int gridheight Number of columns a component occupies.
gridwidth public int gridwidth Number of rows a component occupies.
gridx public int gridx Horizontal grid position at which to add component.
gridy public int gridy Vertical grid position at which to add component.
insets public Insets insets Specifies the outer padding around the component.
ipadx public int ipadx Serves as the internal padding within the component in both the right and left directions.
http://localhost/java/javaref/awt/ch19_28.htm (5 of 7) [20/12/2001 11:11:37]
[Chapter 19] GridBagConstraints
ipady public int ipady Serves as the internal padding within the component in both the top and bottom directions.
weightx public double weightx Represents the percentage of extra horizontal space that will be given to this component if there is additional space available within the container.
weighty public double weighty Represents the percentage of extra vertical space that will be given to this component if there is additional space available within the container.
Constructors GridBagConstraints public GridBagConstraints() Description Constructs a GridBagConstraints object.
Instance Methods clone public Object clone() Returns A new instance of GridBagConstraints with same values for constraints. Overrides Object.clone()
http://localhost/java/javaref/awt/ch19_28.htm (6 of 7) [20/12/2001 11:11:37]
[Chapter 19] GridBagConstraints
See Also Cloneable, GridBagLayout, Insets, Object, Serializable
Graphics
http://localhost/java/javaref/awt/ch19_28.htm (7 of 7) [20/12/2001 11:11:37]
GridBagLayout
[Chapter 19] GridBagLayout
Chapter 19 java.awt Reference
GridBagLayout Name GridBagLayout
Description The GridBagLayout LayoutManager provides the means to layout components in a flexible grid-based display model.
Class Definition public class java.awt.GridBagLayout extends java.lang.Object implements java.awt.LayoutManager2, java.io.Serializable { // Protected Constants protected static final MAXGRIDSIZE; protected static final MINSIZE; protected static final PREFERREDSIZE; // Variables public double columnWeights[]; public int columnWidths[]; http://localhost/java/javaref/awt/ch19_29.htm (1 of 11) [20/12/2001 11:11:40]
[Chapter 19] GridBagLayout
public int rowHeights[]; public double rowWeights[]; // Protected Variables protected Hashtable comptable; protected GridBagConstraints defaultConstraints; protected GridBagLayoutInfo layoutInfo; // Constructors public GridBagLayout(); // Instance Methods public void addLayoutComponent (Component comp, Object constraints); public void addLayoutComponent (String name, Component component); public GridBagConstraints getConstraints (Component component); public abstract float getLayoutAlignmentX(Container target); public public public public
abstract float getLayoutAlignmentY(Container target); int[][] getLayoutDimensions(); Point getLayoutOrigin(); double[][] getLayoutWeights();
public abstract void invalidateLayout(Container target); public void layoutContainer (Container target); public Point location (int x, int y); public abstract Dimension maximumLayoutSize(Container target); public Dimension minimumLayoutSize (Container target); public Dimension preferredLayoutSize (Container target); public void removeLayoutComponent (Component component); public void setConstraints (Component component, GridBagConstraints constraints); public String toString(); // Protected Instance Methods protected void AdjustForGravity (GridBagConstraints constraints, Rectangle r); protected void ArrangeGrid (Container target); protected GridBagLayoutInfo GetLayoutInfo (Container target, int sizeFlag); protected Dimension GetMinSize (Container target, GridBagLayoutInfo info); protected GridBagConstraints lookupConstraints (Component comp); }
http://localhost/java/javaref/awt/ch19_29.htm (2 of 11) [20/12/2001 11:11:40]
[Chapter 19] GridBagLayout
Protected Constants MAXGRIDSIZE protected static final MAXGRIDSIZE Maximum number of rows and columns within container managed by GridBagLayout.
MINSIZE protected static final MINSIZE Used for internal sizing purposes.
PREFERREDSIZE protected static final PREFERREDSIZE Used for internal sizing purposes.
Variables columnWeights public double[] columnWeights The weightx values of the components in the row with the most elements.
columnWidths public int[] columnWidths The width values of the components in the row with the most elements.
rowHeights public int[] rowHeights The height values of the components in the column with the most elements.
rowWeights public double[] rowWeights The weighty values of the components in the column with the most elements.
http://localhost/java/javaref/awt/ch19_29.htm (3 of 11) [20/12/2001 11:11:40]
[Chapter 19] GridBagLayout
Protected Variables comptable protected Hashtable comptable Internal table to manage components.
defaultConstraints protected GridBagConstraints defaultConstraints Constraints to use for Components that have none.
layoutInfo protected GridBagLayoutInfo layoutInfo Internal information about the GridBagLayout.
Constructors GridBagLayout public GridBagLayout() Description Constructs a GridBagLayout object.
Instance Methods addLayoutComponent public void addLayoutComponent (Component comp, Object constraints) Parameters comp The component being added. constraints An object describing the constraints on this component. Implements LayoutManager2.addLayoutComponent() http://localhost/java/javaref/awt/ch19_29.htm (4 of 11) [20/12/2001 11:11:40]
[Chapter 19] GridBagLayout
Description Adds the component comp to container subject to the given constraints. This is a more generalized version of addLayoutComponent(String, Component). It corresponds to java.awt.Container's add(Component, Object). public void addLayoutComponent (String name, Component component) Parameters name Name of component to add. component Actual component being added. Implements LayoutManager.addLayoutComponent() Description Does nothing.
getConstraints public GridBagConstraints getConstraints (Component component) Parameters component Component whose constraints are desired Returns GridBagConstraints for component requested.
getLayoutAlignmentX public abstract float getLayoutAlignmentX (Container target) Parameters target The container to inspect. Returns The value .5 for all containers. Description This method returns the preferred alignment of the given container target. A return value of 0 is left aligned, .5 is centered, and 1 is right aligned. http://localhost/java/javaref/awt/ch19_29.htm (5 of 11) [20/12/2001 11:11:41]
[Chapter 19] GridBagLayout
getLayoutAlignmentY public abstract float getLayoutAlignmentY (Container target) Parameters target The container to inspect. Returns The value .5 for all containers. Description This method returns the preferred alignment of the given container target. A return value of 0 is top aligned, .5 is centered, and 1 is bottom aligned.
getLayoutDimensions public int[][] getLayoutDimensions() Returns Returns two single dimension arrays as a multi-dimensional array. Index 0 is an array of widths (columnWidths instance variable), while index 1 is an array of heights (rowHeights instance variable).
getLayoutOrigin public Point getLayoutOrigin() Returns Returns the origin of the components within the Container whose LayoutManager is GridBagLayout.
getLayoutWeights public double[][] getLayoutWeights() Returns Returns two single dimension arrays as a multi-dimensional array. Index 0 is an array of columns weights (columnWeights instance variable), while index 1 is an array of row weights (rowWeights instance variable).
http://localhost/java/javaref/awt/ch19_29.htm (6 of 11) [20/12/2001 11:11:41]
[Chapter 19] GridBagLayout
invalidateLayout public abstract void invalidateLayout (Container target) Parameters target The container to invalidate. Description Does nothing.
layoutContainer public void layoutContainer (Container target) Parameters target The container that needs to be redrawn. Implements LayoutManager.layoutContainer() Description Draws components contained within target.
location public Point location (int x, int y) Parameters x The x coordinate of the grid position to find. y The y coordinate of the grid position to find. Returns Returns the grid element under the location provided at position (x, y) in pixels. Note that the returned Point uses the GridBagLayout's grid for its coordinate space. Description Locates the grid position in the Container under the given location.
http://localhost/java/javaref/awt/ch19_29.htm (7 of 11) [20/12/2001 11:11:41]
[Chapter 19] GridBagLayout
maximumLayoutSize public abstract Dimension maximumLayoutSize (Container target) Parameters target The container to inspect. Returns A Dimension whose horizontal and vertical components are Integer.MAX_VALUE. Description For GridBagLayout, a maximal Dimension is always returned.
minimumLayoutSize public Dimension minimumLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Minimum Dimension of container target. Implements LayoutManager.minimumLayoutSize() Description Calculates minimum size of target container.
preferredLayoutSize public Dimension preferredLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Preferred Dimension of container target Implements LayoutManager.preferredLayoutSize() Description http://localhost/java/javaref/awt/ch19_29.htm (8 of 11) [20/12/2001 11:11:41]
[Chapter 19] GridBagLayout
Calculates preferred size of target container.
removeLayoutComponent public void removeLayoutComponent (Component component) Parameters component Component to stop tracking. Implements LayoutManager.removeLayoutComponent() Description Does nothing.
setConstraints public void setConstraints (Component component, GridBagConstraints constraints) Parameters component Component to set constraints for constraints Constraints for component Description Changes the GridBagConstraints on component to those provided.
toString public String toString() Returns A string representation of the GridBagLayout object. Overrides Object.toString()
Protected Instance Methods
http://localhost/java/javaref/awt/ch19_29.htm (9 of 11) [20/12/2001 11:11:41]
[Chapter 19] GridBagLayout
AdjustForGravity protected void AdjustForGravity (GridBagConstraints constraints, Rectangle r) Parameters constraints Constraints to use for adjustment of Rectangle. r Rectangular area that needs to be adjusted. Description Helper routine for laying out a cell of the grid. The routine adjusts the values for r based upon the constraints.
ArrangeGrid protected void ArrangeGrid (Container target) Parameters target Container to layout. Description Helper routine that does the actual arrangement of components in target.
GetLayoutInfo protected GridBagLayoutInfo GetLayoutInfo (Container target, int sizeFlag) Parameters target Container to get information about. sizeFlag One of the constants MINSIZE or PREFERREDSIZE. Returns Returns an internal class used to help size the container.
GetMinSize protected Dimension GetMinSize (Container target, GridBagLayoutInfo info) Parameters
http://localhost/java/javaref/awt/ch19_29.htm (10 of 11) [20/12/2001 11:11:41]
[Chapter 19] GridBagLayout
target Container to calculate size. info Specifics about the container's constraints. Returns Minimum Dimension of container target based on info. Description Helper routine for calculating size of container.
lookupConstraints protected GridBagConstraints lookupConstraints (Component comp) Parameters comp Component in question. Returns A reference to the GridBagConstraints object for this component. Description Helper routine for calculating size of container.
See Also Component, Container, Dimension, GridBagConstraints, Hashtable, LayoutManager, LayoutManager2, Object, Point, Rectangle, String
GridBagConstraints
http://localhost/java/javaref/awt/ch19_29.htm (11 of 11) [20/12/2001 11:11:41]
GridLayout
[Chapter 19] GridLayout
Chapter 19 java.awt Reference
GridLayout Name GridLayout
Description The GridLayout LayoutManager provides the means to layout components in a grid of rows and columns.
Class Definition public class java.awt.GridLayout extends java.lang.Object implements java.awt.LayoutManager, java.io.Serializable { // Constructors public GridLayout(); public GridLayout (int rows, int cols); public GridLayout (int rows, int cols, int hgap, int vgap); // Instance Methods public void addLayoutComponent (String name, Component component);
http://localhost/java/javaref/awt/ch19_30.htm (1 of 7) [20/12/2001 11:11:43]
[Chapter 19] GridLayout
public int getColumns(); public int getHgap(); public int getRows(); public public public public public
int getVgap(); void layoutContainer (Container target); Dimension minimumLayoutSize (Container target); Dimension preferredLayoutSize (Container target); void removeLayoutComponent (Component component);
public int setColumns(int cols); public int setHgap(int hgap); public int setRows(int rows); public int setVgap(int vgap); public String toString(); }
Constructors GridLayout public GridLayout() Description Constructs a GridLayout object with a default single row and one column per component. public GridLayout (int rows, int cols) Parameters rows Requested number of rows in container. cols Requested number of columns in container. Description Constructs a GridLayout object with the requested number of rows and columns. Note that the actual number of rows and columns depends on the number of objects in the layout, not the constructor's parameters. public GridLayout (int rows, int cols, int hgap, int vgap) http://localhost/java/javaref/awt/ch19_30.htm (2 of 7) [20/12/2001 11:11:43]
[Chapter 19] GridLayout
Parameters rows Requested number of rows in container. cols Requested number of columns in container. hgap Horizontal space between each component in a row. vgap Vertical space between each row. Description Constructs a GridLayout object with the requested number of rows and columns and the values specified as the gaps between each component. Note that the actual number of rows and columns depends on the number of objects in the layout, not the constructor's parameters.
Instance Methods addLayoutComponent public void addLayoutComponent (String name, Component component) Parameters name Name of component to add. component Actual component being added. Implements LayoutManager.addLayoutComponent() Description Does nothing.
getColumns public int getColumns() Returns The number of columns. http://localhost/java/javaref/awt/ch19_30.htm (3 of 7) [20/12/2001 11:11:43]
[Chapter 19] GridLayout
getHgap public int getHgap() Returns The horizontal gap for this GridLayout instance.
getRows public int getRows() Returns The number of rows.
getVgap public int getVgap() Returns The vertical gap for this GridLayout instance.
layoutContainer public void layoutContainer (Container target) Parameters target The container that needs to be redrawn. Implements LayoutManager.layoutContainer() Description Draws the components contained within the target.
minimumLayoutSize public Dimension minimumLayoutSize (Container target) Parameters target
http://localhost/java/javaref/awt/ch19_30.htm (4 of 7) [20/12/2001 11:11:43]
[Chapter 19] GridLayout
The container whose size needs to be calculated. Returns Minimum Dimension of the container target. Implements LayoutManager.minimumLayoutSize() Description Calculates the minimum size of the target container.
preferredLayoutSize public Dimension preferredLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Preferred Dimension of the container target. Implements LayoutManager.preferredLayoutSize() Description Calculates the preferred size of the target container.
removeLayoutComponent public void removeLayoutComponent (Component component) Parameters component Component to stop tracking. Implements LayoutManager.removeLayoutComponent() Description Does nothing.
http://localhost/java/javaref/awt/ch19_30.htm (5 of 7) [20/12/2001 11:11:43]
[Chapter 19] GridLayout
setColumns public void setColumns(int cols) Parameters cols The new number of columns. Description Sets the number of columns.
setHgap public void setHgap(int hgap) Parameters hgap The horizontal gap value. Description Sets the horizontal gap between components.
setRows public void setRows(int rows) Parameters rows The new number of rows. Description Sets the number of rows.
setVgap public void setVgap(int vgap) Parameters vgap The vertical gap value. Description
http://localhost/java/javaref/awt/ch19_30.htm (6 of 7) [20/12/2001 11:11:43]
[Chapter 19] GridLayout
Sets the vertical gap between components.
toString public String toString() Returns A string representation of the GridLayout object. Overrides Object.toString()
See Also Component, Container, Dimension, LayoutManager, Object, String
GridBagLayout
http://localhost/java/javaref/awt/ch19_30.htm (7 of 7) [20/12/2001 11:11:43]
IllegalComponentStateException
[Chapter 19] IllegalComponentStateException
Chapter 19 java.awt Reference
IllegalComponentStateException Name IllegalComponentStateException
Description An Exception indicating that a Component was not in an appropriate state to perform a requested action.
Class Definition public class java.awt.IllegalComponentStateException extends java.lang.IllegalStateException { // Constructors public IllegalComponentStateException(); public IllegalComponentStateException (String s); }
http://localhost/java/javaref/awt/ch19_31.htm (1 of 2) [20/12/2001 11:11:44]
[Chapter 19] IllegalComponentStateException
Constructors IllegalComponentStateException public IllegalComponentStateException() Description Constructs the exception object with no detail message. public IllegalComponentStateException (String s) Parameters s Detail message Description Constructs the exception object with the given detail message.
See Also Exception, String
GridLayout
http://localhost/java/javaref/awt/ch19_31.htm (2 of 2) [20/12/2001 11:11:44]
Image
[Chapter 19] Image
Chapter 19 java.awt Reference
Image Name Image
Description The Image class represents a displayable object maintained in memory. Because Image is an abstract class, you never work with the Image class itself, but with a platform specific subclass. However, you should never need to know what that subclass is. To draw on an Image, get its graphics context.
Class Definition public abstract class java.awt.Image extends java.lang.Object implements java.io.Serializable { // Constants public final static int SCALE_AREA_AVERAGING; public final static int SCALE_DEFAULT; public final static int SCALE_FAST; public final static int SCALE_REPLICATE; public final static int SCALE_SMOOTH; public final static Object UndefinedProperty; // Instance Methods public abstract void flush();
http://localhost/java/javaref/awt/ch19_32.htm (1 of 5) [20/12/2001 11:11:47]
[Chapter 19] Image
public abstract Graphics getGraphics(); public abstract int getHeight (ImageObserver observer); public abstract Object getProperty (String name, ImageObserver observer); public Image getScaledInstance (int width, int height, int hints); public abstract ImageProducer getSource(); public abstract int getWidth (ImageObserver observer); }
Constants SCALE_AREA_AVERAGING public final static int SCALE_AREA_AVERAGING Flag that requests use of AreaAveragingScaleFilter.
SCALE_DEFAULT public final static int SCALE_DEFAULT Flag that requests use of the default image scaling algorithm.
SCALE_FAST public final static int SCALE_FAST Flag that requests use of an image scaling algorithm that is faster rather than smoother.
SCALE_REPLICATE public final static int SCALE_REPLICATE Flag that requests use of ReplicateScaleFilter.
SCALE_SMOOTH public final static int SCALE_SMOOTH Flag that requests use of an image scaling algorithm that is smoother rather than faster.
UndefinedProperty public final static Object UndefinedProperty Possible return object from getProperty().
http://localhost/java/javaref/awt/ch19_32.htm (2 of 5) [20/12/2001 11:11:47]
[Chapter 19] Image
Instance Methods flush public abstract void flush() Description Resets image to initial state.
getGraphics public abstract Graphics getGraphics() Throws ClassCastException If image created from file or URL. Returns The graphics context of the image. Description Gets the graphics context of the image for drawing.
getHeight public abstract int getHeight (ImageObserver observer) Parameters observer An image observer; usually the Component on which the image is rendered. Returns Image height, or -1 if the height is not yet available.
getProperty public abstract Object getProperty (String name, ImageObserver observer) Parameters name Name of the property to fetch. observer An image observer; usually the Component on which the image is rendered. Returns
http://localhost/java/javaref/awt/ch19_32.htm (3 of 5) [20/12/2001 11:11:47]
[Chapter 19] Image
Object representing the requested property, null, or UndefinedProperty. Throws ArrayIndexOutOfBoundsException If offset or length is invalid. Description Retrieves a property from the image's private property list.
getScaledInstance public Image getScaledInstance (int width, int height, int hints) Parameters width The width for the scaled image. Use -1 to preserve the aspect ratio with reference to height. height The height for the scaled image. Use -1 to preserve the aspect ratio with reference to width. hints One or more of the SCALE_ constants. Returns The scaled image. It may be loaded asynchronously, even if the original image was fully loaded. Description Creates a copy of an image, scaled to width x height and using an algorithm chosen based on the hints given.
getSource public abstract ImageProducer getSource() Returns The ImageProducer of the image.
getWidth public abstract int getWidth (ImageObserver observer) Parameters observer An image observer; usually the Component on which the image is rendered. Returns Image width, or -1 if the width is not yet available. http://localhost/java/javaref/awt/ch19_32.htm (4 of 5) [20/12/2001 11:11:47]
[Chapter 19] Image
See Also Graphics, ImageObserver, ImageProducer, Object, Properties, String
IllegalComponentStateException
http://localhost/java/javaref/awt/ch19_32.htm (5 of 5) [20/12/2001 11:11:47]
Insets
[Chapter 19] Insets
Chapter 19 java.awt Reference
Insets Name Insets
Description The Insets class provides a way to encapsulate the layout margins of the four different sides of a Container.
Class Definition public class java.awt.Insets extends java.lang.Object implements java.io.Serializable, java.lang.Cloneable { // Variables public int bottom; public int left; public int right; public int top; // Constructors public Insets (int top, int left, int bottom, int right);
http://localhost/java/javaref/awt/ch19_33.htm (1 of 4) [20/12/2001 11:11:49]
[Chapter 19] Insets
// Instance Methods public Object clone(); public boolean equals (Object obj); public String toString(); }
Variables bottom public int bottom The border width for the bottom of a Container.
left public int left The border width for the left side of a Container.
right public int right The border width for the right side of a Container.
top public int top The border width for the top of a Container.
Constructors Insets public Insets (int top, int left, int bottom, int right) Parameters top The border width for the top of a Container. left The border width for the left side of a Container. http://localhost/java/javaref/awt/ch19_33.htm (2 of 4) [20/12/2001 11:11:49]
[Chapter 19] Insets
bottom The border width for the bottom of a Container. right The border width for the right side of a Container. Description Constructs an Insets object with the appropriate border settings.
Instance Methods clone public Object clone() Returns Clone of original object. Overrides Object.clone() Description Creates a copy of the original instance of an object.
equals public boolean equals (Object obj) Parameters obj The object to be tested. Returns true if the objects are equal; false otherwise. Overrides Object.equals(Object) Description Tests two Insets objects for equality.
http://localhost/java/javaref/awt/ch19_33.htm (3 of 4) [20/12/2001 11:11:49]
[Chapter 19] Insets
toString public String toString() Returns A string representation of the Insets object. Overrides Object.toString()
See Also Cloneable, Container, Object, Serializable, String
Image
http://localhost/java/javaref/awt/ch19_33.htm (4 of 4) [20/12/2001 11:11:49]
ItemSelectable
[Chapter 19] ItemSelectable
Chapter 19 java.awt Reference
ItemSelectable Name ItemSelectable
Description An interface that describes an object that has one or more items that can be selected.
Interface Definition public abstract interface ItemSelectable { // Instance Methods public abstract void addItemListener (ItemListener l); public abstract Object[] getSelectedObjects(); public abstract void removeItemListener (ItemListener l); }
http://localhost/java/javaref/awt/ch19_34.htm (1 of 2) [20/12/2001 11:11:52]
[Chapter 19] ItemSelectable
Interface Methods addItemListener public abstract void addItemListener (ItemListener l) Parameters l The listener to be added. Description Adds a listener for ItemEvent objects.
getSelectedObjects public abstract Object[] getSelectedObjects() Description This method returns an array containing Objects representing the items that are currently selected. If no items are selected, null is returned.
removeItemListener public abstract void removeItemListener (ItemListener l) Parameters l The listener to be removed. Description Removes the specified ItemListener so it will not receive ItemEvent objects.
See Also Checkbox, CheckboxMenuItem, Choice, ItemEvent, ItemListener, List
Insets
http://localhost/java/javaref/awt/ch19_34.htm (2 of 2) [20/12/2001 11:11:52]
Label
[Chapter 19] Label
Chapter 19 java.awt Reference
Label Name Label
Description The Label is a Component that displays a single line of static text.
Class Definition public class java.awt.Label extends java.awt.Component { // Constants public static final int CENTER; public static final int LEFT; public static final int RIGHT; // Constructors public Label(); public Label (String label); public Label (String label, int alignment); // Instance Methods public void addNotify(); http://localhost/java/javaref/awt/ch19_35.htm (1 of 5) [20/12/2001 11:11:53]
[Chapter 19] Label
public public public public
int getAlignment(); String getText(); synchronized void setAlignment (int alignment); synchronized void setText (String label);
// Protected Instance Methods protected String paramString(); }
Constants CENTER public static final int CENTER Description Constant to center text within the label.
LEFT public static final int LEFT Description Constant to left justify text within the label.
RIGHT public static final int RIGHT Description Constant to right justify text within the label.
Constructors Label public Label() Description Constructs a Label object with the text centered within the label. public Label (String label)
http://localhost/java/javaref/awt/ch19_35.htm (2 of 5) [20/12/2001 11:11:53]
[Chapter 19] Label
Parameters label The text for the label Description Constructs a Label object with the text label centered within the label. public Label (String label, int alignment) Parameters label The text for the label alignment The alignment for the label; one of the constants CENTER, LEFT, or RIGHT. Throws IllegalArgumentException If alignment is not one of CENTER, LEFT, or RIGHT. Description Constructs a Label object, with a given alignment and text of label.
Instance Methods addNotify public void addNotify() Overrides Component.addNotify() Description Creates Label's peer.
getAlignment public int getAlignment() Returns Current alignment.
http://localhost/java/javaref/awt/ch19_35.htm (3 of 5) [20/12/2001 11:11:53]
[Chapter 19] Label
getText public String getText() Returns Current text of Label.
setAlignment public synchronized void setAlignment (int alignment) Parameters alignment New alignment for Label; CENTER, LEFT, or RIGHT. Throws IllegalArgumentException If alignment is not one of CENTER, LEFT, or RIGHT. Description Changes the current alignment of Label.
setText public synchronized void setText (String label) Parameters label New text for Label. Description Changes the current text of Label.
Protected Instance Methods paramString protected String paramString() Returns String with current settings of Label. Overrides http://localhost/java/javaref/awt/ch19_35.htm (4 of 5) [20/12/2001 11:11:53]
[Chapter 19] Label
Component.paramString() Description Helper method for toString() to generate string of current settings.
See Also Component, String
ItemSelectable
http://localhost/java/javaref/awt/ch19_35.htm (5 of 5) [20/12/2001 11:11:53]
LayoutManager
[Chapter 19] LayoutManager
Chapter 19 java.awt Reference
LayoutManager Name LayoutManager
Description LayoutManager is an interface that defines the responsibilities of an object that wants to lay out Components to the display in a Container.
Interface Definition public abstract interface java.awt.LayoutManager { // Interface Methods public abstract void addLayoutComponent (String name, Component component); public abstract void layoutContainer (Container target); public abstract Dimension minimumLayoutSize (Container target); public abstract Dimension preferredLayoutSize (Container target); public abstract void removeLayoutComponent (Component component); }
http://localhost/java/javaref/awt/ch19_36.htm (1 of 3) [20/12/2001 11:11:55]
[Chapter 19] LayoutManager
Interface Methods addLayoutComponent public abstract void addLayoutComponent (String name, Component component) Parameters name Name of component to add. component Actual component being added. Description Called when you call Container.add(String, Component) to add an object to a container.
layoutContainer public abstract void layoutContainer (Container target) Parameters target The container who needs to be redrawn. Description Called when target needs to be redrawn.
minimumLayoutSize public abstract Dimension minimumLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Minimum Dimension of the container target Description Called when the minimum size of the target container needs to be calculated.
http://localhost/java/javaref/awt/ch19_36.htm (2 of 3) [20/12/2001 11:11:55]
[Chapter 19] LayoutManager
preferredLayoutSize public abstract Dimension preferredLayoutSize (Container target) Parameters target The container whose size needs to be calculated. Returns Preferred Dimension of the container target Description Called when the preferred size of the target container needs to be calculated.
removeLayoutComponent public abstract void removeLayoutComponent (Component component) Parameters component Component to no longer track. Description Called when you call Container.remove(Component) to remove a component from the layout.
See Also Component, Container, FlowLayout, GridLayout, Object, String
Label
http://localhost/java/javaref/awt/ch19_36.htm (3 of 3) [20/12/2001 11:11:55]
LayoutManager2
[Chapter 19] LayoutManager2
Chapter 19 java.awt Reference
LayoutManager2 Name LayoutManager2
Description LayoutManager2 is an extension of LayoutManager. It provides a more generalized way to add components to a container, as well as more sizing and alignment methods.
Interface Definition public abstract interface java.awt.LayoutManager2 extends java.awt.LayoutManager { // Interface Methods public abstract void addLayoutComponent (Component comp, Object constraints); public abstract float getLayoutAlignmentX(Container target); public abstract float getLayoutAlignmentY(Container target); public abstract void invalidateLayout(Container target); public abstract Dimension maximumLayoutSize(Container target); }
http://localhost/java/javaref/awt/ch19_37.htm (1 of 3) [20/12/2001 11:11:57]
[Chapter 19] LayoutManager2
Interface Methods addLayoutComponent public abstract void addLayoutComponent (Component comp, Object constraints) Parameters comp Component to add. constraints Constraints on the component. Description Called to add an object to a container. This is slightly more generic than LayoutManager's addLayoutComponent(String, Component).
getLayoutAlignmentX public abstract float getLayoutAlignmentX (Container target) Parameters target The container to inspect. Returns A value between 0 and 1. Description This method returns the preferred alignment of the given container target. A return value of 0 is left aligned, .5 is centered, and 1 is right aligned.
getLayoutAlignmentY public abstract float getLayoutAlignmentY (Container target) Parameters target The container to inspect. Returns A value between 0 and 1. Description http://localhost/java/javaref/awt/ch19_37.htm (2 of 3) [20/12/2001 11:11:57]
[Chapter 19] LayoutManager2
This method returns the preferred alignment of the given container target. A return value of 0 is top aligned, .5 is centered, and 1 is bottom aligned.
invalidateLayout public abstract void invalidateLayout (Container target) Parameters target The container to invalidate. Description Sophisticated layout managers may cache information to improve performance. This method can be used to signal the manager to discard any cached information and start fresh.
maximumLayoutSize public abstract Dimension maximumLayoutSize (Container target) Returns The maximum size of target. Parameters target The container to inspect. Description This method returns the maximum size of target using this layout manager.
See Also BorderLayout, CardLayout, Component, Container, GridBagLayout, Object, String
LayoutManager
http://localhost/java/javaref/awt/ch19_37.htm (3 of 3) [20/12/2001 11:11:57]
List
[Chapter 19] List
Chapter 19 java.awt Reference
List Name List
Description The List is a Component that provides a scrollable list of choices to select from. A List can be in one of two modes: single selection mode, in which only one item may be selected at a time; and multiple selection mode, in which several items may be selected at one time. A list does not necessarily display all of the choices at one time; one of the constructors lets you specify the number of choices to display simultaneously. Although the changes in 1.1 are extensive, almost all of them can be boiled down to (1) using the 1.1 event model, and (2) standardizing method names (e.g. set/get pairs).
Class Definition public class java.awt.List extends java.awt.Component implements java.awt.ItemSelectable { // Constructors public List(); public List (int rows); public List (int rows, boolean multipleSelections); // Instance Methods http://localhost/java/javaref/awt/ch19_38.htm (1 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
public void add (String item); public synchronized void add (String item, int index); public void addActionListener (ActionListener l); public void addItem (String item); public synchronized void addItem (String item, int index); public void addItemListener (ItemListener l); public void addNotify(); public boolean allowsMultipleSelections(); public synchronized void clear(); public int countItems(); public synchronized void delItem (int position); public synchronized void delItems (int start, int end); public synchronized void deselect (int index); public String getItem (int index); public int getItemCount(); public synchronized String[] getItems(); public Dimension getMinimumSize(); public Dimension getMinimumSize (int rows); public Dimension getPreferredSize(); public public public public public public
Dimension getPreferredSize (int rows); int getRows(); synchronized int getSelectedIndex(); synchronized int[] getSelectedIndexes(); synchronized String getSelectedItem(); synchronized String[] getSelectedItems();
public Object[] getSelectedObjects(); public int getVisibleIndex(); public boolean isIndexSelected(int index); public boolean isMultipleMode(); public boolean isSelected (int index); public synchronized void makeVisible (int index); public Dimension minimumSize(); public Dimension minimumSize (int rows); public Dimension preferredSize(); public Dimension preferredSize (int rows); public synchronized void remove (int position); public synchronized void remove (String item);
http://localhost/java/javaref/awt/ch19_38.htm (2 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
public void removeActionListener (ActionListener l); public synchronized void removeAll(); public public public public
void removeItemListener (ItemListener l); void removeNotify(); synchronized void replaceItem (String newItem, int index); synchronized void select (int position);
public synchronized void setMultipleMode (boolean b); public synchronized void setMultipleSelections (boolean value); // Protected Instance Methods protected String paramString(); protected void processActionEvent (ActionEvent e); protected void processEvent (AWTEvent e); protected void processItemEvent (ItemEvent e); }
Constructors List public List() Description Constructs a List object in single-selection mode. public List (int rows) Parameters rows Requested number of rows to display. Description Constructs a List object with the specified number of rows, in single-selection mode. public List (int rows, boolean multipleSelections) Parameters rows Requested number of rows to display. multipleSelections http://localhost/java/javaref/awt/ch19_38.htm (3 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
true to allow multiple selections; false to select one item at a time. Description Constructs a List object.
Instance Methods add public void add (String item) Parameters item Text for entry to add. Description Adds a new entry to the available choices. public synchronized void add (String item, int index) Parameters item Text for entry to add. index Position at which to add entry; the first entry has an index of zero. Description Adds a new entry to the available choices at the designated position.
addActionListener public void addActionListener (ActionListener l) Parameters l An object that implements the ActionListener interface. Description Add a listener for the action event.
http://localhost/java/javaref/awt/ch19_38.htm (4 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
addItem public void addItem (String item) Parameters item Text for entry to add. Description Replaced by add(String). public synchronized void addItem (String item, int index) Parameters item Text for entry to add. index Position at which to add entry; the first entry has an index of zero. Description Replaced by add(String, int).
addItemListener public void addItemListener (ItemListener l) Parameters l The listener to be added. Implements ItemSelectable.addItemListener(ItemListener l) Description Adds a listener for the ItemEvent objects this List fires off.
addNotify public void addNotify() Overrides Component.addNotify() http://localhost/java/javaref/awt/ch19_38.htm (5 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
Description Creates List's peer.
allowsMultipleSelections public boolean allowsMultipleSelections() Returns true if multi-selection active, false otherwise. Replaced by isMultipleMode().
clear public synchronized void clear() Description Clears all the entries out of the List. Replaced by removeAll().
countItems public int countItems() Returns Number of items in the List. Replaced by getItemCount().
delItem public synchronized void delItem (int position) Parameters position Position of item to delete. Description Removes a single entry from the List. Replaced by remove(int) and remove(String).
delItems public synchronized void delItems (int start, int end) Parameters start
http://localhost/java/javaref/awt/ch19_38.htm (6 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
Starting position of entries to delete. end Ending position of entries to delete. Description Removes a set of entries from the List.
deselect public synchronized void deselect (int index) Parameters index Position to deselect. Description Deselects the entry at the designated position, if selected.
getItem public String getItem (int index) Parameters index Position of entry to get. Throws ArrayIndexOutOfBoundsException If index is invalid. Returns String for entry at given position.
getItemCount public int getItemCount() Returns Number of items in the List.
http://localhost/java/javaref/awt/ch19_38.htm (7 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
getItems public String[] getItems() Returns The string items in the List.
getMinimumSize public Dimension getMinimumSize() Returns The minimum dimensions of the List. public Dimension getMinimumSize (int rows) Parameters rows Number of rows within List to size. Returns The minimum dimensions of a List of the given size.
getPreferredSize public Dimension getPreferredSize() Returns The preferred dimensions of the List. public Dimension getPreferredSize (int rows) Parameters rows Number of rows within List to size. Returns The preferred dimensions of a List of the given size.
http://localhost/java/javaref/awt/ch19_38.htm (8 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
getRows public int getRows() Returns Returns number of rows requested to be displayed in List.
getSelectedIndex public synchronized int getSelectedIndex() Returns Position of currently selected entry, or -1 if nothing is selected, or if multiple entries are selected.
getSelectedIndexes public synchronized int[] getSelectedIndexes() Returns An array whose elements are the indices of the currently selected entries.
getSelectedItem public synchronized String getSelectedItem() Returns Currently selected entry as a String, or null if nothing is selected, or if multiple entries are selected.
getSelectedItems public synchronized String[] getSelectedItems() Returns An array of strings whose elements are the labels of the currently selected entries.
getSelectedObjects public Object[] getSelectedObjects() Implements ItemSelectable.getSelectedObjects() Returns http://localhost/java/javaref/awt/ch19_38.htm (9 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
An array of strings whose elements are the labels of the currently selected entries.
getVisibleIndex public int getVisibleIndex() Returns The last index from a call to makeVisible().
isIndexSelected public boolean isIndexSelected (int index) Parameters index Position to check. Returns true if index selected, false otherwise. Description Checks to see if a particular entry is currently selected.
isMultipleMode public boolean isMultipleMode() Returns true if multiple selection is allowed, false otherwise.
isSelected public boolean isSelected (int index) Parameters index Position to check. Returns true if index selected, false otherwise. Description
http://localhost/java/javaref/awt/ch19_38.htm (10 of 16) [20/12/2001 11:12:00]
[Chapter 19] List
Checks to see if a particular entry is currently selected. Replaced by isIndexSelected(int).
makeVisible public synchronized void makeVisible (int index) Parameters index Position to make visible on screen. Description Ensures an item is displayed on the screen.
minimumSize public Dimension minimumSize() Returns The minimum dimensions of the List. Replaced by getMinimumSize(). public Dimension minimumSize (int rows) Parameters rows Number of rows within List to size. Returns The minimum dimensions of a List of the given size. Replaced by getMinimumSize(int).
preferredSize public Dimension preferredSize() Returns The preferred dimensions of the List. Replaced by getPreferredSize(). public Dimension preferredSize (int rows) Parameters rows Number of rows within List to size.
http://localhost/java/javaref/awt/ch19_38.htm (11 of 16) [20/12/2001 11:12:01]
[Chapter 19] List
Returns The preferred dimensions of a List of the given size. Replaced by getPreferredSize(int).
remove public synchronized void remove (int position) Parameters position Position of item to remove. Description Removes a single entry from the List. public synchronized void remove (String item) Parameters item Item to remove. Throws IllegalArgumentException If item is not in the List. Description Removes a single entry from the List.
removeActionListener public void removeActionListener (ActionListener l) Parameters l One of this List's ActionListeners. Description Remove an action event listener.
http://localhost/java/javaref/awt/ch19_38.htm (12 of 16) [20/12/2001 11:12:01]
[Chapter 19] List
removeAll public synchronized removeAll() Description Removes all items from the List.
removeItemListener public void removeItemListener (ItemListener l) Parameters l The listener to be removed. Implements ItemSelectable.removeItemListener (ItemListener l) Description Removes the specified ItemListener so it will not receive ItemEvent objects from this List.
removeNotify public void removeNotify() Description Destroys the peer of the List.
replaceItem public synchronized void replaceItem (String newItem, int index) Parameters newItem Label for entry to add. index Position of entry to replace. Description Replaces the contents at a particular position with a new entry.
http://localhost/java/javaref/awt/ch19_38.htm (13 of 16) [20/12/2001 11:12:01]
[Chapter 19] List
select public synchronized void select (int position) Parameters position Position to make selected entry. Description Makes the given entry the selected one for the List.
setMultipleMode public synchronized void setMultipleMode (boolean b) Parameters b true to enable multiple selections; false to disable multiple selections. Description Changes List's selection mode based upon flag.
setMultipleSelections public synchronized void setMultipleSelections (boolean value) Parameters value true to enable multiple selections; false to disable multiple selections. Description Changes List's selection mode based upon flag. Replaced by setMultipleMode(boolean).
Protected Instance Methods paramString protected String paramString() Returns String with current settings of List. http://localhost/java/javaref/awt/ch19_38.htm (14 of 16) [20/12/2001 11:12:01]
[Chapter 19] List
Overrides Component.paramString() Description Helper method for toString() to generate string of current settings.
processActionEvent protected void processActionEvent (ActionEvent e) Parameters e The action event to process. Description Action events are passed to this method for processing. Normally, this method is called by processEvent().
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description Low-level AWTEvents are passed to this method for processing.
processItemEvent protected void processItemEvent(ItemEvent e) Parameters e The item event to process. Description Item events are passed to this method for processing. Normally, this method is called by processEvent().
http://localhost/java/javaref/awt/ch19_38.htm (15 of 16) [20/12/2001 11:12:01]
[Chapter 19] List
See Also Component, Dimension, ItemSelectable, String
LayoutManager2
http://localhost/java/javaref/awt/ch19_38.htm (16 of 16) [20/12/2001 11:12:01]
MediaTracker
[Chapter 19] MediaTracker
Chapter 19 java.awt Reference
MediaTracker Name MediaTracker
Description The MediaTracker class assists in the loading of multimedia objects across the network. It can be used to wait until an object (or group of objects) has been loaded completely. Tracked objects are assigned to groups; if there is more than one object in a group, you can only track the behavior of the group as a whole (i.e., it isn't possible to track an individual object unless it is the only object in its group). Currently (1.0.2 and 1.1) MediaTracker only works for Image objects; future releases may extend MediaTracker to other multi-media types.
Class Definition public abstract class java.awt.MediaTracker extends java.lang.Object implements java.io.Serializable { // Constants public static public static public static public static
final final final final
int int int int
ABORTED; COMPLETE; ERRORED; LOADING;
// Constructors public MediaTracker (Component component); // Instance Methods public void addImage (Image image, int id); public synchronized void addImage (Image image, int id, int width, int height); public boolean checkAll(); public synchronized boolean checkAll (boolean load); public boolean checkID (int id); public synchronized boolean checkID (int id, boolean load); http://localhost/java/javaref/awt/ch19_39.htm (1 of 8) [20/12/2001 11:12:04]
[Chapter 19] MediaTracker
public public public public
synchronized synchronized synchronized synchronized
Object[] getErrorsAny(); Object[] getErrorsID (int id); boolean isErrorAny(); boolean isErrorID (int id);
public synchronized void removeImage(Image image); public synchronized void removeImage(Image image, int id); public synchronized void removeImage(Image image, int id, int width, int height); public synchronized int statusAll (boolean load); public synchronized int statusID (int id, boolean load); public void waitForAll() throws InterruptedException; public synchronized boolean waitForAll (long ms) throws InterruptedException; public void waitForID (int id) throws InterruptedException; public synchronized boolean waitForID (int id, long ms) throws InterruptedException; }
Constants ABORTED public static final int ABORTED Flag that indicates that the loading process aborted while loading a particular image.
COMPLETE public static final int COMPLETE Flag that indicates a particular image loaded successfully.
ERRORED public static final int ERRORED Flag that indicates an error occurred while a particular image was loading.
LOADING public static final int LOADING Flag that indicates a particular image is still loading.
Constructors MediaTracker public MediaTracker (Component component) Parameters component Component that eventually renders objects being tracked. http://localhost/java/javaref/awt/ch19_39.htm (2 of 8) [20/12/2001 11:12:04]
[Chapter 19] MediaTracker
Description Constructs an MediaTracker object.
Instance Methods addImage public void addImage (Image image, int id) Parameters image Image to track. id ID of a group. Description Tells a MediaTracker to track the loading of image, placing the image in the group identified by id. public synchronized void addImage (Image image, int id, int width, int height) Parameters image Image to track. id ID of a group. width Eventual rendering width. height Eventual rendering height. Description Tells a MediaTracker to track the loading of image, which will be scaled to the given height and width, placing the image in the group identified by id.
checkAll public boolean checkAll() Returns true if images completed loading (successfully or unsuccessfully), false otherwise. Description Determines if all images have finished loading. public synchronized boolean checkAll (boolean load) Parameters load http://localhost/java/javaref/awt/ch19_39.htm (3 of 8) [20/12/2001 11:12:04]
[Chapter 19] MediaTracker
Flag to force image loading to start. Returns true if all images have completed loading (successfully or unsuccessfully), false otherwise. Description Determines if all images have finished loading; the load parameter may be used to force images to start loading.
checkID public boolean checkID (int id) Parameters id ID of a group. Returns true if all images have completed loading (successfully or unsuccessfully), false otherwise. Description Determines if all images with the given ID tag have finished loading. public synchronized boolean checkID (int id, boolean load) Parameters id ID of a group. load Flag to force image loading to start. Returns true if all images have completed loading (successfully or unsuccessfully), false otherwise. Description Determines if all images with the given ID tag have finished loading; the load parameter may be used to force images to start loading.
getErrorsAny public synchronized Object[] getErrorsAny() Returns An array of objects managed by this media tracker that encountered a loading error. Description Checks to see if any media encountered an error while loading.
getErrorsID public synchronized Object[] getErrorsID (int id) Parameters
http://localhost/java/javaref/awt/ch19_39.htm (4 of 8) [20/12/2001 11:12:04]
[Chapter 19] MediaTracker
id ID of a group. Returns An array of objects that encountered a loading error. Description Checks to see if any media with the given ID tag encountered an error while loading.
isErrorAny public synchronized boolean isErrorAny() Returns true if an error occurred, false otherwise. Description Checks to see if any media monitored by this media tracker encountered an error while loading.
isErrorID public synchronized boolean isErrorID (int id) Parameters id ID of a group. Returns true if error happened, false otherwise. Description Checks to see if any media in the given group encountered an error while loading.
removeImage public synchronized void removeImage (Image image) Parameters image The image to remove. Description Removes the specified image from this MediaTracker. public synchronized void removeImage (Image image, int id) Parameters image The image to remove. id
http://localhost/java/javaref/awt/ch19_39.htm (5 of 8) [20/12/2001 11:12:04]
[Chapter 19] MediaTracker
ID of a group. Description Removes the specified image from this MediaTracker. Only instances matching the given id will be removed. public synchronized void removeImage (Image image, int id, int width, int height) Parameters image The image to remove. id ID of a group. width Width of the scaled image, or -1 for unscaled. height Height of the scaled image, or -1 for unscaled. Description Removes the specified image from this MediaTracker. Only instances matching the given id and scale sizes will be removed.
statusAll public synchronized int statusAll (boolean load) Parameters load Flag to force image loading to start. Returns MediaTracker status flags ORed together. Description Checks load status of all the images monitored by this media tracker; the load parameter may be used to force images to start loading.
statusID public synchronized int statusID (int id, boolean load) Parameters id ID of a group. load Flag to force image loading to start. Returns MediaTracker status flags ORed together. Description http://localhost/java/javaref/awt/ch19_39.htm (6 of 8) [20/12/2001 11:12:04]
[Chapter 19] MediaTracker
Checks load status of all the images in the given group; the load parameter may be used to force images to start loading.
waitForAll public void waitForAll() throws InterruptedException Throws InterruptedException If waiting interrupted. Description Waits for all the images monitored by this media tracker to load. public synchronized boolean waitForAll (long ms) throws InterruptedException Parameters ms Time to wait for loading. Throws InterruptedException If waiting interrupted. Returns true if images fully loaded, false otherwise. Description Waits at most ms milliseconds for all images monitored by this media tracker to load.
waitForID public void waitForID (int id) throws InterruptedException Parameters id ID of a group. Throws InterruptedException If waiting interrupted. Description Waits for images in the given group to load. public synchronized boolean waitForID (int id, long ms) throws InterruptedException Parameters id ID of a group. ms http://localhost/java/javaref/awt/ch19_39.htm (7 of 8) [20/12/2001 11:12:04]
[Chapter 19] MediaTracker
Maximum time to wait for loading. Throws InterruptedException If waiting interrupted. Returns true if images fully loaded, false otherwise. Description Waits at most ms milliseconds for the images in the given group to load.
See Also Component, Image, Object
List
http://localhost/java/javaref/awt/ch19_39.htm (8 of 8) [20/12/2001 11:12:04]
Menu
[Chapter 19] Menu
Chapter 19 java.awt Reference
Menu Name Menu
Description The Menu class represents a group of MenuItem objects. Menus themselves are menu items, allowing you to build multi-level menus. Menus are always attached to MenuBars, which currently can only belong to frames.
Class Definition public class java.awt.Menu extends java.awt.MenuItem implements java.awt.MenuContainer { // Constructors public Menu(); public Menu (String label); public Menu (String label, boolean tearOff); // Instance Methods
http://localhost/java/javaref/awt/ch19_40.htm (1 of 7) [20/12/2001 11:12:06]
[Chapter 19] Menu
public public public public
synchronized MenuItem add (MenuItem item); void add (String label); void addNotify(); void addSeparator();
public int countItems(); public MenuItem getItem (int index); public int getItemCount(); public void insert (String label, int index); public synchronized void insert (MenuItem menuitem, int index); public void insertSeparator (int index); public boolean isTearOff(); public String paramString(); public synchronized void remove (int index); public synchronized void remove (MenuComponent component); public synchronized void removeAll(); public void removeNotify(); }
Constructors Menu public Menu() Description Constructs a Menu object. public Menu (String label) Parameters label Text that appears on Menu. Description Constructs a Menu object with the given label. public Menu (String label, boolean tearOff) Parameters label
http://localhost/java/javaref/awt/ch19_40.htm (2 of 7) [20/12/2001 11:12:06]
[Chapter 19] Menu
Text that appears on Menu. tearOff true to create a tear-off menu, false otherwise. Description Constructs a Menu object; this will be a tear-off menu if tearOff is set to true.
Instance Methods add public synchronized MenuItem add (MenuItem item) Parameters item A MenuItem to add to the Menu. Returns Item just added. Description Adds a new item to a Menu. public void add (String label) Parameters label Text for a MenuItem Description Constructs a new MenuItem object with the given label, and adds it to a Menu.
addNotify public void addNotify() Overrides MenuItem.addNotify() Description Creates a Menu peer, and peers for all MenuItem objects that appear on it.
http://localhost/java/javaref/awt/ch19_40.htm (3 of 7) [20/12/2001 11:12:06]
[Chapter 19] Menu
addSeparator public void addSeparator() Description Adds a separator bar to the Menu.
countItems public int countItems() Returns The number of items on the menu. Replaced by getItemCount().
getItem public MenuItem getItem (int index) Parameters index The position of the MenuItem to fetch; the first item has index 0. Returns The MenuItem at the designated position.
getItemCount public int getItemCount() Returns The number of items on the menu.
insert public void insert (String label, int index) Parameters label The label for the new item. index The position for the new item. http://localhost/java/javaref/awt/ch19_40.htm (4 of 7) [20/12/2001 11:12:06]
[Chapter 19] Menu
Description Adds a new item to this menu. public synchronized void insert (MenuItem menuitem, int index) Parameters menuitem The item to add. index The position for the new item. Throws IllegalArgumentException If index is less than zero. Description Adds a new item to this menu.
insertSeparator public void insertSeparator (int index) Parameters index The position for the separator. Throws IllegalArgumentException If index is less than zero. Description Adds a separator to this menu.
isTearOff public boolean isTearOff() Returns true if the menu is a tear-off menu, false otherwise.
http://localhost/java/javaref/awt/ch19_40.htm (5 of 7) [20/12/2001 11:12:06]
[Chapter 19] Menu
paramString public String paramString() Returns String with current settings of Menu. Overrides MenuItem.paramString() Description Helper method for toString() to generate string of current settings.
remove public synchronized void remove (int index) Parameters index The position of the MenuItem to remove. Description Removes an item from the Menu. public synchronized void remove (MenuComponent component) Parameters component The element to remove. Implements MenuContainer.remove() Description Removes an item from the Menu.
removeAll public synchronized void removeAll() Description Removes all items from the Menu.
http://localhost/java/javaref/awt/ch19_40.htm (6 of 7) [20/12/2001 11:12:06]
[Chapter 19] Menu
removeNotify public void removeNotify() Description Destroys Menu peer, and peers for all MenuItem objects that appear on it.
See Also Frame, MenuComponent, MenuContainer, MenuItem, String
MediaTracker
http://localhost/java/javaref/awt/ch19_40.htm (7 of 7) [20/12/2001 11:12:06]
MenuBar
[Chapter 19] MenuBar
Chapter 19 java.awt Reference
MenuBar Name MenuBar
Description A MenuBar holds menus. MenuBars are always attached to frames, and displayed on the top line of the Frame. One menu in a MenuBar may be designated a "help" menu.
Class Definition public class java.awt.MenuBar extends java.awt.MenuComponent implements java.awt.MenuContainer { // Constructors public MenuBar(); // Instance Methods public synchronized Menu add (Menu m); public void addNotify(); public int countMenus(); public void deleteShortcut (MenuShortcut s); public Menu getHelpMenu();
http://localhost/java/javaref/awt/ch19_41.htm (1 of 5) [20/12/2001 11:12:08]
[Chapter 19] MenuBar
public Menu getMenu (int index); public int getMenuCount(); public public public public public
MenuItem getShortcutMenuItem (MenuShortcut s); synchronized void remove (int index); synchronized void remove (MenuComponent component); void removeNotify(); synchronized void setHelpMenu (Menu m);
public synchronized Enumeration shortcuts(); }
Constructors MenuBar public MenuBar() Description Constructs a MenuBar object.
Instance Methods add public synchronized Menu add (Menu m) Parameters m A Menu to add to MenuBar. Returns Item just added. Description Adds a new menu to the MenuBar.
addNotify public void addNotify() Description Creates MenuBar's peer and peers of contained menus.
http://localhost/java/javaref/awt/ch19_41.htm (2 of 5) [20/12/2001 11:12:08]
[Chapter 19] MenuBar
countMenus public int countMenus() Returns The number of menus on the menu bar. Replaced by getMenuCount().
deleteShortcut public void deleteShortcut (MenuShortcut s) Parameters s The shortcut to remove. Description Removes a menu shortcut.
getHelpMenu public Menu getHelpMenu() Returns The menu that was designated the help menu.
getMenu public Menu getMenu (int index) Parameters index The position of the Menu to fetch. Returns The Menu at the designated position.
getMenuCount public int getMenuCount() Returns The number of menus on the menu bar. http://localhost/java/javaref/awt/ch19_41.htm (3 of 5) [20/12/2001 11:12:08]
[Chapter 19] MenuBar
getShortcutMenuItem public MenuItem getShortcutMenuItem (MenuShortcut s) Parameters s A menu shortcut. Returns The corresponding menu item. Description Finds the MenuItem corresponding to the given MenuShortcut, or null if no match is found.
remove public synchronized void remove (int index) Parameters index The position of the Menu to remove. Description Removes a Menu from the MenuBar. public synchronized void remove (MenuComponent component) Parameters component The element of the MenuBar to remove. Implements MenuContainer.remove() Description Removes a Menu from the MenuBar.
removeNotify public void removeNotify() Description
http://localhost/java/javaref/awt/ch19_41.htm (4 of 5) [20/12/2001 11:12:08]
[Chapter 19] MenuBar
Destroys the MenuBar peer, and peers for all Menu objects that appear on it.
setHelpMenu public synchronized void setHelpMenu (Menu m) Parameters m Menu to designate as the help menu. Description Designates a Menu as the MenuBar's help menu.
shortcuts public synchronized Enumeration shortcuts() Returns An Enumeration of MenuShortcut objects. Description Returns an Enumeration of all MenuShortcut objects managed by this MenuBar.
See Also Frame, Menu, MenuComponent, MenuContainer
Menu
http://localhost/java/javaref/awt/ch19_41.htm (5 of 5) [20/12/2001 11:12:08]
MenuComponent
[Chapter 19] MenuComponent
Chapter 19 java.awt Reference
MenuComponent Name MenuComponent
Description The abstract MenuComponent class represents the parent of all menu GUI components.
Class Definition public abstract class java.awt.MenuComponent extends java.lang.Object implements java.io.Serializable { // Instance Methods public final void dispatchEvent (AWTEvent e); public Font getFont(); public String getName(); public MenuContainer getParent(); public MenuComponentPeer getPeer();
http://localhost/java/javaref/awt/ch19_42.htm (1 of 5) [20/12/2001 11:12:10]
[Chapter 19] MenuComponent
public boolean postEvent (Event e); public void removeNotify(); public void setFont (Font f); public void setName (String name); public String toString(); // Protected Instance Methods protected String paramString(); protected void processEvent (AWTEvent e); }
Instance Methods dispatchEvent public final void dispatchEvent (AWTEvent e) Parameters e The AWTEvent to process. Description Tells the menu component to deal with the AWTEvent e.
getFont public Font getFont() Returns The font for the current MenuComponent.
getName public Font getName() Returns The name for the current MenuComponent.
http://localhost/java/javaref/awt/ch19_42.htm (2 of 5) [20/12/2001 11:12:10]
[Chapter 19] MenuComponent
getParent public MenuContainer getParent() Returns The parent MenuContainer for the MenuComponent.
getPeer public MenuComponentPeer getPeer() Returns A reference to the MenuComponent's peer.
postEvent public boolean postEvent (Event e) Parameters e Event instance to post to component. Returns Ignored for menus. Description Tells the Frame that contains the MenuBar containing the MenuComponent to deal with Event.
removeNotify public void removeNotify() Description Removes peer of MenuComponent's subclass.
setFont public void setFont (Font f) Parameters f
http://localhost/java/javaref/awt/ch19_42.htm (3 of 5) [20/12/2001 11:12:10]
[Chapter 19] MenuComponent
New font for MenuComponent. Description Changes the font of the label of the MenuComponent.
setName public void setName (String name) Parameters name New name for MenuComponent. Description Changes the name of the MenuComponent.
toString public String toString() Returns A string representation of the MenuComponent object. Overrides Object.toString()
Protected Instance Methods paramString protected String paramString() Returns String with current settings of MenuComponent. Overrides Component.paramString() Description Helper method for toString() to generate string of current settings.
http://localhost/java/javaref/awt/ch19_42.htm (4 of 5) [20/12/2001 11:12:10]
[Chapter 19] MenuComponent
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description Low-level AWTEvents are passed to this method for processing.
See Also Event, Font, MenuBar, MenuComponentPeer, MenuContainer, MenuItem, Object, Serializable, String
MenuBar
http://localhost/java/javaref/awt/ch19_42.htm (5 of 5) [20/12/2001 11:12:10]
MenuContainer
[Chapter 19] MenuContainer
Chapter 19 java.awt Reference
MenuContainer Name MenuContainer
Description MenuContainer is an interface that defines the responsibilities for objects that can have a menu.
Interface Definition public abstract interface java.awt.MenuContainer extends java.lang.Object { // Interface Methods public abstract Font getFont(); public abstract boolean postEvent (Event e); public abstract void remove (MenuComponent component); }
http://localhost/java/javaref/awt/ch19_43.htm (1 of 2) [20/12/2001 11:12:11]
[Chapter 19] MenuContainer
Interface Methods getFont public abstract Font getFont() Returns Current font of the object implementing this method.
postEvent public abstract boolean postEvent (Event e) Parameters e Event to post. Returns Ignores return value. Description Posts event to the object implementing this method.
remove public abstract void remove (MenuComponent component) Parameters component Menu object to remove Description Tells the object implementing this method to remove a menu component.
See Also Event, Font, Frame, Menu, MenuBar, MenuComponent, Object
MenuComponent
http://localhost/java/javaref/awt/ch19_43.htm (2 of 2) [20/12/2001 11:12:11]
MenuItem
[Chapter 19] MenuItem
Chapter 19 java.awt Reference
MenuItem Name MenuItem
Description The MenuItem class represents a selectable item on a menu.
Class Definition public class java.awt.MenuItem extends java.awt.MenuComponent { // Constructors public MenuItem(); public MenuItem (String label); public MenuItem (String label, MenuShortcut s); // Instance Methods public void addActionListener (ActionListener l);
http://localhost/java/javaref/awt/ch19_44.htm (1 of 8) [20/12/2001 11:12:14]
[Chapter 19] MenuItem
public void addNotify(); public void deleteShortcut(); public synchronized void disable(); public synchronized void enable(); public void enable (boolean condition); public String getActionCommand(); public String getLabel(); public MenuShortcut getShortcut(); public boolean isEnabled(); public String paramString(); public void removeActionListener (ActionListener l); public void setActionCommand (String command); public synchronized void setEnabled (boolean b); public synchronized void setLabel (String label); public void setShortcut (MenuShortcut s); // Protected Instance Methods protected final void disableEvents (long eventsToDisable); protected final void enableEvents (long eventsToEnable); protected void processActionEvent (ActionEvent e); protected void processEvent (AWTEvent e); }
Constructors MenuItem public MenuItem() Description Constructs a MenuItem object with no label or shortcut. public MenuItem (String label) Parameters label Text that appears on the MenuItem. Description Constructs a MenuItem object. http://localhost/java/javaref/awt/ch19_44.htm (2 of 8) [20/12/2001 11:12:14]
[Chapter 19] MenuItem
public MenuItem (String label, MenuShortcut s) Parameters label Text that appears on the MenuItem. s Shortcut for the MenuItem. Description Constructs a MenuItem object with the given shortcut.
Instance Methods addActionListener public void addActionListener(ActionListener l) Parameters l An object that implements the ActionListener interface. Description Add a listener for the action event.
addNotify public void addNotify() Description Creates the MenuItem's peer.
deleteShortcut public void deleteShortcut() Description Removes the shortcut associated with this item.
http://localhost/java/javaref/awt/ch19_44.htm (3 of 8) [20/12/2001 11:12:14]
[Chapter 19] MenuItem
disable public synchronized void disable() Description Disables the menu component so that it is unresponsive to user interactions. Replaced by setEnabled(false).
enable public synchronized void enable() Description Enables the menu component so that it is responsive to user interactions. Replaced by setEnabled(true). public void enable (boolean condition) Parameters condition true to enable the menu component; false to disable it. Description Enables or disables the menu component, depending on the condition parameter. Replaced by setEnabled(boolean).
getActionCommand public String getActionCommand() Returns Current action command string. Description Returns the string used for the action command.
getLabel public String getLabel() Returns The current text associated with the MenuItem. http://localhost/java/javaref/awt/ch19_44.htm (4 of 8) [20/12/2001 11:12:14]
[Chapter 19] MenuItem
getShortcut public MenuShortcut getShortcut() Returns The current shortcut for this item, or null if there is none.
isEnabled public boolean isEnabled() Returns true if the menu item is enabled, false otherwise.
paramString public String paramString() Returns String with current settings of MenuItem. Description Helper method for toString() to generate string of current settings.
removeActionListener public void removeActionListener(ActionListener l) Parameters l One of this Button's ActionListeners. Description Remove an action event listener.
setActionCommand public void setActionCommand(String command) Parameters command
http://localhost/java/javaref/awt/ch19_44.htm (5 of 8) [20/12/2001 11:12:14]
[Chapter 19] MenuItem
New action command string. Description Specify the string used for the action command.
setEnabled public synchronized void setEnabled (boolean b) Parameters b true to enable the item, false to disable it. Description Enables or disables the item. Replaces enable(), enable(boolean), and disable().
setLabel public synchronized void setLabel (String label) Parameters label New text to appear on MenuItem. Description Changes the label of the MenuItem.
setShortcut public void setShortcut (MenuShortcut s) Parameters s New shortcut for the MenuItem. Description Changes the shortcut of the MenuItem.
Protected Instance Methods
http://localhost/java/javaref/awt/ch19_44.htm (6 of 8) [20/12/2001 11:12:14]
[Chapter 19] MenuItem
disableEvents protected final void disableEvents (long eventsToDisable) Parameters eventsToDisable A value representing certain kinds of events. This can be constructed by ORing the event mask constants defined in java.awt.AWTEvent. Description By default, a menu item receives events corresponding to the event listeners that have registered. If a menu item should not receive events of a certain type, even if there is a listener registered for that type of event, this method can be used to disable that event type.
enableEvents protected final void enableEvents (long eventsToEnable) Parameters eventsToDisable A value representing certain kinds of events. This can be constructed by ORing the event mask constants defined in java.awt.AWTEvent. Description By default, a menu item receives events corresponding to the event listeners that have registered. If a menu item should receive other types of events as well, this method can be used to get them.
processActionEvent protected void processActionEvent (ActionEvent e) Parameters e The action event to process. Description Action events are passed to this method for processing. Normally, this method is called by processEvent().
http://localhost/java/javaref/awt/ch19_44.htm (7 of 8) [20/12/2001 11:12:14]
[Chapter 19] MenuItem
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description Low-level AWTEvents are passed to this method for processing.
See Also CheckboxMenuItem, Menu, MenuComponent, MenuShortcut, String
MenuContainer
http://localhost/java/javaref/awt/ch19_44.htm (8 of 8) [20/12/2001 11:12:14]
MenuShortcut
[Chapter 19] MenuShortcut
Chapter 19 java.awt Reference
MenuShortcut Name MenuShortcut
Description A MenuShortcut is used to associate a keystroke with a menu item. MenuShortcuts are constructed using their corresponding key; they are associated with menu items via MenuItem.setShortcut(MenuShortcut).
Class Definition public class java.awt.MenuShortcut extends java.awt.Event { // Constructors public MenuShortcut (int key); public MenuShortcut (int key, boolean useShiftModifier); // Instance Methods public boolean equals (MenuShortcut s); public int getKey(); public String toString(); public boolean usesShiftModifier(); // Protected Instance Methods protected String paramString(); } http://localhost/java/javaref/awt/ch19_45.htm (1 of 4) [20/12/2001 11:12:16]
[Chapter 19] MenuShortcut
Constructors MenuShortcut public MenuShortcut (int key) Parameters key A keycode like those returned with key press Event objects. Description Constructs a MenuShortcut object for the given key. public MenuShortcut (int key, boolean useShiftModifier) Parameters key A keycode like those returned with key press Event objects. useShiftModifier true if the Shift key must be used, false otherwise. Description Constructs a MenuShortcut object with the given values.
Instance Methods equals public boolean equals (MenuShortcut s) Parameters s The MenuShortcut to compare. Returns true if s is equal to this MenuShortcut, false otherwise.
http://localhost/java/javaref/awt/ch19_45.htm (2 of 4) [20/12/2001 11:12:16]
[Chapter 19] MenuShortcut
getKey public int getKey() Returns The key for this MenuShortcut.
toString public String toString() Returns A string representation of the MenuShortcut object. Overrides Event.toString()
usesShiftModifier public boolean usesShiftModifier() Returns true if this MenuShortcut must be invoked with the Shift key pressed, false otherwise.
Protected Instance Methods paramString protected String paramString() Returns String with current settings of MenuShortcut. Overrides Event.paramString() Description Helper method for toString() to generate string of current settings.
http://localhost/java/javaref/awt/ch19_45.htm (3 of 4) [20/12/2001 11:12:16]
[Chapter 19] MenuShortcut
See Also Event, MenuItem
MenuItem
http://localhost/java/javaref/awt/ch19_45.htm (4 of 4) [20/12/2001 11:12:16]
Panel
[Chapter 19] Panel
Chapter 19 java.awt Reference
Panel Name Panel
Description The Panel class provides a generic Container within an existing display area.
Class Definition public class java.awt.Panel extends java.awt.Container { // Constructors public Panel(); public Panel(LayoutManager layout); // Instance Methods public void addNotify(); }
http://localhost/java/javaref/awt/ch19_46.htm (1 of 2) [20/12/2001 11:12:17]
[Chapter 19] Panel
Constructors Panel public Panel() Description Constructs a Panel object. public Panel (LayoutManager layout) Description Constructs a Panel object with the specified layout manager.
Instance Methods addNotify public void addNotify() Overrides Container.addNotify() Description Creates Panel's peer and peers of contained components.
See Also Applet, Container
MenuShortcut
http://localhost/java/javaref/awt/ch19_46.htm (2 of 2) [20/12/2001 11:12:17]
Point
[Chapter 19] Point
Chapter 19 java.awt Reference
Point Name Point
Description The Point class encapsulates a pair of x and y coordinates within a single object.
Class Definition public class java.awt.Point extends java.lang.Object implements java.io.Serializable { // Variables public int x; public int y; // Constructors public Point(); public Point (int width, int height); public Point (Point p); // Instance Methods public boolean equals (Object object);
http://localhost/java/javaref/awt/ch19_47.htm (1 of 5) [20/12/2001 11:12:19]
[Chapter 19] Point
public Point getLocation(); public int hashCode(); public void move (int x, int y); public void setLocation (int x, int y); public void setLocation (Point p); public String toString(); public void translate (int deltax, int deltay); }
Variables x public int x The coordinate that represents the horizontal position.
y public int y The coordinate that represents the vertical position.
Constructors Point public Point() Description Constructs a Point object initialized to (0, 0). public Point (int x, int y) Parameters x Coordinate that represents the horizontal position. y Coordinate that represents the vertical position. Description
http://localhost/java/javaref/awt/ch19_47.htm (2 of 5) [20/12/2001 11:12:19]
[Chapter 19] Point
Constructs a Point object with an initial position of (x, y). public Point (Point p) Parameters p Initial position. Description Constructs a Point object with the same position as p.
Instance Methods equals public boolean equals (Object object) Parameters object The object to compare. Returns true if both points have the same x and y coordinates, false otherwise. Overrides Object.equals() Description Compares two different Point instances for equivalence.
getLocation public Point getLocation() Returns Position of this point. Description Gets the current position of this Point.
http://localhost/java/javaref/awt/ch19_47.htm (3 of 5) [20/12/2001 11:12:19]
[Chapter 19] Point
hashCode public int hashCode() Returns A hashcode to use the Point is used as a key in a Hashtable. Overrides Object.hashCode() Description Generates a hashcode for the Point.
move public void move (int x, int y) Parameters x The new x coordinate. y The new y coordinate. Description Changes the Point's location to (x, y).
setLocation public void setLocation (int x, int y) Parameters x The new x coordinate. y The new y coordinate. Description Changes the Point's location to (x, y). public void setLocation (Point p) Parameters http://localhost/java/javaref/awt/ch19_47.htm (4 of 5) [20/12/2001 11:12:19]
[Chapter 19] Point
p The new location. Description Changes the Point's location to p.
toString public String toString() Returns A string representation of the Point object. Overrides Object.toString()
translate public void translate (int deltax, int deltay) Parameters deltax Amount to move horizontally. deltay Amount to move vertically. Description Moves the Point to the location (x+deltax, y+deltay).
See Also Object, String
Panel
http://localhost/java/javaref/awt/ch19_47.htm (5 of 5) [20/12/2001 11:12:19]
Polygon
[Chapter 19] Polygon
Chapter 19 java.awt Reference
Polygon Name Polygon
Description The Polygon class encapsulates a collection of points used to create a series of line segments.
Class Definition public class java.awt.Polygon extends java.lang.Object implements java.awt.Shape, java.io.Serializable { // Variables protected Rectangle bounds; public int npoints; public int xpoints[]; public int ypoints[]; // Constructors public Polygon(); public Polygon (int xpoints[], int ypoints, int npoints);
http://localhost/java/javaref/awt/ch19_48.htm (1 of 6) [20/12/2001 11:12:22]
[Chapter 19] Polygon
// Instance Methods public void addPoint (int x, int y); public boolean contains (int x, int y); public boolean contains (Point p); public Rectangle getBoundingBox(); public Rectangle getBounds(); public boolean inside (int x,int y); public void translate (int deltaX, int deltaY); }
Variables bounds protected Rectangle bounds The rectangle that describes the boundaries of the Polygon.
npoints public int npoints The number of elements to use in the xpoints and ypoints arrays.
xpoints public int xpoints[] The array of x coordinates for each point.
ypoints public int ypoints[] The array of y coordinates for each point.
Constructors
http://localhost/java/javaref/awt/ch19_48.htm (2 of 6) [20/12/2001 11:12:22]
[Chapter 19] Polygon
Polygon public Polygon() Description Constructs an empty Polygon object with no points. public Polygon (int xPoints[], int yPoints[], int numPoints) Parameters xPoints[] The initial array of x coordinates for each point. yPoints[] The initial array of y coordinates for each point. numPoints The number of elements in both xPoints and yPoints arrays to use. Throws ArrayIndexOutOfBoundsException If numPoints > xPoints.length or numPoints > yPoints.length. Description Constructs a Polygon object with the set of points provided.
Instance Methods addPoint public void addPoint (int x, int y) Parameters x The x coordinate of the point to be added. y The y coordinate of the point to be added. Description Adds the point (x, y) to the end of the list of points for the Polygon.
http://localhost/java/javaref/awt/ch19_48.htm (3 of 6) [20/12/2001 11:12:22]
[Chapter 19] Polygon
contains public boolean contains (int x, int y) Parameters x The x coordinate to test. y The y coordinate to test. Returns true if the Polygon contains the point; false otherwise. public boolean contains (Point p) Parameters p The point to be tested. Returns true if the Polygon contains the point; false otherwise.
getBoundingBox public Rectangle getBoundingBox() Returns Bounding Rectangle of the points within the Polygon. Description Returns the smallest Rectangle that contains all the points within the Polygon. Replaced by getBounds().
getBounds public Rectangle getBounds() Implements Shape.getBounds() Returns
http://localhost/java/javaref/awt/ch19_48.htm (4 of 6) [20/12/2001 11:12:22]
[Chapter 19] Polygon
Bounding Rectangle of the points within the Polygon. Description Returns the smallest Rectangle that contains all the points within the Polygon.
inside public boolean inside (int x,int y) Parameters x The x coordinate of the point to be checked. y The y coordinate of the point to be checked. Returns true if (x, y) within Polygon, false otherwise. Description Checks to see if the (x, y) point is within an area that would be filled if the Polygon was drawn with Graphics.fillPolygon(). Replaced by contains(int, int).
translate public void translate (int deltaX, int deltaY) Parameters deltaX Amount to move horizontally. deltaY Amount to move vertically. Description Moves the Polygon to the location (x+deltaX, y+deltaY).
See Also Graphics, Object, Rectangle
http://localhost/java/javaref/awt/ch19_48.htm (5 of 6) [20/12/2001 11:12:22]
[Chapter 19] Polygon
Point
http://localhost/java/javaref/awt/ch19_48.htm (6 of 6) [20/12/2001 11:12:22]
PopupMenu
[Chapter 19] PopupMenu
Chapter 19 java.awt Reference
PopupMenu Name PopupMenu
Description A PopupMenu is a menu that can be popped up on a Component.
Class Definition public class java.awt.PopupMenu extends java.awt.Menu { // Constructors public PopupMenu(); public PopupMenu (String label); // Instance Methods public synchronized void addNotify(); public void show (Component origin, int x, int y); }
http://localhost/java/javaref/awt/ch19_49.htm (1 of 3) [20/12/2001 11:12:23]
[Chapter 19] PopupMenu
Constructors PopupMenu public PopupMenu() Description Constructs a PopupMenu object. public PopupMenu (String label) Parameters label Text that appears on Menu. Description Constructs a PopupMenu object with the given label.
Instance Methods addNotify public synchronized void addNotify() Overrides Menu.addNotify() Description Creates a PopupMenu peer.
show public void show (Component origin, int x, int y) Parameters origin The Component upon which the PopupMenu will be displayed. x The PopupMenu's horizontal position on the component. y
http://localhost/java/javaref/awt/ch19_49.htm (2 of 3) [20/12/2001 11:12:23]
[Chapter 19] PopupMenu
The PopupMenu's vertical position on the component. Description Shows the menu on the given Component. The origin specified must be contained in the hierarchy of the PopupMenu's parent component, which is determined by the call to Component.add(PopupMenu).
Polygon
http://localhost/java/javaref/awt/ch19_49.htm (3 of 3) [20/12/2001 11:12:23]
PrintGraphics
[Chapter 19] PrintGraphics
Chapter 19 java.awt Reference
PrintGraphics Name PrintGraphics
Description PrintGraphics is an interface for classes that provide a printing graphics context.
Interface Definition public abstract interface java.awt.PrintGraphics { // Interface Methods public abstract PrintJob getPrintJob(); }
Interface Methods getPrintJob public abstract PrintJob getPrintJob() Returns
http://localhost/java/javaref/awt/ch19_50.htm (1 of 2) [20/12/2001 11:12:26]
[Chapter 19] PrintGraphics
The PrintJob from which the PrintGraphics object originated.
See Also PrintJob
PopupMenu
http://localhost/java/javaref/awt/ch19_50.htm (2 of 2) [20/12/2001 11:12:26]
PrintJob
[Chapter 19] PrintJob
Chapter 19 java.awt Reference
PrintJob Name PrintJob
Description PrintJob encapsulates printing information. When you call Toolkit.getPrintJob(), this is the object that is returned. From the PrintJob, you can access a Graphics object, which can be used for drawing to the printer.
Class Definition public abstract class jav.awt.PrintJob extends java.lang.Object { // Instance Methods public abstract void end(); public void finalize(); public abstract Graphics getGraphics(); public abstract Dimension getPageDimension(); public abstract int getPageResolution(); public abstract boolean lastPageFirst(); }
http://localhost/java/javaref/awt/ch19_51.htm (1 of 3) [20/12/2001 11:12:29]
[Chapter 19] PrintJob
Instance Methods end public abstract void end() Description Ends printing and cleans up.
finalize public void finalize() Overrides Object.finalize() Description Cleans up when this object is garbage collected.
getGraphics public abstract Graphics getGraphics() Returns A Graphics object representing the next page. The object returned will also implement the PrintGraphics interface. Description Returns a Graphics object for printing.
getPageDimension public abstract Dimension getPageDimension() Returns The page dimensions in pixels.
getPageResolution public abstract int getPageResolution Returns
http://localhost/java/javaref/awt/ch19_51.htm (2 of 3) [20/12/2001 11:12:29]
[Chapter 19] PrintJob
The page resolution, in pixels per inch.
lastPageFirst public abstract boolean lastPageFirst() Returns true if pages are printed in reverse order; false otherwise.
See Also Dimension, Graphics, PrintGraphics, Toolkit
PrintGraphics
http://localhost/java/javaref/awt/ch19_51.htm (3 of 3) [20/12/2001 11:12:29]
Rectangle
[Chapter 19] Rectangle
Chapter 19 java.awt Reference
Rectangle Name Rectangle
Description The Rectangle class represents a rectangle by combining its origin (a pair of x and y coordinates) with its size (a width and a height).
Class Definition public class java.awt.Rectangle extends java.lang.Object implements java.awt.Shape, java.io.Serializable { // Variables pubic int height; public int width; public int x; public int y; // Constructors public Rectangle();
http://localhost/java/javaref/awt/ch19_52.htm (1 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
public public public public public
Rectangle Rectangle Rectangle Rectangle Rectangle
(int width, int height); (int x, int y, int width, int height); (Dimension d); (Point p); (Point p, Dimension d);
public Rectangle (Rectangle r); // Instance public void public void public void
Methods add (int newX, int newY); add (Point p); add (Rectangle r);
public boolean contains (int x, int y); public boolean contains (Point p); public boolean equals (Object object); public Rectangle getBounds(); public Point getLocation(); public Dimension getSize(); public void grow (int horizontal, int vertical); public int hashCode(); public public public public
boolean inside (int x, int y); Rectangle intersection (Rectangle r); boolean intersects (Rectangle r); boolean isEmpty();
public void move (int x, int y); public void reshape (int x, int y, int width, int height); public void resize (int width, int height); public void setBounds (Rectangle r); public void setBounds (int x, int y, int width, int height); public void setLocation (int x, int y); public void setLocation (Point p); public void setSize (int width, int height); public public public public
void setSize (Dimension d); String toString(); void translate (int x, int y); Rectangle union (Rectangle r);
}
http://localhost/java/javaref/awt/ch19_52.htm (2 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
Variables height public int height The height of the Rectangle.
width public int width The width of the Rectangle.
x public int x The x coordinate of the Rectangle's upper left corner (its origin).
y public int y The y coordinate of the Rectangle's upper left corner (its origin).
Constructors Rectangle public Rectangle() Description Constructs an empty Rectangle object with an origin of (0, 0) and dimensions of 0 x 0. public Rectangle (int width, int height) Parameters width width of Rectangle height height of Rectangle
http://localhost/java/javaref/awt/ch19_52.htm (3 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
Description Constructs a Rectangle object with an origin of (0, 0) and dimensions of width x height. public Rectangle (int x, int y, int width, int height) Parameters x x coordinate of the Rectangle's origin y y coordinate of the Rectangle's origin width width of Rectangle height height of Rectangle Description Constructs a Rectangle object with an origin of (x, y) and dimensions of width x height. public Rectangle (Dimension d) Parameters d dimensions of Rectangle Description Constructs a Rectangle object with an origin of (0, 0) and dimensions of d.width x d.height. public Rectangle (Point p) Parameters p origin of Rectangle Description Constructs an empty Rectangle object with an origin of (p.x, p.y) and dimensions of 0 x 0. public Rectangle (Point p, Dimension d) Parameters p http://localhost/java/javaref/awt/ch19_52.htm (4 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
origin of Rectangle d dimensions of Rectangle Description Constructs a Rectangle object with an origin of (p.x, p.y) and dimensions of d.width x d.height. public Rectangle (Rectangle r) Parameters r original Rectangle Description Constructs copy of the given Rectangle.
Instance Methods add public void add (int newX, int newY) Parameters newX The x-coordinate of a point to incorporate within the Rectangle. newY The y-coordinate of a point to incorporate within the Rectangle. Description Extends the Rectangle so that the point (newX, newY) is within it. public void add (Point p) Parameters p The new Point to add to the Rectangle. Description Extends the Rectangle so that the point p is within it.
http://localhost/java/javaref/awt/ch19_52.htm (5 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
public void add (Rectangle r) Parameters r The Rectangle being added to the current Rectangle. Description Extends the Rectangle to include the Rectangle r.
contains public boolean contains (int x, int y) Parameters x The x coordinate to test. y The y coordinate to test. Returns true if the Rectangle contains the point; false otherwise. public boolean contains (Point p) Parameters p The point to be tested. Returns true if the Rectangle contains the point; false otherwise.
equals public boolean equals (Object object) Parameters object The object to compare. Returns true if both Rectangles have the same origin, width, and height; false otherwise.
http://localhost/java/javaref/awt/ch19_52.htm (6 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
Overrides Object.equals(Object) Description Compares two different Rectangle instances for equivalence.
getBounds public Rectangle getBounds() Implements Shape.getBounds() Returns Bounding Rectangle.
getLocation public Point getLocation() Returns Position of the rectangle. Description Gets the current position of this Rectangle.
getSize public Dimension getSize() Returns Dimensions of the rectangle. Description Gets width and height of the rectangle.
grow public void grow (int horizontal, int vertical) Parameters horizontal
http://localhost/java/javaref/awt/ch19_52.htm (7 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
Amount to extend Rectangle in horizontal direction on both the left and right sides. vertical Amount to extend Rectangle in vertical direction on both the top and the bottom. Description Increases the rectangle's dimensions.
hashCode public int hashCode() Returns A hashcode to use when using the Rectangle as a key in a Hashtable. Overrides Object.hashCode() Description Generates a hashcode for the Rectangle.
inside public boolean inside (int x, int y) Parameters x The x coordinate to check. y The y coordinate to check. Returns true if (x, y) falls within the Rectangle, false otherwise. Description Checks to see if the point (x, y) is within the Rectangle. Replaced by contains(int, int).
intersection public Rectangle intersection (Rectangle r) Parameters r http://localhost/java/javaref/awt/ch19_52.htm (8 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
Rectangle to add to the current Rectangle. Returns A new Rectangle consisting of all points in both the current Rectangle and r. Description Generates a new Rectangle that is the intersection of r and the current Rectangle.
intersects public boolean intersects (Rectangle r) Parameters r Rectangle to check. Returns true if any points in r are also in the current Rectangle, false otherwise. Description Checks to see if r crosses the Rectangle.
isEmpty public boolean isEmpty() Returns true if the Rectangle is empty, false otherwise. Description Determines if the rectangle is dimensionless (i.e., width or height are less than or equal to 0).
move public void move (int x, int y) Parameters x The new x coordinate of the Rectangle's upper left corner. y The new y coordinate of the Rectangle's upper left corner. Description http://localhost/java/javaref/awt/ch19_52.htm (9 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
Changes the Rectangle's origin to (x, y). Replaced by setLocation(int, int).
reshape public void reshape (int x, int y, int width, int height) Parameters x The new x coordinate of the Rectangle's upper left corner. y The new y coordinate of the Rectangle's upper left corner. width The new width. height The new height. Description Changes Rectangle's origin and dimensions. Replaced by setBounds(int, int, int, int).
resize public void resize (int width, int height) Parameters width The new width. height The new height. Description Changes Rectangle's dimensions. Replaced by setSize(int, int).
setBounds public void setBounds (Rectangle r) Parameters r
http://localhost/java/javaref/awt/ch19_52.htm (10 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
A Rectangle describing the new bounds. Description Changes Rectangle's location and size. public void setBounds (int x, int y, int width, int height) [New in 1.1] Parameters x The new x coordinate of the Rectangle's upper left corner. y The new y coordinate of the Rectangle's upper left corner. width The new width. height The new height. Description Changes Rectangle's location and size.
setLocation public void setLocation (int x, int y) Parameters x New horizontal position. y New vertical position. Description Relocates the rectangle. public void setLocation (Point p) Parameters p New position for component. Description
http://localhost/java/javaref/awt/ch19_52.htm (11 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
Relocates the rectangle.
setSize public void setSize (int width, int height) Parameters width New width. height New height. Description Resizes the rectangle. public void setSize (Dimension d) Parameters d New dimensions. Description Resizes the rectangle.
toString public String toString() Returns A string representation of the Rectangle object. Overrides Object.toString()
translate public void translate (int deltax, int deltay) Parameters deltax Amount to move Rectangle horizontally.
http://localhost/java/javaref/awt/ch19_52.htm (12 of 13) [20/12/2001 11:12:34]
[Chapter 19] Rectangle
deltay Amount to move Rectangle vertically. Description Moves the Rectangle's origin to (x+deltax, y+deltay).
union public Rectangle union (Rectangle r) Parameters r Rectangle to determine union with. Returns The smallest Rectangle containing both r and the current Rectangle. Description Generates a new Rectangle by combining r and the current Rectangle.
See Also Dimension, Object, Point, String
PrintJob
http://localhost/java/javaref/awt/ch19_52.htm (13 of 13) [20/12/2001 11:12:34]
ScrollPane
[Chapter 19] ScrollPane
Chapter 19 java.awt Reference
ScrollPane Name ScrollPane
Description The ScrollPane class provides automatic scrolling of a child component.
Class Definition public class java.awt.ScrollPane extends java.awt.Container { // Constants public final static int SCROLLBARS_ALWAYS; public final static int SCROLLBARS_AS_NEEDED; public final static int SCROLLBARS_NEVER; // Constructors public ScrollPane(); public ScrollPane (int scrollbarDisplayPolicy); // Public Instance Methods public void addNotify(); public void doLayout(); public Adjustable getHAdjustable(); public int getHScrollbarHeight(); public Point getScrollPosition(); http://localhost/java/javaref/awt/ch19_53.htm (1 of 7) [20/12/2001 11:12:37]
[Chapter 19] ScrollPane
public public public public
int getScrollbarDisplayPolicy(); Adjustable getVAdjustable(); int getVScrollbarWidth(); Dimension getViewportSize();
public public public public public public
void layout(); String paramString(); void printComponents (Graphics g); final void setLayout (LayoutManager mgr); void setScrollPosition (int x, int y); void setScrollPosition (Point p);
//Protected Instance Methods protected final void addImpl (Component comp, Object constraints, int index); }
Constants SCROLLBARS_ALWAYS public final static int SCROLLBARS_ALWAYS Always show the scrollbars.
SCROLLBARS_AS_NEEDED public final static int SCROLLBARS_AS_NEEDED Only show the scrollbars if the contents of the ScrollPane are larger than what is visible.
SCROLLBARS_NEVER public final static int SCROLLBARS_NEVER Don't ever show the scrollbars. The ScrollPane can still be scrolled programmatically.
Constructors ScrollPane public ScrollPane() Description Constructs a ScrollPane object with SCROLLBARS_AS_NEEDED. http://localhost/java/javaref/awt/ch19_53.htm (2 of 7) [20/12/2001 11:12:37]
[Chapter 19] ScrollPane
public ScrollPane (int scrollbarDisplayPolicy) Parameters scrollbarDisplayPolicy One of the SCROLLBARS_ constants. Description Constructs a ScrollPane object with the specified scrollbar display policy.
Instance Methods addImpl protected final void addImpl (Component comp, Object constraints, int index) Parameters comp The component to add to the Scrollpane. constraints Layout constraints; ignored. index The position at which to add the component; should always be less than or equal to 0. Returns The component that was added. Overrides Container.addImpl (Component, Object, int) Throws IllegalArgumentException If pos is greater than 0. Description Adds a child component to the Scrollpane. If there already was a child component, it is replaced by the new component.
http://localhost/java/javaref/awt/ch19_53.htm (3 of 7) [20/12/2001 11:12:37]
[Chapter 19] ScrollPane
addNotify public void addNotify() Overrides Container.addNotify() Description Creates ScrollPane's peer.
doLayout public void doLayout() Overrides Container.doLayout() Description Lays out the ScrollPane. Resizes the child component to its preferred size.
getHAdjustable public Adjustable getHAdjustable() Returns The object implementing the Adjustable interface that is used to adjust the ScrollPane horizontally. Usually this is a Scrollbar.
getHScrollbarHeight public int getHScrollbarHeight() Returns The height a horizontal scrollbar would occupy, regardless of whether it's shown or not.
getScrollPosition public Point getScrollPosition() Returns Returns the position within the child component that is displayed at 0, 0 in the ScrollPane.
http://localhost/java/javaref/awt/ch19_53.htm (4 of 7) [20/12/2001 11:12:37]
[Chapter 19] ScrollPane
getScrollbarDisplayPolicy public int getScrollbarDisplayPolicy() Returns The display policy for the scrollbars (one of the SCROLLBARS_ constants).
getVAdjustable public Adjustable getVAdjustable() Returns The object implementing the Adjustable interface that is used to adjust the ScrollPane vertically. Usually this is a Scrollbar.
getVScrollbarWidth public int getVScrollbarWidth() Returns The width a vertical scrollbar would occupy, regardless of whether it's shown or not.
getViewportSize public Dimension getViewportSize() Returns The size of the ScrollPane's port (the area of the child component that is shown).
layout public void layout() Overrides Container.layout() Description Lays out component. Replaced by doLayout().
http://localhost/java/javaref/awt/ch19_53.htm (5 of 7) [20/12/2001 11:12:37]
[Chapter 19] ScrollPane
paramString public String paramString() Returns String with current settings of ScrollPane. Overrides Container.paramString() Description Helper method for toString() to generate string of current settings.
printComponents public void printComponents (Graphics g) Parameters g Graphics context. Overrides Container.printComponents(Graphics) Description Prints the ScrollPane's child component.
setLayout public void setLayout (LayoutManager manager) Parameters manager Ignored. Overrides Container.setLayout(LayoutManager) Description Does nothing. No layout manager is needed because there is only one child component.
http://localhost/java/javaref/awt/ch19_53.htm (6 of 7) [20/12/2001 11:12:37]
[Chapter 19] ScrollPane
setScrollPosition public void setScrollPosition (int x, int y) Parameters x New horizontal position. y New vertical position. Throws IllegalArgumentException If the point given is not valid. Description Scroll to the given position in the child component. public void setScrollPosition (Point p) Parameters p New position. Throws IllegalArgumentException If the point given is not valid. Description Scroll to the given position in the child component.
See Also Adjustable, Container, Point, Scrollbar
Rectangle
http://localhost/java/javaref/awt/ch19_53.htm (7 of 7) [20/12/2001 11:12:37]
Scrollbar
[Chapter 19] Scrollbar
Chapter 19 java.awt Reference
Scrollbar Name Scrollbar
Description The Scrollbar is a Component that provides the means to get and set values within a predetermined range. For example, a scrollbar could be used for a volume control. Scrollbars are most frequently used to help users manipulate areas too large to be displayed on the screen (pre version 1.1) or to set a value within an integer range.
Class Definition public class java.awt.Scrollbar extends java.awt.Component implements java.awt.Adjustable { // Constants public final static int HORIZONTAL; public final static int VERTICAL; // Constructors public Scrollbar(); public Scrollbar (int orientation); public Scrollbar (int orientation, int value, int visible, int minimum, int maximum);
http://localhost/java/javaref/awt/ch19_54.htm (1 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
// Instance Methods public void addAdjustmentListener (AdjustmentListener l); public void addNotify(); public int getBlockIncrement(); public public public public
int int int int
getLineIncrement(); getMaximum(); getMinimum(); getOrientation();
public int getPageIncrement(); public int getUnitIncrement(); public int getValue(); public int getVisible(); public int getVisibleAmount(); public void removeAdjustmentListener (AdjustmentListener l); public synchronized void setBlockIncrement (int v); public void setLineIncrement (int amount); public synchronized void setMaximum (int newMaximum); public synchronized void setMinimum (int newMinimum); public synchronized void setOrientation (int orientation); public void setPageIncrement (int amount); public synchronized void setUnitIncrement(int v); public synchronized void setValue (int value); public synchronized void setValues (int value, int visible, int minimum, int maximum); public synchronized void setVisibleAmount (int newAmount); // Protected Instance Methods protected String paramString(); protected void processAdjustmentEvent (AdjustmentEvent e); protected void processEvent (AWTEvent e); }
Constants HORIZONTAL public final static int HORIZONTAL Constant used for a Scrollbar with a horizontal orientation.
http://localhost/java/javaref/awt/ch19_54.htm (2 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
VERTICAL public final static int VERTICAL Constant used for a Scrollbar with a vertical orientation.
Constructors Scrollbar public Scrollbar() Description Constructs a vertical Scrollbar object; slider size, minimum value, maximum value, and initial value are all zero. public Scrollbar (int orientation) Parameters orientation Scrollbar constant designating direction. Throws IllegalArgumentException If orientation is invalid. Description Constructs a Scrollbar object, in the designated direction; slider size, minimum value, maximum value, and initial value are all zero. public Scrollbar (int orientation, int value, int visible, int minimum, int maximum) Parameters orientation Scrollbar constant designating direction. value Initial value of Scrollbar. visible Initial slider size. minimum Initial minimum value. maximum
http://localhost/java/javaref/awt/ch19_54.htm (3 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
Initial maximum value. Throws IllegalArgumentException If orientation is invalid. Description Constructs a Scrollbar object with the given values.
Instance Methods addAdjustmentListener public void addAdjustmentListener (AdjustmentListener l) Parameters l An object that implements the AdjustmentListener interface. Implements Adjustable.addAdjustmentListener() Description Add a listener for adjustment event.
addNotify public void addNotify() Overrides Component.addNotify() Description Creates Scrollbar's peer.
getBlockIncrement public int getBlockIncrement() Implements Adjustable.getBlockIncrement() Returns The amount to scroll when a paging area is selected.
http://localhost/java/javaref/awt/ch19_54.htm (4 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
getLineIncrement public int getLineIncrement() Returns The amount to scroll when one of the arrows at the ends of the scrollbar is selected. Replaced by getUnitIncrement().
getMaximum public int getMaximum() Implements Adjustable.getMaximum() Returns The maximum value that the Scrollbar can take.
getMinimum public int getMinimum() Implements Adjustable.getMinimum() Returns The minimum value that the Scrollbar can take.
getOrientation public int getOrientation() Implements Adjustable.getOrientation() Returns A constant representing the direction of the Scrollbar.
getPageIncrement public int getPageIncrement() Returns The amount to scroll when a paging area is selected. Replaced with getBlockIncrement().
http://localhost/java/javaref/awt/ch19_54.htm (5 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
getUnitIncrement public int getUnitIncrement() Implements Adjustable.getUnitIncrement() Returns The amount to scroll when one of the arrows at the ends of the scrollbar is selected.
getValue public int getValue() Implements Adjustable.getValue() Returns The current setting for the Scrollbar.
getVisible public int getVisible() Returns The current visible setting (i.e., size) for the slider. Replaced by getVisibleAmount().
getVisibleAmount public int getVisibleAmount() Implements Adjustable.getVisibleAmount() Returns The current visible setting (i.e., size) for the slider.
removeAdjustmentListener public void removeAdjustmentListener (AdjustmentListener l) Parameters l One of this Scrollbar's AdjustmentListeners. http://localhost/java/javaref/awt/ch19_54.htm (6 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
Implements Adjustable.removeAdjustmentListener() Description Remove an adjustment event listener.
setBlockIncrement public synchronized void setBlockIncrement (int amount) Parameters amount New paging increment amount. Implements Adjustable.setBlockIncrement() Description Changes the block increment amount for the Scrollbar; the default block increment is 10.
setLineIncrement public void setLineIncrement (int amount) Parameters amount New line increment amount. Description Changes the line increment amount for the Scrollbar. The default line increment is 1. Replaced by setUnitIncrement(int).
setMaximum public synchronized void setMaximum (int newMaximum) Parameters newMaximum New maximum value. Implements Adjustable.setMaximum() Description Changes the maximum value for the Scrollbar. http://localhost/java/javaref/awt/ch19_54.htm (7 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
setMinimum public synchronized void setMinimum (int newMinimum) Parameters newMinimum New minimum value. Implements Adjustable.setMinimum() Description Changes the minimum value for the Scrollbar.
setOrientation public synchronized void setOrientation (int orientation) Parameters orientation One of the orientation constants HORIZONTAL or VERTICAL. Description Changes the orientation of the Scrollbar.
setPageIncrement public void setPageIncrement (int amount) Parameters amount New paging increment amount. Description Changes the paging increment amount for the Scrollbar; the default page increment is 10. Replaced by setBlockIncrement(int).
setUnitIncrement public synchronized void setUnitIncrement (int amount) Parameters amount
http://localhost/java/javaref/awt/ch19_54.htm (8 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
New line increment amount. Implements Adjustable.setUnitIncrement() Description Changes the unit increment amount for the Scrollbar. The default unit increment is 1.
setValue public synchronized void setValue (int value) Parameters value New Scrollbar value. Implements Adjustable.setValue() Description Changes the current value of the Scrollbar.
setValues public synchronized void setValues (int value, int visible, int minimum, int maximum) Parameters value New Scrollbar value. visible New slider width. minimum New minimum value for Scrollbar. maximum New maximum value for Scrollbar. Description Changes the settings of the Scrollbar to the given amounts.
setVisibleAmount public synchronized void setVisibleAmount (int newAmount) Parameters
http://localhost/java/javaref/awt/ch19_54.htm (9 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
newAmount New amount visible. Implements Adjustable.setVisibleAmount() Description Changes the current visible amount of the Scrollbar.
Protected Instance Methods paramString protected String paramString() Returns String with current settings of Scrollbar. Overrides Component.paramString() Description Helper method for toString() to generate string of current settings.
processAdjustmentEvent protected void processAdjustmentEvent (AdjustmentEvent e) Parameters e The adjustment event to process. Description Adjustment events are passed to this method for processing. Normally, this method is called by processEvent().
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description
http://localhost/java/javaref/awt/ch19_54.htm (10 of 11) [20/12/2001 11:12:41]
[Chapter 19] Scrollbar
Low level AWTEvents are passed to this method for processing.
See Also Adjustable, Component, String
ScrollPane
http://localhost/java/javaref/awt/ch19_54.htm (11 of 11) [20/12/2001 11:12:41]
Shape
[Chapter 19] Shape
Chapter 19 java.awt Reference
Shape Name Shape
Description Shape is an interface describing a two-dimensional geometric shape.
Interface Definition public abstract interface java.awt.Shape { // Interface Methods public abstract Rectangle getBounds(); }
Interface Methods
http://localhost/java/javaref/awt/ch19_55.htm (1 of 2) [20/12/2001 11:12:43]
[Chapter 19] Shape
getBounds public abstract Rectangle getBounds() Returns A Rectangle that completely encloses the shape.
See Also Polygon, Rectangle
Scrollbar
http://localhost/java/javaref/awt/ch19_55.htm (2 of 2) [20/12/2001 11:12:43]
SystemColor
[Chapter 19] SystemColor
Chapter 19 java.awt Reference
SystemColor Name SystemColor
Description SystemColor provides information on the colors that the windowing system uses to display windows and other graphic components. Most windowing systems allow the user to choose different color schemes; SystemColor enables programs to find out what colors are in use in order to paint themselves in a consistent manner.
Class Definition public final class java.awt.SystemColor extends java.awt.Color implements java.io.Serializable { // Constants public final static int ACTIVE_CAPTION; public final static int ACTIVE_CAPTION_BORDER; public final static int ACTIVE_CAPTION_TEXT; public final static int CONTROL; public final static int CONTROL_DK_SHADOW; public final static int CONTROL_HIGHLIGHT; public final static int CONTROL_LT_HIGHLIGHT; public final static int CONTROL_SHADOW; http://localhost/java/javaref/awt/ch19_56.htm (1 of 10) [20/12/2001 11:12:46]
[Chapter 19] SystemColor
public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public
final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final
static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static
int CONTROL_TEXT; int DESKTOP; int INACTIVE_CAPTION; int INACTIVE_CAPTION_BORDER; int INACTIVE_CAPTION_TEXT; int INFO; int INFO_TEXT; int MENU; int MENU_TEXT; int NUM_COLORS; int SCROLLBAR; int TEXT; int TEXT_HIGHLIGHT; int TEXT_HIGHLIGHT_TEXT; int TEXT_INACTIVE_TEXT; int TEXT_TEXT; int WINDOW; int WINDOW_BORDER; int WINDOW_TEXT; SystemColor activeCaption; SystemColor activeCaptionBorder; SystemColor activeCaptionText; SystemColor control; SystemColor controlDkShadow; SystemColor controlHighlight; SystemColor controlLtHighlight; SystemColor controlShadow; SystemColor controlText; SystemColor desktop; SystemColor inactiveCaption; SystemColor inactiveCaptionBorder; SystemColor inactiveCaptionText; SystemColor info; SystemColor infoText; SystemColor menu; SystemColor menuText; SystemColor scrollbar; SystemColor text; SystemColor textHighlight; SystemColor textHighlightText; SystemColor textInactiveText; SystemColor textText; SystemColor window; SystemColor windowBorder; SystemColor windowText;
http://localhost/java/javaref/awt/ch19_56.htm (2 of 10) [20/12/2001 11:12:46]
[Chapter 19] SystemColor
// Public Instance Methods public int getRGB(); public String toString(); }
Constants ACTIVE_CAPTION public static final int ACTIVE_CAPTION
ACTIVE_CAPTION_BORDER public static final int ACTIVE_CAPTION_BORDER
ACTIVE_CAPTION_TEXT public static final int ACTIVE_CAPTION_TEXT
CONTROL public static final int CONTROL
CONTROL_DK_SHADOW public static final int CONTROL_DK_SHADOW
CONTROL_HIGHLIGHT public static final int CONTROL_HIGHLIGHT
CONTROL_LT_HIGHLIGHT public static final int CONTROL_LT_HIGHLIGHT
CONTROL_SHADOW public static final int CONTROL_SHADOW
CONTROL_TEXT public static final int CONTROL_TEXT
http://localhost/java/javaref/awt/ch19_56.htm (3 of 10) [20/12/2001 11:12:46]
[Chapter 19] SystemColor
DESKTOP public static final int DESKTOP
INACTIVE_CAPTION public static final int INACTIVE_CAPTION
INACTIVE_CAPTION_BORDER public static final int INACTIVE_CAPTION_BORDER
INACTIVE_CAPTION_TEXT public static final int INACTIVE_CAPTION_TEXT
INFO public static final int INFO
INFO_TEXT public static final int INFO_TEXT
MENU public static final int MENU
MENU_TEXT public static final int MENU_TEXT
NUM_COLORS public static final int NUM_COLORS
SCROLLBAR public static final int SCROLLBAR
TEXT public static final int TEXT
http://localhost/java/javaref/awt/ch19_56.htm (4 of 10) [20/12/2001 11:12:46]
[Chapter 19] SystemColor
TEXT_HIGHLIGHT public static final int TEXT_HIGHLIGHT
TEXT_HIGHLIGHT_TEXT public static final int TEXT_HIGHLIGHT_TEXT
TEXT_INACTIVE_TEXT public static final int TEXT_INACTIVE_TEXT
TEXT_TEXT public static final int TEXT_TEXT
WINDOW public static final int WINDOW
WINDOW_BORDER public static final int WINDOW_BORDER
WINDOW_TEXT public static final int WINDOW_TEXT
activeCaption public static final SystemColor activeCaption Background color for captions in window borders.
activeCaptionBorder public static final SystemColor activeCaptionBorder Border color for captions in window borders.
activeCaptionText public static final SystemColor activeCaptionText Text color for captions in window borders.
http://localhost/java/javaref/awt/ch19_56.htm (5 of 10) [20/12/2001 11:12:46]
[Chapter 19] SystemColor
control public static final SystemColor control Background color for controls.
controlDkShadow public static final SystemColor controlDkShadow Dark shadow color for controls.
controlHighlight public static final SystemColor controlHighlight Highlight color for controls.
controlLtHighlight public static final SystemColor controlLtHighlight Light highlight color for controls.
controlShadow public static final SystemColor controlShadow Shadow color for controls.
controlText public static final SystemColor controlText Text color for controls.
desktop public static final SystemColor desktop Desktop background color.
http://localhost/java/javaref/awt/ch19_56.htm (6 of 10) [20/12/2001 11:12:46]
[Chapter 19] SystemColor
inactiveCaption public static final SystemColor inactiveCaption Background color for inactive captions in window borders.
inactiveCaptionBorder public static final SystemColor inactiveCaptionBorder Border color for inactive captions in window borders.
inactiveCaptionText public static final SystemColor inactiveCaptionText Text color for inactive captions in window borders.
info public static final SystemColor info Background color for informational text.
infoText public static final SystemColor infoText Text color for informational text.
menu public static final SystemColor menu Background color for menus.
menuText public static final SystemColor menuText Text color for menus.
http://localhost/java/javaref/awt/ch19_56.htm (7 of 10) [20/12/2001 11:12:46]
[Chapter 19] SystemColor
scrollbar public static final SystemColor scrollbar Background color for scrollbars.
text public static final SystemColor text Background color for text components.
textHighlight public static final SystemColor textHighlight Background color for highlighted text.
textHighlightText public static final SystemColor textHighlightText Text color for highlighted text.
textInactiveText public static final SystemColor textInactiveText Text color for inactive text.
textText public static final SystemColor textText Text color for text components.
window public static final SystemColor window Background color for windows.
http://localhost/java/javaref/awt/ch19_56.htm (8 of 10) [20/12/2001 11:12:46]
[Chapter 19] SystemColor
windowBorder public static final SystemColor windowBorder Border color for windows.
windowText public static final SystemColor windowText Text color for windows.
Instance Methods getRGB public int getRGB() Returns Current color as a composite value Overrides Color.getRGB() Description Gets integer value of current system color.
toString public String toString() Returns A string representation of the SystemColor object. Overrides Color.toString()
See Also Color, Serializable, String
Shape http://localhost/java/javaref/awt/ch19_56.htm (9 of 10) [20/12/2001 11:12:46]
TextArea
[Chapter 19] SystemColor
http://localhost/java/javaref/awt/ch19_56.htm (10 of 10) [20/12/2001 11:12:46]
[Chapter 19] TextArea
Chapter 19 java.awt Reference
TextArea Name TextArea
Description The TextArea class provides a multi-line Component for textual user input.
Class Definition public class java.awt.TextArea extends java.awt.TextComponent { // Constants public final static int SCROLLBARS_BOTH; public final static int SCROLLBARS_HORIZONTAL_ONLY; public final static int SCROLLBARS_NONE; public final static int SCROLLBARS_VERTICAL_ONLY; // Constructors public TextArea(); public TextArea (int rows, int columns); public TextArea (String text); public TextArea (String text, int rows, int columns); public TextArea (String text, int rows, int columns, int scrollbars); // Instance Methods public void addNotify(); public synchronized void append (String string); public void appendText (String string);
http://localhost/java/javaref/awt/ch19_57.htm (1 of 9) [20/12/2001 11:12:49]
[Chapter 19] TextArea
public int getColumns(); public Dimension getMinimumSize(); public Dimension getMinimumSize (int rows, int columns); public Dimension getPreferredSize(); public Dimension getPreferredSize (int rows, int columns); public int getRows(); public int getScrollbarVisibility(); public synchronized void insert (String string, int position); public void insertText (String string, int position); public Dimension minimumSize(); public Dimension minimumSize (int rows, int columns); public Dimension preferredSize(); public Dimension preferredSize (int rows, int columns); public synchronized void replaceRange (String str, int start, int end); public void replaceText (String string, int startPosition, int endPosition); public void setColumns (int columns); public void setRows (int rows); // Protected Instance Methods protected String paramString(); }
Constants SCROLLBARS_BOTH public final static int SCROLLBARS_BOTH Show both the horizontal and vertical scrollbars.
SCROLLBARS_HORIZONTAL_ONLY public final static int SCROLLBARS_HORIZONTAL_ONLY Show the horizontal scrollbar.
SCROLLBARS_NONE public final static int SCROLLBARS_NONE Show no scrollbars.
http://localhost/java/javaref/awt/ch19_57.htm (2 of 9) [20/12/2001 11:12:49]
[Chapter 19] TextArea
SCROLLBARS_VERTICAL_ONLY public final static int SCROLLBARS_VERTICAL_ONLY Show the vertical scrollbar.
Constructors TextArea public TextArea() Description Constructs a TextArea object with the default size and no initial content. The default size of a text area varies widely from platform to platform, so it's best to avoid this constructor. public TextArea (int rows, int columns) Parameters rows Requested number of displayed rows. columns Requested number of displayed columns. Description Constructs a TextArea object of the given size and no initial content. public TextArea (String text) Parameters text Initial text for TextArea. Description Constructs a TextArea object with the given initial content. public TextArea (String text, int rows, int columns) Parameters text Initial text for TextArea. rows Requested number of displayed rows. columns Requested number of displayed columns. Description
http://localhost/java/javaref/awt/ch19_57.htm (3 of 9) [20/12/2001 11:12:49]
[Chapter 19] TextArea
Constructs a TextArea object with the given content and size. public TextArea (String text, int rows, int columns, int scrollbars) Parameters text Initial text for TextArea. rows Requested number of displayed rows. columns Requested number of displayed columns. scrollbars Requested scrollbar visibility. Use one of the constants defined. Description Constructs a TextArea object with the given content, size, and scrollbar visibility.
Instance Methods addNotify public void addNotify() Overrides Component.addNotify() Description Creates TextArea's peer.
append public synchronized void append (String string) Parameters string Content to append to the end of the TextArea. Description Appends the given text string to the text already displayed in the TextArea.
appendText public void appendText (String string) Parameters string
http://localhost/java/javaref/awt/ch19_57.htm (4 of 9) [20/12/2001 11:12:49]
[Chapter 19] TextArea
Content to append to end of TextArea. Description Replaced by append(String).
getColumns public int getColumns() Returns The width of the TextArea in columns.
getMinimumSize public Dimension getMinimumSize() Returns The minimum dimensions of the TextArea. public Dimension getMinimumSize (int rows, int columns) Parameters rows Number of rows within TextArea to size. columns Number of columns within TextArea to size. Returns The minimum dimensions of a TextArea of the given size.
getPreferredSize public Dimension getPreferredSize() Returns The preferred dimensions of the TextArea. public Dimension getPreferredSize (int rows, int columns) Parameters rows Number of rows within TextArea to size. columns Number of columns within TextArea to size. Returns The preferred dimensions of a TextArea of the given size. http://localhost/java/javaref/awt/ch19_57.htm (5 of 9) [20/12/2001 11:12:49]
[Chapter 19] TextArea
getRows public int getRows() Returns The height of the TextArea in rows.
getScrollbarVisibility public int getScrollbarVisibility() Returns One of the SCROLLBAR_ constants indicating which scrollbars are visible.
insert public synchronized void insert (String string, int position) Parameters string Content to place within TextArea content. position Location to insert content. Description Places additional text within the TextArea at the given position.
insertText public void insertText (String string, int position) Parameters string Content to place within TextArea content. position Location to insert content. Description Places additional text within the TextArea at the given position. Replaced by insert(String, int).
minimumSize public Dimension minimumSize() Returns The minimum dimensions of the TextArea. Replaced by getMinimumSize(). http://localhost/java/javaref/awt/ch19_57.htm (6 of 9) [20/12/2001 11:12:49]
[Chapter 19] TextArea
public Dimension minimumSize (int rows, int columns) Parameters rows Number of rows within TextArea to size. columns Number of columns within TextArea to size. Returns The minimum dimensions of a TextArea of the given size. Replaced by getMinimumSize(int, int).
preferredSize public Dimension preferredSize() Returns The preferred dimensions of the TextArea. Replaced by getPreferredSize(). public Dimension preferredSize (int rows, int columns) Parameters rows Number of rows within TextArea to size. columns Number of columns within TextArea to size. Returns The preferred dimensions of a TextArea of the given size. Replaced by getPreferredSize(int, int).
replaceRange public synchronized void replaceRange (String str, int start, int end) Parameters str New content to place in TextArea. start Starting position of content to replace. end Ending position of content to replace. Description Replaces a portion of the TextArea's content with the given text.
http://localhost/java/javaref/awt/ch19_57.htm (7 of 9) [20/12/2001 11:12:49]
[Chapter 19] TextArea
replaceText public void replaceText (String string, int startPosition, int endPosition) Parameters string New content to place in TextArea. startPosition Starting position of content to replace. endPosition Ending position of content to replace. Description Replaces a portion of the TextArea's content with the given text. Replaced by replaceRange(String, int, int).
setColumns public void setColumns (int columns) Parameters columns New number of columns. Throws IllegalArgumentException If columns is less than zero. Description Changes the number of columns.
setRows public void setRows (int rows) Parameters rows New number of columns. Throws IllegalArgumentException If rows is less than zero. Description Changes the number of rows.
http://localhost/java/javaref/awt/ch19_57.htm (8 of 9) [20/12/2001 11:12:49]
[Chapter 19] TextArea
Protected Instance Methods paramString protected String paramString() Returns String with current settings of TextArea. Overrides TextComponent.paramString() Description Helper method for toString() to generate string of current settings.
See Also Dimension, TextComponent, String
SystemColor
http://localhost/java/javaref/awt/ch19_57.htm (9 of 9) [20/12/2001 11:12:49]
TextComponent
[Chapter 19] TextComponent
Chapter 19 java.awt Reference
TextComponent Name TextComponent
Description The abstract TextComponent class provides the base class for the text input components, TextArea and TextField.
Class Definition public abstract class java.awt.TextComponent extends java.awt.Component { // Instance Methods public void addTextListener (TextListener l); public public public public public public
int getCaretPosition(); synchronized String getSelectedText(); synchronized int getSelectionEnd(); synchronized int getSelectionStart(); synchronized String getText(); boolean isEditable();
http://localhost/java/javaref/awt/ch19_58.htm (1 of 6) [20/12/2001 11:12:53]
[Chapter 19] TextComponent
public void removeNotify(); public void removeTextListener (TextListener l); public synchronized void select (int selectionStart, int selectionEnd); public synchronized void selectAll(); public void setCaretPosition (int position); public synchronized void setEditable (boolean state); public synchronized void setSelectionEnd (int selectionEnd); public synchronized void setSelectionStart (int selectionStart); public synchronized void setText (String text); // Protected Instance Methods protected String paramString(); protected void processEvent (AWTEvent e); protected void processTextEvent (TextEvent e); }
Instance Methods addTextListener public void addTextListener (TextListener l) Parameters l An object that implements the TextListener interface. Description Add a listener for the text events.
getCaretPosition public int getCaretPosition() Returns The position, in characters, of the caret (text cursor).
getSelectedText public synchronized String getSelectedText() Returns The currently selected text of the TextComponent.
http://localhost/java/javaref/awt/ch19_58.htm (2 of 6) [20/12/2001 11:12:53]
[Chapter 19] TextComponent
getSelectionEnd public synchronized int getSelectionEnd() Returns The ending cursor position of any selected text.
getSelectionStart public synchronized int getSelectionStart() Returns The initial position of any selected text.
getText public synchronized String getText() Returns Current contents of the TextComponent.
isEditable public boolean isEditable() Returns true if editable, false otherwise.
removeNotify public void removeNotify() Description Destroys the peer of the TextComponent.
removeTextListener public void removeTextListener (TextListener l) Parameters l One of this TextComponent's TextListeners. Description http://localhost/java/javaref/awt/ch19_58.htm (3 of 6) [20/12/2001 11:12:53]
[Chapter 19] TextComponent
Remove a text event listener.
select public synchronized void select (int selectionStart, int selectionEnd) Parameters selectionStart Beginning position of text to select. selectionEnd Ending position of text to select. Description Selects text in the TextComponent.
selectAll public synchronized void selectAll() Description Selects all the text in the TextComponent.
setCaretPosition public void setCaretPosition (int position) Parameters position The new character position for the caret. Throws IllegalArgumentException If position is less than zero. Description Allows you to change the location of the caret.
setEditable public synchronized void setEditable (boolean state) Parameters state
http://localhost/java/javaref/awt/ch19_58.htm (4 of 6) [20/12/2001 11:12:53]
[Chapter 19] TextComponent
true to allow the user to edit the text in the TextComponent; false to prevent editing. Description Allows you to make the TextComponent editable or read-only.
setSelectionEnd public synchronized void setSelectionEnd (int selectionEnd) Parameters selectionEnd The character position of the end of the selection. Description Allows you to change the location of the end of the selected text.
setSelectionStart public synchronized void setSelectionStart (int selectionStart) Parameters selectionStart The character position of the start of the selection. Description Allows you to change the location of the start of the selected text.
setText public synchronized void setText (String text) Parameters text New text for TextComponent. Description Sets the content of the TextComponent.
Protected Instance Methods
http://localhost/java/javaref/awt/ch19_58.htm (5 of 6) [20/12/2001 11:12:53]
[Chapter 19] TextComponent
paramString protected String paramString() Returns String with current settings of TextComponent. Overrides Component.paramString() Description Helper method for toString() to generate string of current settings.
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description Low-level AWTEvents are passed to this method for processing.
processTextEvent protected void processTextEvent (TextEvent e) Parameters e The event to process. Description Text events are passed to this method for processing. Normally, this method is called by processEvent().
See Also Component, TextArea, TextField, String
TextArea
http://localhost/java/javaref/awt/ch19_58.htm (6 of 6) [20/12/2001 11:12:53]
TextField
[Chapter 19] TextField
Chapter 19 java.awt Reference
TextField Name TextField
Description The TextField class provides a single line Component for user input.
Class Definition public class java.awt.TextField extends java.awt.TextComponent { // Constructors public TextField(); public TextField (int columns); public TextField (String text); public TextField (String text, int columns); // Instance Methods public public public public public
void addActionListener (ActionListener l); void addNotify(); boolean echoCharIsSet(); int getColumns(); char getEchoChar();
http://localhost/java/javaref/awt/ch19_59.htm (1 of 8) [20/12/2001 11:12:57]
[Chapter 19] TextField
public Dimension getMinimumSize(); public Dimension getMinimumSize (int columns); public Dimension getPreferredSize(); public Dimension getPreferredSize (int columns); public Dimension minimumSize(); public Dimension minimumSize (int columns); public Dimension preferredSize(); public Dimension preferredSize (int columns); public void removeActionListener (ActionListener l); public void setColumns(int columns); public void setEchoChar(char c); public void setEchoCharacter (char c); // Protected Instance Methods protected String paramString(); protected void processActionEvent (ActionEvent e); protected void processEvent (AWTEvent e); }
Constructors TextField public TextField() Description Constructs a TextField object of the default size. public TextField (int columns) Parameters columns Requested number of displayed columns. Description Constructs a TextField object of the given size. public TextField (String text)
http://localhost/java/javaref/awt/ch19_59.htm (2 of 8) [20/12/2001 11:12:57]
[Chapter 19] TextField
Parameters text Initial text for TextField. Description Constructs a TextField object with the given content. public TextField (String text, int columns) Parameters text Initial text for TextField. columns Requested number of displayed columns. Description Constructs a TextField object with the given content and size.
Instance Methods addActionListener public void addActionListener (ActionListener l) Parameters l An object that implements the ActionListener interface. Description Add a listener for the action event.
addNotify public synchronized void addNotify() Overrides Component.addNotify() Description Creates TextField's peer.
http://localhost/java/javaref/awt/ch19_59.htm (3 of 8) [20/12/2001 11:12:57]
[Chapter 19] TextField
echoCharIsSet public boolean echoCharIsSet() Returns true if the TextField has an echo character used as a response to any input character; false otherwise. An echo character can be used to create a TextField for hidden input, like a password; the same character (e.g., "x") is used to echo all input.
getColumns public int getColumns() Returns The width of the TextField in columns.
getEchoChar public char getEchoChar() Returns The current echo character.
getMinimumSize public Dimension getMinimumSize() Returns The minimum dimensions of the TextField. public Dimension getMinimumSize (int columns) Parameters columns Number of columns within TextField to size. Returns The minimum dimensions of a TextField of the given size.
http://localhost/java/javaref/awt/ch19_59.htm (4 of 8) [20/12/2001 11:12:57]
[Chapter 19] TextField
getPreferredSize public Dimension getPreferredSize() Returns The preferred dimensions of the TextField. public Dimension getPreferredSize (int columns) Parameters columns Number of columns within TextField to size. Returns The preferred dimensions of a TextField of the given size.
minimumSize public Dimension minimumSize() Returns The minimum dimensions of the TextField. Replaced by getMinimumSize(). public Dimension minimumSize (int columns) Parameters columns Number of columns within TextField to size. Returns The minimum dimensions of a TextField of the given size. Replaced by getMinimumSize(int).
preferredSize public Dimension preferredSize() Returns The preferred dimensions of the TextField. Replaced by getPreferredSize(). public Dimension preferredSize (int columns) http://localhost/java/javaref/awt/ch19_59.htm (5 of 8) [20/12/2001 11:12:57]
[Chapter 19] TextField
Parameters columns Number of columns within TextField to size. Returns The preferred dimensions of a TextField of the given size. Replaced by getPreferredSize(int).
removeActionListener public void removeActionListener (ActionListener l) Parameters l One of this TextField's ActionListeners. Description Remove an action event listener.
setColumns public void setColumns (int columns) Parameters columns New number of columns. Throws IllegalArgumentException If columns is less than zero. Description Changes the number of columns.
setEchoChar public void setEchoChar (char c) Parameters c The character to echo for all input. To echo the characters that the user types (the default),
http://localhost/java/javaref/awt/ch19_59.htm (6 of 8) [20/12/2001 11:12:57]
[Chapter 19] TextField
set the echo character to 0 (zero). Description Changes the character that is used to echo all user input in the TextField.
setEchoCharacter public void setEchoCharacter (char c) Parameters c The character to echo for all input. To echo the characters that the user types (the default), set the echo character to 0 (zero). Description Replaced by setEchoChar(char) for consistency with getEchoChar().
Protected Instance Methods paramString protected String paramString() Returns String with current settings of TextField. Overrides TextComponent.paramString() Description Helper method for toString() to generate string of current settings.
processActionEvent protected void processActionEvent (ActionEvent e) Parameters e The action event to process. Description Action events are passed to this method for processing. Normally, this method is called by processEvent(). http://localhost/java/javaref/awt/ch19_59.htm (7 of 8) [20/12/2001 11:12:57]
[Chapter 19] TextField
processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description Low-level AWTEvents are passed to this method for processing.
See Also Dimension, TextComponent, String
TextComponent
http://localhost/java/javaref/awt/ch19_59.htm (8 of 8) [20/12/2001 11:12:57]
Toolkit
[Chapter 19] Toolkit
Chapter 19 java.awt Reference
Toolkit Name Toolkit
Description The abstract Toolkit class provides access to platform-specific details like window size and available fonts. It also deals with creating all the components' peer objects when you call addNotify().
Class Definition public abstract class java.awt.Toolkit extends java.lang.Object { // Class Methods public static synchronized Toolkit getDefaultToolkit(); protected static Container getNativeContainer (Component c); public static String getProperty (String key, String defaultValue); // Instance Methods public abstract public abstract ImageObserver public abstract
void beep(); int checkImage (Image image, int width, int height, observer); Image createImage (ImageProducer producer);
public Image createImage (byte[] imagedata); public abstract Image createImage (byte[ ] imagedata, int imageoffset, int imagelength); public abstract ColorModel getColorModel();
http://localhost/java/javaref/awt/ch19_60.htm (1 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
public public public public
abstract abstract abstract abstract
String[] getFontList(); FontMetrics getFontMetrics (Font font); Image getImage (String filename); Image getImage (URL url);
public int getMenuShortcutKeyMask(); public abstract PrintJob getPrintJob (Frame frame, String jobtitle, Properties props); public abstract int getScreenResolution(); public abstract Dimension getScreenSize(); public abstract Clipboard getSystemClipboard(); public final EventQueue getSystemEventQueue(); public abstract boolean prepareImage (Image image, int width, int height, ImageObserver observer); public abstract void sync(); // Protected Instance Methods protected abstract ButtonPeer createButton (Button b); protected abstract CanvasPeer createCanvas (Canvas c); protected abstract CheckboxPeer createCheckbox (Checkbox cb); protected abstract CheckboxMenuItemPeer createCheckboxMenuItem (CheckboxMenuItem cmi); protected abstract ChoicePeer createChoice (Choice c); protected protected protected protected protected protected protected protected protected protected
LightweightPeer createComponent(Component target); abstract DialogPeer createDialog (Dialog d); abstract FileDialogPeer createFileDialog (FileDialog fd); abstract FramePeer createFrame (Frame f); abstract LabelPeer createLabel (Label l); abstract ListPeer createList (List l); abstract MenuPeer createMenu (Menu m); abstract MenuBarPeer createMenuBar (MenuBar mb); abstract MenuItemPeer createMenuItem (MenuItem mi); abstract PanelPeer createPanel (Panel p);
protected abstract PopupMenuPeer createPopupMenu (PopupMenu target); protected protected protected protected protected
abstract abstract abstract abstract abstract
ScrollPanePeer createScrollPane (ScrollPane target); ScrollbarPeer createScrollbar (Scrollbar sb); TextAreaPeer createTextArea (TextArea ta); TextFieldPeer createTextField (TextField tf); WindowPeer createWindow (Window w);
protected abstract FontPeer getFontPeer (String name, int style); protected abstract EventQueue getSystemEventQueueImpl(); protected void loadSystemColors (int[] systemColors); }
http://localhost/java/javaref/awt/ch19_60.htm (2 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
Class Methods getDefaultToolkit public static synchronized Toolkit getDefaultToolkit() Throws AWTError If the toolkit for the current platform cannot be found. Returns The system's default Toolkit.
getNativeContainer protected static Container getNativeContainer (Component c) Returns The native container for the given component. The component's immediate parent may be a lightweight component.
getProperty public static String getProperty (String key, String defaultValue) Parameters key The name of a property. defaultValue A default value to return if the property is not found. Returns The value of the property described by key, or defaultValue if it is not found.
Instance Methods beep public abstract void beep() Description Produces an audible beep.
http://localhost/java/javaref/awt/ch19_60.htm (3 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
checkImage public abstract int checkImage (Image image, int width, int height, ImageObserver observer) Parameters image Image to check. width Width of the scaled image; -1 if image will be rendered unscaled. height Height of the scaled image; -1 if image will be rendered unscaled. observer The Component that image will be rendered on. Returns The ImageObserver flags ORed together for the data that is now available. Description Checks on the status of the construction of a screen representation of image on observer.
createImage public abstract Image createImage (ImageProducer producer) Parameters producer An ImageProducer that generates data for the desired image. Returns Newly created Image. Description Creates a new Image from an ImageProducer. public abstract Image createImage (byte[] imagedata) Parameters imagedata Raw data representing an image. Returns Newly created Image. Description Creates a new Image from the imagedata provided.
http://localhost/java/javaref/awt/ch19_60.htm (4 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
public abstract Image createImage (byte[] imagedata, int imageoffset, int imagelength) Parameters imagedata Raw data representing one or more images. imageoffset An offset into the data given. imagelength The length of data to use. Returns Newly created Image. Description Creates a new Image from the imagedata provided, starting at imageoffset bytes and reading imagelength bytes.
getColorModel public abstract ColorModel getColorModel() Returns The current ColorModel used by the system.
getFontList public abstract String[] getFontList() Returns A String array of the set of Java fonts available with this Toolkit.
getFontMetrics public abstract FontMetrics getFontMetrics (Font font) Parameters font A Font whose metrics are desired Returns The current FontMetrics for the font on the user's system.
http://localhost/java/javaref/awt/ch19_60.htm (5 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
getImage public abstract Image getImage (String filename) Parameters filename Location of Image on local filesystem Returns The Image that needs to be fetched. Description Fetches an image from the local file system. public abstract Image getImage (URL url) Parameters url Location of Image. Returns The Image that needs to be fetched. Description Fetches an image from a URL.
getMenuShortcutKeyMask public int getMenuShortcutKeyMask() Returns The modifier key mask used for menu shortcuts. This will be one of the mask constants defined in java.awt.Event.
getPrintJob public abstract PrintJob getPrintJob (Frame frame, String jobtitle, Properties props) Parameters frame The frame to be used as the parent of a platform-specific printing dialog. jobtitle The name of the job. props Properties for this print job. http://localhost/java/javaref/awt/ch19_60.htm (6 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
Returns A PrintJob object. If the user canceled the printing operation, null is returned.
getScreenResolution public abstract int getScreenResolution() Returns The current resolution of the user's screen, in dots-per-inch.
getScreenSize public abstract Dimension getScreenSize() Returns The size of the screen available to the Toolkit, in pixels, as a Dimension object.
getSystemClipboard public abstract Clipboard getSystemClipboard() Returns A Clipboard object that can be used for cut, copy, and paste operations.
getSystemEventQueue public final EventQueue getSystemEventQueue() Returns A reference to the system's event queue, allowing the program to post new events or inspect the queue.
prepareImage public abstract boolean prepareImage (Image image, int width, int height, ImageObserver observer) Parameters image Image to check. width Width of the scaled image; -1 if image will be rendered unscaled. height Height of the scaled image; -1 if image will be rendered unscaled. observer http://localhost/java/javaref/awt/ch19_60.htm (7 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
The Component that image will be rendered on. Returns true if image fully loaded, false otherwise. Description Forces the system to start loading the image.
sync public abstract void sync() Description Flushes the display of the underlying graphics context.
Protected Instance Methods createButton protected abstract ButtonPeer createButton (Button b) Parameters b Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Button.
createCanvas protected abstract CanvasPeer createCanvas (Canvas c) Parameters c Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Canvas.
http://localhost/java/javaref/awt/ch19_60.htm (8 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
createCheckbox protected abstract CheckboxPeer createCheckbox (Checkbox cb) Parameters cb Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Checkbox.
createCheckboxMenuItem protected abstract CheckboxMenuItemPeer createCheckboxMenuItem (CheckboxMenuItem cmi) Parameters cmi Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the CheckboxMenuItem.
createChoice protected abstract ChoicePeer createChoice (Choice c) Parameters c Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Choice.
createComponent protected LightweightPeer createComponent (Component target) Parameters target http://localhost/java/javaref/awt/ch19_60.htm (9 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Component.
createDialog protected abstract DialogPeer createDialog (Dialog d) Parameters d Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Dialog.
createFileDialog protected abstract FileDialogPeer createFileDialog (FileDialog fd) Parameters fd Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the FileDialog.
createFrame protected abstract FramePeer createFrame (Frame f) Parameters f Component whose peer needs to be created. Returns Newly created peer. Description
http://localhost/java/javaref/awt/ch19_60.htm (10 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
Creates a peer for the Frame.
createLabel protected abstract LabelPeer createLabel (Label l) Parameters l Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Label.
createList protected abstract ListPeer createList (List l) Parameters l Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the List.
createMenu protected abstract MenuPeer createMenu (Menu m) Parameters m Menu whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the given Menu.
http://localhost/java/javaref/awt/ch19_60.htm (11 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
createMenuBar protected abstract MenuBarPeer createMenuBar (MenuBar mb) Parameters mb MenuBar whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the MenuBar.
createMenuItem protected abstract MenuItemPeer createMenuItem (MenuItem mi) Parameters mi MenuItem whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the MenuItem.
createPanel protected abstract PanelPeer createPanel (Panel p) Parameters p Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Panel.
createPopupMenu protected abstract PopupMenuPeer createPopupMenu (PopupMenu target) Parameters target http://localhost/java/javaref/awt/ch19_60.htm (12 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the PopupMenu.
createScrollPane protected abstract ScrollPanePeer createScrollPane (ScrollPane target) Parameters target Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the ScrollPane.
createScrollbar protected abstract ScrollbarPeer createScrollbar (Scrollbar sb) Parameters sb Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Scrollbar.
createTextArea protected abstract TextAreaPeer createTextArea (TextArea ta) Parameters ta Component whose peer needs to be created. Returns Newly created peer. Description http://localhost/java/javaref/awt/ch19_60.htm (13 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
Creates a peer for the TextArea.
createTextField protected abstract TextFieldPeer createTextField (TextField tf) Parameters tf Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the TextField.
createWindow protected abstract WindowPeer createWindow (Window w) Parameters w Component whose peer needs to be created. Returns Newly created peer. Description Creates a peer for the Window.
getFontPeer protected abstract FontPeer getFontPeer (String name, int style) Parameters name Name of the font to be created. style Style of the font to be created. Returns Newly created peer. Description Creates a FontPeer.
http://localhost/java/javaref/awt/ch19_60.htm (14 of 15) [20/12/2001 11:13:01]
[Chapter 19] Toolkit
getSystemEventQueueImpl protected abstract getSystemEventQueueImpl() Returns A toolkit-specific EventQueue object.
loadSystemColors protected abstract void loadSystemColors (int[] systemColors) Description Fills the given integer array with the current system colors.
See Also Button, ButtonPeer, Canvas, CanvasPeer, Checkbox, CheckboxMenuItem, CheckboxMenuItemPeer, CheckboxPeer, Choice, ChoicePeer, Clipboard, ColorModel, Component, Container, Dialog, DialogPeer, Dimension, FileDialog, FileDialogPeer, Font, FontMetrics, FontPeer, Frame, FramePeer, Image, ImageObserver, ImageProducer, Label, LabelPeer, LightweightPeer, List, ListPeer, Menu, MenuBar, MenuBarPeer, MenuItem, MenuItemPeer, MenuPeer, Panel, PanelPeer, PrintJob, Scrollbar, ScrollbarPeer, ScrollPane, ScrollPanePeer, String, TextArea, TextAreaPeer, TextField, TextFieldPeer, Window, WindowPeer
TextField
http://localhost/java/javaref/awt/ch19_60.htm (15 of 15) [20/12/2001 11:13:01]
Window
[Chapter 19] Window
Chapter 19 java.awt Reference
Window Name Window
Description The Window class serves as a top-level display area that exists outside the browser or applet area you may be working in. A window must have a parent Frame.
Class Definition public class java.awt.Window extends java.awt.Container { // Constructors public Window (Frame parent); // Instance Methods public void addNotify(); public synchronized void addWindowListener (WindowListener l); public void dispose();
http://localhost/java/javaref/awt/ch19_61.htm (1 of 6) [20/12/2001 11:13:05]
[Chapter 19] Window
public Component getFocusOwner(); public Locale getLocale(); public Toolkit getToolkit(); public final String getWarningString(); public boolean isShowing(); public void pack(); public boolean postEvent (Event e); public synchronized void remove WindowListener (WindowListener l); public void show(); public void toBack(); public void toFront(); //Protected Instance Methods protected void processEvent (AWTEvent e); protected void processWindowEvent (WindowEvent e); }
Constructors Window public Window (Frame parent) Parameters parent Frame that is to act as the parent of Window. Description Constructs a Window object.
Instance Methods addNotify public void addNotify() Overrides Container.addNotify() Description Creates Window's peer and peers of contained components.
http://localhost/java/javaref/awt/ch19_61.htm (2 of 6) [20/12/2001 11:13:05]
[Chapter 19] Window
removeWindowListener public synchronized void removeWindowListener(WindowListener l) Parameters l One of this Frame's WindowListeners. Description Remove an event listener.
addWindowListener public synchronized void addWindowListener (WindowListener l) Parameters l An object that implements the WindowListener interface. Description Add a listener for windowing events.
dispose public void dispose() Returns Releases the resources of the Window.
getFocusOwner public Component getFocusOwner() Returns The child component that currently has the input focus.
getLocale public Locale getLocale() Returns The locale for this Window. http://localhost/java/javaref/awt/ch19_61.htm (3 of 6) [20/12/2001 11:13:05]
[Chapter 19] Window
Overrides Window.getLocale()
getToolkit public Toolkit getToolkit() Returns Toolkit of Window. Overrides Component.getToolkit()
getWarningString public final String getWarningString() Returns String that will be displayed on the bottom of insecure Window instances.
isShowing public boolean isShowing() Returns true if the Window is showing on the screen, false otherwise.
pack public void pack() Description Resizes Window to getPreferredSize() of contained components.
postEvent public boolean postEvent (Event e) Parameters e Event instance to post to window. Returns http://localhost/java/javaref/awt/ch19_61.htm (4 of 6) [20/12/2001 11:13:05]
[Chapter 19] Window
If Event is handled, true is returned. Otherwise, false is returned. Description Tells the Window to deal with Event.
removeWindowListener public synchronized void removeWindowListener (WindowListener l) Parameters l One of this Frame's WindowListeners. Description Remove an event listener.
show public void show() Description Show the Window and validate its components. Overrides Component.show()
toBack public void toBack() Description Puts the Window in the background of the display.
toFront public void toFront() Description Brings the Window to the foreground of the display.
http://localhost/java/javaref/awt/ch19_61.htm (5 of 6) [20/12/2001 11:13:05]
[Chapter 19] Window
Protected Instance Methods processEvent protected void processEvent (AWTEvent e) Parameters e The event to process. Description Low level AWTEvents are passed to this method for processing.
processWindowEvent protected void processWindowEvent (WindowEvent e) Parameters e The event to process. Description Window events are passed to this method for processing. Normally, this method is called by processEvent().
See Also Component, Container, Dialog, Frame, String, Toolkit
Toolkit
http://localhost/java/javaref/awt/ch19_61.htm (6 of 6) [20/12/2001 11:13:05]
Clipboard
[Chapter 20] ClipboardOwner
Chapter 20 java.awt.datatransfer Reference
ClipboardOwner Name ClipboardOwner
Description ClipboardOwner is implemented by classes that want to be notified when someone else sets the contents of a clipboard.
Interface Definition public abstract interface java.awt.datatransfer.ClipboardOwner { // Interface Methods public abstract void lostOwnership (Clipboard clipboard, Transferable contents); }
Interface Methods lostOwnership public abstract void lostOwnership (Clipboard clipboard, Transferable contents) Parameters clipboard The clipboard whose contents have changed. contents The contents that this owner originally put on the clipboard. Description Tells the ClipboardOwner that the contents it placed on the given clipboard are no longer there. http://localhost/java/javaref/awt/ch20_02.htm (1 of 2) [20/12/2001 11:13:07]
[Chapter 20] ClipboardOwner
See Also Clipboard, StringSelection, Transferable
Clipboard
http://localhost/java/javaref/awt/ch20_02.htm (2 of 2) [20/12/2001 11:13:07]
DataFlavor
[Chapter 20] DataFlavor
Chapter 20 java.awt.datatransfer Reference
DataFlavor Name DataFlavor
Description The DataFlavor class encapsulates information about data formats.
Class Definition public class java.awt.datatransfer.DataFlavor extends java.lang.Object { // Class Variables public static DataFlavor plainTextFlavor; public static DataFlavor stringFlavor; // Constructors public DataFlavor (Class representationClass, String humanPresentableName); public DataFlavor (String MIMEType, String humanPresentableName); // Instance Methods public boolean equals (DataFlavor dataFlavor); public String getHumanPresentableName(); public String getMIMEType(); public Class getRepresentationClass(); public boolean isMIMETypeEqual (String MIMEType); http://localhost/java/javaref/awt/ch20_03.htm (1 of 6) [20/12/2001 11:13:09]
[Chapter 20] DataFlavor
public final boolean isMIMETypeEqual (DataFlavor dataFlavor); public void setHumanPresentableName (String humanPresentableName); // Protected Instance Methods protected String normalizeMIMEType (String MIMEType); protected String normalizeMIMETypeParameter (String parameterName, String parameterValue); }
Class Variables plainTextFlavor public static DataFlavor plainTextFlavor A preset DataFlavor object representing plain text.
stringFlavor public static DataFlavor stringFlavor A preset DataFlavor object representing a Java String.
Constructors DataFlavor public DataFlavor (Class representationClass, String humanPresentableName) Parameters representationClass The Java class that represents data in this flavor. humanPresentableName A name for this flavor that humans will recognize. Description Constructs a DataFlavor object with the given characteristics. The MIME type for this DataFlavor is application/x-java-serialized-object <Java ClassName>.[1] [1] The type name changed to x-java-serialized-object in the 1.1.1 release. public DataFlavor (String MIMEType, String humanPresentableName)
http://localhost/java/javaref/awt/ch20_03.htm (2 of 6) [20/12/2001 11:13:09]
[Chapter 20] DataFlavor
Parameters MIMEType The MIME type string this DataFlavor represents. humanPresentableName A name for this flavor that humans will recognize. Description Constructs a DataFlavor object with the given characteristics. The representation class used for this DataFlavor is java.io.InputStream.
Instance Methods equals public boolean equals (DataFlavor dataFlavor) Parameters dataFlavor The flavor to compare. Returns true if dataFlavor is equivalent to this DataFlavor, false otherwise. Description Compares two different DataFlavor instances for equivalence.
getHumanPresentableName public String getHumanPresentableName() Returns The name of this flavor.
getMIMEType public String getMIMEType() Returns The MIME type string for this flavor.
http://localhost/java/javaref/awt/ch20_03.htm (3 of 6) [20/12/2001 11:13:09]
[Chapter 20] DataFlavor
getRepresentationClass public Class getRepresentationClass() Returns The Java class that will be used to represent data in this flavor.
isMIMETypeEqual public boolean isMIMETypeEqual (String MIMEType) Parameters MIMEType The type to compare. Returns true if the given MIME type is the same as this DataFlavor's MIME type; false otherwise. Description Compares two different DataFlavor MIME types for equivalence. public final boolean isMIMETypeEqual (DataFlavor dataFlavor) Parameters dataFlavor The flavor to compare. Returns true if DataFlavor's MIME type is the same as this DataFlavor's MIME type; false otherwise. Description Compares two different DataFlavor MIME types for equivalence.
setHumanPresentableName public void setHumanPresentableName (String humanPresentableName) Parameters humanPresentableName A name for this flavor that humans will recognize. Description
http://localhost/java/javaref/awt/ch20_03.htm (4 of 6) [20/12/2001 11:13:09]
[Chapter 20] DataFlavor
Changes the name of the DataFlavor.
Protected Instance Methods normalizeMIMEType protected String normalizeMIMEType (String MIMEType) Parameters MIMEType The MIME type string to normalize. Returns Normalized MIME type string. Description This method is called for each MIME type string. Subclasses can override this method to add default parameter/value pairs to MIME strings.
normalizeMIMETypeParameter protected String normalizeMIMETypeParameter (String parameterName, String parameterValue) Parameters parameterName The MIME type parameter to normalize. parameterValue The corresponding value. Returns Normalized MIME type parameter string. Description This method is called for each MIME type parameter string. Subclasses can override this method to handle special parameters, such as those that are case-insensitive.
See Also Class, String
http://localhost/java/javaref/awt/ch20_03.htm (5 of 6) [20/12/2001 11:13:09]
[Chapter 20] DataFlavor
ClipboardOwner
http://localhost/java/javaref/awt/ch20_03.htm (6 of 6) [20/12/2001 11:13:09]
StringSelection
[Chapter 20] StringSelection
Chapter 20 java.awt.datatransfer Reference
StringSelection Name StringSelection
Description StringSelection is a "convenience" class that can be used for copy and paste operations on Unicode text strings. For example, you could place a string on the system's clipboard with the following code: Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection s = new StringSelection( "Be safe when you cut and paste."); c.setContents(s, s);
Class Definition public class java.awt.datatransfer.StringSelection extends java.lang.Object implements java.awt.datatransfer.ClipboardOwner, java.awt.datatransfer.Transferable { // Constructor public StringSelection(String data); // Instance Methods
http://localhost/java/javaref/awt/ch20_04.htm (1 of 4) [20/12/2001 11:13:10]
[Chapter 20] StringSelection
public synchronized Object getTransferData (DataFlavor flavor) throws UnsupportedFlavorException, IOException; public synchronized DataFlavor[] getTransferDataFlavors(); public boolean isDataFlavorSupported (DataFlavor flavor); public void lostOwnership (Clipboard clipboard, Transferable contents); }
Constructors StringSelection public StringSelection (String data) Parameters data The string to be placed in a clipboard. Description Constructs a StringSelection object from the given string.
Instance Methods getTransferData public synchronized Object getTransferData (DataFlavor flavor) throws UnsupportedFlavorException, IOException Parameters flavor The requested flavor for the returned data, which can be either DataFlavor.stringFlavor or DataFlavor.plainTextFlavor. Returns The string that the StringSelection was constructed with. This is returned either as a String object or a Reader object, depending on the flavor requested. Throws UnsupportedFlavorException If the requested flavor is not supported. IOException If a Reader representing the string could not be created. Implements
http://localhost/java/javaref/awt/ch20_04.htm (2 of 4) [20/12/2001 11:13:10]
[Chapter 20] StringSelection
Transferable.getTransferData(DataFlavor) Description Returns the string this StringSelection represents. This is returned either as a String object or a Reader object, depending on the flavor requested.
getTransferDataFlavors public synchronized DataFlavor[] getTransferDataFlavors() Returns An array of the data flavors the StringSelection supports. Implements Transferable.getTransferDataFlavors() Description DataFlavor.stringFlavor and DataFlavor.plainTextFlavor are returned.
isDataFlavorSupported public boolean isDataFlavorSupported (DataFlavor flavor) Parameters flavor The flavor in question. Returns true if flavor is supported; false otherwise. Implements Transferable.isDataFlavorSupported(DataFlavor)
lostOwnership public void lostOwnership (Clipboard clipboard, Transferable contents) Parameters clipboard The clipboard whose contents are changing. contents The contents that were on the clipboard. Implements ClipboardOwner.lostOwnership(Clipboard, Transferable) http://localhost/java/javaref/awt/ch20_04.htm (3 of 4) [20/12/2001 11:13:10]
[Chapter 20] StringSelection
Description Does nothing.
See Also Clipboard, ClipboardOwner, DataFlavor, String, Transferable
DataFlavor
http://localhost/java/javaref/awt/ch20_04.htm (4 of 4) [20/12/2001 11:13:10]
Transferable
[Chapter 20] Transferable
Chapter 20 java.awt.datatransfer Reference
Transferable Name Transferable
Description The Transferable interface is implemented by objects that can be placed on Clipboards.
Interface Definition public abstract interface Transferable { // Instance Methods public abstract Object getTransferData (DataFlavor flavor) throws UnsupportedFlavorException, IOException; public abstract DataFlavor[] getTransferDataFlavors(); public abstract boolean isDataFlavorSupported (DataFlavor flavor); }
Interface Methods
http://localhost/java/javaref/awt/ch20_05.htm (1 of 3) [20/12/2001 11:13:11]
[Chapter 20] Transferable
getTransferData public abstract Object getTransferData (DataFlavor flavor) throws UnsupportedFlavorException, IOException Parameters flavor The requested flavor for the returned data. Returns The data represented by this Transferable object, in the requested flavor. Throws UnsupportedFlavorException If the requested flavor is not supported. IOException If a Reader representing the data could not be created. Description Returns the data this Transferable object represents. The class of object returned depends on the flavor requested.
getTransferDataFlavors public abstract DataFlavor[] getTransferDataFlavors() Returns An array of the supported data flavors. Description The data flavors should be returned in order, sorted from most to least descriptive.
isDataFlavorSupported public abstract boolean isDataFlavorSupported (DataFlavor flavor) Parameters flavor The flavor in question. Returns true if flavor is supported; false otherwise.
http://localhost/java/javaref/awt/ch20_05.htm (2 of 3) [20/12/2001 11:13:11]
[Chapter 20] Transferable
See Also Clipboard, DataFlavor, Reader, StringSelection, Transferable
StringSelection
http://localhost/java/javaref/awt/ch20_05.htm (3 of 3) [20/12/2001 11:13:11]
UnsupportedFlavorException
[Chapter 20] UnsupportedFlavorException
Chapter 20 java.awt.datatransfer Reference
UnsupportedFlavorException Name UnsupportedFlavorException
Description This exception is thrown from Transferable.getTransferData(DataFlavor) to indicate that the DataFlavor requested is not available.
Class Definition public class java.awt.datatransfer.UnsupportedFlavorException extends java.lang.Exception { // Constructor public UnsupportedFlavorException (DataFlavor flavor); }
Constructors
http://localhost/java/javaref/awt/ch20_06.htm (1 of 2) [20/12/2001 11:13:14]
[Chapter 20] UnsupportedFlavorException
UnsupportedFlavorException public UnsupportedFlavorException (DataFlavor flavor) Parameters flavor The flavor that caused the exception.
See Also DataFlavor, Exception, Transferable
Transferable
http://localhost/java/javaref/awt/ch20_06.htm (2 of 2) [20/12/2001 11:13:14]
ActionEvent
[Chapter 21] ActionListener
Chapter 21 java.awt.event Reference
ActionListener Name ActionListener
Description Objects that implement the ActionListener interface can receive ActionEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.ActionListener extends java.util.EventListener { // Interface Methods public abstract void actionPerformed (ActionEvent e); }
http://localhost/java/javaref/awt/ch21_02.htm (1 of 2) [20/12/2001 11:13:16]
[Chapter 21] ActionListener
Interface Methods actionPerformed public abstract void actionPerformed (ActionEvent e) Parameters e The action event that occurred. Description Notifies the ActionListener that an event occurred.
See Also ActionEvent, AWTEventMulticaster, EventListener
ActionEvent
http://localhost/java/javaref/awt/ch21_02.htm (2 of 2) [20/12/2001 11:13:16]
AdjustmentEvent
[Chapter 21] AdjustmentEvent
Chapter 21 java.awt.event Reference
AdjustmentEvent Name AdjustmentEvent
Description AdjustmentEvents are generated by objects that implement the Adjustable interface. Scrollbar is one example of such an object.
Class Definition public class java.awt.event.AdjustmentEvent extends java.awt.AWTEvent { // Constants public final static int ADJUSTMENT_FIRST; public final static int ADJUSTMENT_LAST; public final static int ADJUSTMENT_VALUE_CHANGED; public final static int BLOCK_DECREMENT; public final static int BLOCK_INCREMENT; public final static int TRACK; public final static int UNIT_DECREMENT; public final static int UNIT_INCREMENT; // Constructors public AdjustmentEvent (Adjustable source, int id, int type, int value); // Instance Methods
http://localhost/java/javaref/awt/ch21_03.htm (1 of 4) [20/12/2001 11:13:17]
[Chapter 21] AdjustmentEvent
public public public public
Adjustable getAdjustable(); int getAdjustmentType(); int getValue(); String paramString();
}
Constants ADJUSTMENT_FIRST public final static int ADJUSTMENT_FIRST Specifies the beginning range of adjustment event ID values.
ADJUSTMENT_LAST public final static int ADJUSTMENT_LAST Specifies the ending range of adjustment event ID values.
ADJUSTMENT_VALUE_CHANGED public final static int ADJUSTMENT_VALUE_CHANGED Event type ID for value changed.
BLOCK_DECREMENT public final static int BLOCK_DECREMENT Adjustment type for block decrement.
BLOCK_INCREMENT public final static int BLOCK_INCREMENT Adjustment type for block increment.
TRACK public final static int TRACK Adjustment type for tracking.
http://localhost/java/javaref/awt/ch21_03.htm (2 of 4) [20/12/2001 11:13:17]
[Chapter 21] AdjustmentEvent
UNIT_DECREMENT public final static int UNIT_DECREMENT Adjustment type for unit decrement.
UNIT_INCREMENT public final static int UNIT_INCREMENT Adjustment type for unit increment.
Constructors AdjustmentEvent public AdjustmentEvent (Adjustable source, int id, int type, int value) Parameters source The object that generated the event. id The event type ID of the event. type The type of adjustment event. value The value of the Adjustable object. Description Constructs an AdjustmentEvent with the given characteristics.
Instance Methods getAdjustable public Adjustable getAdjustable() Returns The source of this event.
http://localhost/java/javaref/awt/ch21_03.htm (3 of 4) [20/12/2001 11:13:17]
[Chapter 21] AdjustmentEvent
getAdjustmentType public int getAdjustmentType() Returns One of the adjustment type constants. Description The type will be BLOCK_DECREMENT, BLOCK_INCREMENT, TRACK, UNIT_DECREMENT, or UNIT_INCREMENT.
getValue public int getValue() Returns The new value of the Adjustable object.
paramString public String paramString() Returns String with current settings of the AdjustmentEvent. Overrides AWTEvent.paramString() Description Helper method for toString() to generate string of current settings.
See Also Adjustable, AdjustmentListener, AWTEvent, Scrollbar
ActionListener
http://localhost/java/javaref/awt/ch21_03.htm (4 of 4) [20/12/2001 11:13:17]
AdjustmentListener
[Chapter 21] AdjustmentListener
Chapter 21 java.awt.event Reference
AdjustmentListener Name AdjustmentListener
Description Objects that implement the AdjustmentListener interface can receive AdjustmentEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.AdjustmentListener extends java.util.Eventlistener { // Interface Methods public abstract void adjustmentValueChanged (AdjustmentEvent e); }
http://localhost/java/javaref/awt/ch21_04.htm (1 of 2) [20/12/2001 11:13:20]
[Chapter 21] AdjustmentListener
Interface Methods adjustmentPerformed public abstract void adjustmentValueChanged (AdjustmentEvent e) Parameters e The adjustment event that occurred. Description Notifies the AdjustmentListener that an event occurred.
See Also AdjustmentEvent, AWTEventMulticaster, EventListener
AdjustmentEvent
http://localhost/java/javaref/awt/ch21_04.htm (2 of 2) [20/12/2001 11:13:20]
ComponentAdapter
[Chapter 21] ComponentAdapter
Chapter 21 java.awt.event Reference
ComponentAdapter Name ComponentAdapter
Description ComponentAdapter is a class that implements the methods of ComponentListener with empty functions. It may be easier for you to extend ComponentAdapter, overriding only those methods you are interested in, than to implement ComponentListener and provide the empty functions yourself.
Class Definition public abstract class java.awt.event.ComponentAdapter extends java.lang.Object implements java.awt.event.ComponentListener { // Instance Methods public void componentHidden (ComponentEvent e); public void componentMoved (ComponentEvent e); public void componentResized (ComponentEvent e); public void componentShown (ComponentEvent e); }
http://localhost/java/javaref/awt/ch21_05.htm (1 of 3) [20/12/2001 11:13:22]
[Chapter 21] ComponentAdapter
Instance Methods componentHidden public void componentHidden (ComponentEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a component is hidden.
componentMoved public void componentMoved (ComponentEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a component is moved.
componentResized public void componentResized (ComponentEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a component is resized.
componentShown public void componentShown (ComponentEvent e) Parameters e The event that has occurred.
http://localhost/java/javaref/awt/ch21_05.htm (2 of 3) [20/12/2001 11:13:22]
[Chapter 21] ComponentAdapter
Description Does nothing. Override this function to be notified when a component is shown.
See Also Component, ComponentEvent, ComponentListener
AdjustmentListener
http://localhost/java/javaref/awt/ch21_05.htm (3 of 3) [20/12/2001 11:13:22]
ComponentEvent
[Chapter 21] ComponentEvent
Chapter 21 java.awt.event Reference
ComponentEvent Name ComponentEvent
Description Component events are generated when a component is shown, hidden, moved, or resized. AWT automatically deals with component moves and resizing; these events are provided only for notification. Subclasses of ComponentEvent deal with other specific component-level events.
Class Definition public class java.awt.event.ComponentEvent extends java.awt.AWTEvent { // Constants
http://localhost/java/javaref/awt/ch21_06.htm (1 of 4) [20/12/2001 11:13:24]
[Chapter 21] ComponentEvent
public final static int COMPONENT_FIRST; public final static int COMPONENT_HIDDEN; public final static int COMPONENT_LAST; public final static int COMPONENT_MOVED; public final static int COMPONENT_RESIZED; public final static int COMPONENT_SHOWN; // Constructors public ComponentEvent (Component source, int id); // Instance Methods public Component getComponent(); public String paramString(); }
Constants COMPONENT_FIRST public final static int COMPONENT_FIRST Specifies the beginning range of component event ID values.
COMPONENT_HIDDEN public final static int COMPONENT_HIDDEN Event type ID indicating that the component was hidden.
COMPONENT_LAST public final static int COMPONENT_LAST Specifies the ending range of component event ID values.
COMPONENT_MOVED public final static int COMPONENT_MOVED Event type ID indicating that the component was moved.
COMPONENT_RESIZED public final static int COMPONENT_RESIZED Event type ID indicating that the component was resized.
http://localhost/java/javaref/awt/ch21_06.htm (2 of 4) [20/12/2001 11:13:24]
[Chapter 21] ComponentEvent
COMPONENT_SHOWN public final static int COMPONENT_SHOWN Event type ID indicating that the component was shown.
Constructors ComponentEvent public ComponentEvent (Component source, int id) Parameters source The object that generated the event. id The event type ID of the event. Description Constructs a ComponentEvent with the given characteristics.
Instance Methods getComponent public Component getComponent() Returns The source of this event.
paramString public String paramString() Returns String with current settings of the ComponentEvent. Overrides AWTEvent.paramString() Description Helper method for toString() to generate string of current settings. http://localhost/java/javaref/awt/ch21_06.htm (3 of 4) [20/12/2001 11:13:24]
[Chapter 21] ComponentEvent
See Also AWTEvent, Component, ComponentAdapter, ComponentListener, ContainerEvent, FocusEvent, InputEvent, PaintEvent, WindowEvent
ComponentAdapter
http://localhost/java/javaref/awt/ch21_06.htm (4 of 4) [20/12/2001 11:13:24]
ComponentListener
[Chapter 21] ComponentListener
Chapter 21 java.awt.event Reference
ComponentListener Name ComponentListener
Description Objects that implement the ComponentListener interface can receive ComponentEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.ComponentListener extends java.util.EventListener { // Instance Methods public abstract void componentHidden (ComponentEvent e); public abstract void componentMoved (ComponentEvent e); public abstract void componentResized (ComponentEvent e); public abstract void componentShown (ComponentEvent e); }
http://localhost/java/javaref/awt/ch21_07.htm (1 of 3) [20/12/2001 11:13:25]
[Chapter 21] ComponentListener
Interface Methods componentHidden public abstract void componentHidden (ComponentEvent e) Parameters e The component event that occurred. Description Notifies the ComponentListener that a component was hidden.
componentMoved public abstract void componentMoved (ComponentEvent e) Parameters e The component event that occurred. Description Notifies the ComponentListener that a component was moved.
componentResized public abstract void componentResized (ComponentEvent e) Parameters e The component event that occurred. Description Notifies the ComponentListener that a component was resized.
componentShown public abstract void componentShown (ComponentEvent e) Parameters e The component event that occurred.
http://localhost/java/javaref/awt/ch21_07.htm (2 of 3) [20/12/2001 11:13:25]
[Chapter 21] ComponentListener
Description Notifies the ComponentListener that a component was shown.
See Also AWTEventMulticaster, ComponentAdapter, ComponentEvent, EventListener
ComponentEvent
http://localhost/java/javaref/awt/ch21_07.htm (3 of 3) [20/12/2001 11:13:25]
ContainerAdapter
[Chapter 21] ContainerAdapter
Chapter 21 java.awt.event Reference
ContainerAdapter Name ContainerAdapter
Description The ContainerAdapter class implements the methods of ContainerListener with empty functions. It may be easier for you to extend ContainerAdapter, overriding only those methods you are interested in, than to implement ContainerListener and provide the empty functions yourself.
Class Definition public abstract class java.awt.event.ContainerAdapter extends java.lang.Object implements java.awt.event.ContainerListener { // Instance Methods public void componentAdded (ContainerEvent e); public void componentRemoved (ContainerEvent e); }
http://localhost/java/javaref/awt/ch21_08.htm (1 of 2) [20/12/2001 11:13:29]
[Chapter 21] ContainerAdapter
Instance Methods componentAdded public void componentAdded (ComponentEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a component is added to a container.
componentRemoved public void componentRemoved (ComponentEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a component is removed from a container.
See Also ContainerEvent, ContainerListener
ComponentListener
http://localhost/java/javaref/awt/ch21_08.htm (2 of 2) [20/12/2001 11:13:29]
[Chapter 21] ContainerEvent
Chapter 21 java.awt.event Reference
ContainerEvent Name ContainerEvent
Description Container events are fired off when a component is added to or removed from a container. The AWT automatically deals with adding components to containers; these events are provided only for notification.
Class Definition public class java.awt.event.ContainerEvent extends java.awt.event.ComponentEvent { // Constants public final static int COMPONENT_ADDED; public final static int COMPONENT_REMOVED; public final static int CONTAINER_FIRST; public final static int CONTAINER_LAST; // Constructors public ContainerEvent (Component source, int id, Component child); // Instance Methods
http://localhost/java/javaref/awt/ch21_09.htm (1 of 3) [20/12/2001 11:13:32]
[Chapter 21] ContainerEvent
public Component getChild(); public Container getContainer(); public String paramString(); }
Constants COMPONENT_ADDED public final static int COMPONENT_ADDED Event type ID indicating that a component was added to a container.
CONTAINER_FIRST public final static int CONTAINER_FIRST Specifies the beginning range of container event ID values.
CONTAINER_LAST public final static int CONTAINER_LAST Specifies the ending range of container event ID values.
COMPONENT_REMOVED public final static int COMPONENT_REMOVED Event type ID indicating that a component was removed from a container.
Constructors ContainerEvent public ContainerEvent (Component source, int id, Component child) Parameters source The object that generated the event. id The event type ID of the event. child http://localhost/java/javaref/awt/ch21_09.htm (2 of 3) [20/12/2001 11:13:32]
[Chapter 21] ContainerEvent
The component that was added or removed. Description Constructs a ContainerEvent with the given characteristics.
Instance Methods getChild public Component getChild() Returns The component that is being added or removed.
getContainer public Container getContainer() Returns The container for this event.
paramString public String paramString() Returns String with current settings of the ContainerEvent. Overrides ComponentEvent.paramString() Description Helper method for toString() to generate string of current settings.
See Also Component, ComponentEvent, Container, ContainerAdapter, ContainerListener
ContainerAdapter
http://localhost/java/javaref/awt/ch21_09.htm (3 of 3) [20/12/2001 11:13:32]
[Chapter 21] ContainerListener
Chapter 21 java.awt.event Reference
ContainerListener Name ContainerListener
Description Objects that implement the ContainerListener interface can receive ContainerEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.ContainerListener extends java.util.EventListener { // Instance Methods public abstract void componentAdded (ContainerEvent e); public abstract void componentRemoved (ContainerEvent e); }
http://localhost/java/javaref/awt/ch21_10.htm (1 of 2) [20/12/2001 11:13:36]
[Chapter 21] ContainerListener
Interface Methods componentAdded public abstract void componentAdded (ContainerEvent e) Parameters e The event that occurred. Description Notifies the ContainerListener that a component has been added to the container.
componentRemoved public abstract void componentRemoved (ContainerEvent e) Parameters e The event that occurred. Description Notifies the ContainerListener that a component has been removed from the container.
See Also ContainerAdapter, ContainerEvent, EventListener
ContainerEvent
http://localhost/java/javaref/awt/ch21_10.htm (2 of 2) [20/12/2001 11:13:36]
FocusAdapter
[Chapter 21] FocusAdapter
Chapter 21 java.awt.event Reference
FocusAdapter Name FocusAdapter
Description The FocusAdapter class implements the methods of FocusListener with empty functions. It may be easier for you to extend FocusAdapter, overriding only those methods you are interested in, than to implement FocusListener and provide the empty functions yourself.
Class Definition public abstract class java.awt.event.FocusAdapter extends java.lang.Object implements java.awt.event.FocusListener { // Instance Methods public void focusGained (FocusEvent e); public void focusLost (FocusEvent e); }
http://localhost/java/javaref/awt/ch21_11.htm (1 of 2) [20/12/2001 11:13:38]
[Chapter 21] FocusAdapter
Instance Methods focusGained public void focusGained (FocusEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a component gains focus.
focusLost public void focusLost (FocusEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a component loses focus.
See Also FocusEvent, FocusListener
ContainerListener
http://localhost/java/javaref/awt/ch21_11.htm (2 of 2) [20/12/2001 11:13:38]
FocusEvent
[Chapter 21] FocusEvent
Chapter 21 java.awt.event Reference
FocusEvent Name FocusEvent
Description Focus events are generated when a component gets or loses input focus. Focus events come in two flavors, permanent and temporary. Permanent focus events occur with explicit focus changes. For example, when the user tabs through components, this causes permanent focus events. An example of a temporary focus event is when a component loses focus as its containing window is deactivated.
Class Definition public class java.awt.event.FocusEvent extends java.awt.event.ComponentEvent { // Constants public final static int FOCUS_FIRST; public final static int FOCUS_GAINED; public final static int FOCUS_LAST; public final static int FOCUS_LOST; // Constructors public FocusEvent (Component source, int id);
http://localhost/java/javaref/awt/ch21_12.htm (1 of 4) [20/12/2001 11:13:40]
[Chapter 21] FocusEvent
public FocusEvent (Component source, int id, boolean temporary); // Instance Methods public boolean isTemporary(); public String paramString(); }
Constants FOCUS_FIRST public final static int FOCUS_FIRST Specifies the beginning range of focus event ID values.
FOCUS_GAINED public final static int FOCUS_GAINED Event type ID indicating that the component gained the input focus.
FOCUS_LAST public final static int FOCUS_LAST Specifies the ending range of focus event ID values.
FOCUS_LOST public final static int FOCUS_LOST Event type ID indicating that the component lost the input focus.
Constructors FocusEvent public FocusEvent (Component source, int id) Parameters source The object that generated the event. id The event type ID of the event. http://localhost/java/javaref/awt/ch21_12.htm (2 of 4) [20/12/2001 11:13:40]
[Chapter 21] FocusEvent
Description Constructs a non-temporary FocusEvent with the given characteristics. public FocusEvent (Component source, int id, boolean temporary) Parameters source The object that generated the event. id The event type ID of the event. temporary A flag indicating whether this is a temporary focus event. Description Constructs a FocusEvent with the given characteristics.
Instance Methods isTemporary public boolean isTemporary() Returns true if this is a temporary focus event; false otherwise.
paramString public String paramString() Returns String with current settings of the FocusEvent. Overrides ComponentEvent.paramString() Description Helper method for toString() to generate string of current settings.
http://localhost/java/javaref/awt/ch21_12.htm (3 of 4) [20/12/2001 11:13:40]
[Chapter 21] FocusEvent
See Also Component, ComponentEvent, FocusAdapter, FocusListener
FocusAdapter
http://localhost/java/javaref/awt/ch21_12.htm (4 of 4) [20/12/2001 11:13:40]
FocusListener
[Chapter 21] FocusListener
Chapter 21 java.awt.event Reference
FocusListener Name FocusListener
Description Objects that implement the FocusListener interface can receive FocusEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.FocusListener extends java.util.EventListener { // Instance Methods public abstract void focusGained (FocusEvent e); public abstract void focusLost (FocusEvent e); }
http://localhost/java/javaref/awt/ch21_13.htm (1 of 2) [20/12/2001 11:13:42]
[Chapter 21] FocusListener
Interface Methods focusGained public abstract void focusGained (FocusEvent e) Parameters e The component event that occurred. Description Notifies the FocusListener that a component gained the input focus.
focusLost public abstract void focusLost (FocusEvent e) Parameters e The component event that occurred. Description Notifies the FocusListener that a component lost the input focus.
See Also AWTEventMulticaster, EventListener, FocusAdapter, FocusEvent
FocusEvent
http://localhost/java/javaref/awt/ch21_13.htm (2 of 2) [20/12/2001 11:13:42]
InputEvent
[Chapter 21] InputEvent
Chapter 21 java.awt.event Reference
InputEvent Name InputEvent
Description InputEvent is the root class for representing user input events. Input events are passed to listeners before the event source processes them. If one of the listeners consumes an event by using consume(), the event will not be processed by the event source peer.
Class Definition public abstract class java.awt.event.InputEvent extends java.awt.event.ComponentEvent { // Constants public final static int ALT_MASK; public final static int BUTTON1_MASK; public final static int BUTTON2_MASK;
http://localhost/java/javaref/awt/ch21_14.htm (1 of 5) [20/12/2001 11:13:44]
[Chapter 21] InputEvent
public final static int BUTTON3_MASK; public final static int CTRL_MASK; public final static int META_MASK; public final static int SHIFT_MASK; // Instance Methods public void consume(); public int getModifiers(); public long getWhen(); public boolean isAltDown(); public boolean isConsumed(); public boolean isControlDown(); public boolean isMetaDown(); public boolean isShiftDown(); }
Constants ALT_MASK public final static int ALT_MASK The ALT key mask. ORed with other masks to form modifiers setting of event.
BUTTON1_MASK public final static int BUTTON1_MASK The mouse button 1 key mask. ORed with other masks to form modifiers setting of event.
BUTTON2_MASK public final static int BUTTON2_MASK The mouse button 2 key mask. ORed with other masks to form modifiers setting of event. This constant is identical to ALT_MASK.
BUTTON3_MASK public final static int BUTTON3_MASK The mouse button 3 key mask. ORed with other masks to form modifiers setting of event. This constant is identical to ALT_MASK.
http://localhost/java/javaref/awt/ch21_14.htm (2 of 5) [20/12/2001 11:13:44]
[Chapter 21] InputEvent
CTRL_MASK public final static int CTRL_MASK The Control key mask. ORed with other masks to form modifiers setting of event.
META_MASK public final static int META_MASK The Meta key mask. ORed with other masks to form modifiers setting of event.
SHIFT_MASK public final static int SHIFT_MASK The Shift key mask. ORed with other masks to form modifiers setting of event.
Instance Methods consume public void consume() Description A consumed event will not be delivered to its source for default processing.
getModifiers public int getModifiers() Returns The modifier flags, a combination of the _MASK constants. Description Use this method to find out what modifier keys were pressed when an input event occurred.
getWhen public long getWhen() Returns The time at which this event occurred.
http://localhost/java/javaref/awt/ch21_14.htm (3 of 5) [20/12/2001 11:13:44]
[Chapter 21] InputEvent
Description The time of the event is returned as the number of milliseconds since the epoch (00:00:00 UTC, January 1, 1970). Conveniently, java.util.Date has a constructor that accepts such values.
isAltDown public boolean isAltDown() Returns true if the Alt key was pressed; false otherwise.
isConsumed public boolean isConsumed() Returns true if the event has been consumed; false otherwise.
isControlDown public boolean isControlDown() Returns true if the Control key was pressed; false otherwise.
isMetaDown public boolean isMetaDown() Returns true if the Meta key was pressed; false otherwise.
isShiftDown public boolean isShiftDown() Returns true if the Shift key was pressed; false otherwise.
http://localhost/java/javaref/awt/ch21_14.htm (4 of 5) [20/12/2001 11:13:44]
[Chapter 21] InputEvent
See Also ComponentEvent, KeyEvent, MouseEvent
FocusListener
http://localhost/java/javaref/awt/ch21_14.htm (5 of 5) [20/12/2001 11:13:44]
ItemEvent
[Chapter 21] ItemEvent
Chapter 21 java.awt.event Reference
ItemEvent Name ItemEvent
Description ItemEvents are generated by objects that implement the ItemSelectable interface. Choice is one example of such an object.
Class Definition public class java.awt.event.ItemEvent extends java.awt.AWTEvent { // Constants public final static int DESELECTED; public final static int ITEM_FIRST; public final static int ITEM_LAST; public final static int ITEM_STATE_CHANGED; public final static int SELECTED; // Constructors public ItemEvent (ItemSelectable source, int id, Object item, int stateChange); // Instance Methods public Object getItem(); public ItemSelectable getItemSelectable(); public int getStateChange(); public String paramString(); }
http://localhost/java/javaref/awt/ch21_15.htm (1 of 4) [20/12/2001 11:13:47]
[Chapter 21] ItemEvent
Constants DESELECTED public final static int DESELECTED Indicates that an item was deselected.
ITEM_FIRST public final static int ITEM_FIRST Specifies the beginning range of item event ID values.
ITEM_LAST public final static int ITEM_LAST Specifies the ending range of item event ID values.
ITEM_STATE_CHANGED public final static int ITEM_STATE_CHANGED An event type indicating that an item was selected or deselected.
SELECTED public final static int SELECTED Indicates that an item was selected.
Constructors ItemEvent public ItemEvent (ItemSelectable source, int id, Object item, int stateChange) Parameters source The object that generated the event. id The type ID of the event. item The item whose state is changing. stateChange Either SELECTED or DESELECTED. Description http://localhost/java/javaref/awt/ch21_15.htm (2 of 4) [20/12/2001 11:13:47]
[Chapter 21] ItemEvent
Constructs an ItemEvent with the given characteristics.
Instance Methods getItem public Object getItem() Returns The item pertaining to this event. Description Returns the item whose changed state triggered this event.
getItemSelectable public ItemSelectable getItemSelectable() Returns The source of this event. Description Returns an object that implements the ItemSelectable interface.
getStateChange public int getStateChange() Returns The change in state that triggered this event. The new state is returned. Description This method will return SELECTED or DESELECTED.
paramString public String paramString() Returns String with current settings of ItemEvent. Overrides AWTEvent.paramString() Description Helper method for toString() to generate string of current settings.
http://localhost/java/javaref/awt/ch21_15.htm (3 of 4) [20/12/2001 11:13:47]
[Chapter 21] ItemEvent
See Also AWTEvent, ItemSelectable, ItemListener
InputEvent
http://localhost/java/javaref/awt/ch21_15.htm (4 of 4) [20/12/2001 11:13:47]
ItemListener
[Chapter 21] ItemListener
Chapter 21 java.awt.event Reference
ItemListener Name ItemListener
Description Objects that implement the ItemListener interface can receive ItemEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.ItemListener extends java.util.EventListener { // Interface Methods public abstract void itemStateChanged (ItemEvent e); }
http://localhost/java/javaref/awt/ch21_16.htm (1 of 2) [20/12/2001 11:13:50]
[Chapter 21] ItemListener
Interface Methods itemStateChanged public abstract void itemStateChanged (ItemEvent e) Parameters e The item event that occurred. Description Notifies the ItemListener that an event occurred.
See Also AWTEventMulticaster, EventListener, ItemEvent
ItemEvent
http://localhost/java/javaref/awt/ch21_16.htm (2 of 2) [20/12/2001 11:13:50]
KeyAdapter
[Chapter 21] KeyAdapter
Chapter 21 java.awt.event Reference
KeyAdapter Name KeyAdapter
Description The KeyAdapter class implements the methods of KeyListener with empty functions. It may be easier for you to extend KeyAdapter, overriding only those methods you are interested in, than to implement KeyListener and provide the empty functions yourself.
Class Definition public abstract class java.awt.event.KeyAdapter extends java.lang.Object implements java.awt.event.KeyListener { // Instance Methods public void keyPressed (KeyEvent e); public void keyReleased (KeyEvent e); public void keyTyped (KeyEvent e); }
http://localhost/java/javaref/awt/ch21_17.htm (1 of 3) [20/12/2001 11:13:52]
[Chapter 21] KeyAdapter
Instance Methods keyPressed public void keyPressed (KeyEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a key is pressed.
keyReleased public void keyReleased (KeyEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a pressed key is released.
keyTyped public void keyTyped (KeyEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a key has been pressed and released.
See Also KeyEvent, KeyListener
ItemListener
http://localhost/java/javaref/awt/ch21_17.htm (2 of 3) [20/12/2001 11:13:52]
KeyEvent
[Chapter 21] KeyAdapter
http://localhost/java/javaref/awt/ch21_17.htm (3 of 3) [20/12/2001 11:13:52]
[Chapter 21] KeyEvent
Chapter 21 java.awt.event Reference
KeyEvent Name KeyEvent
Description Key events are generated when the user types on the keyboard.
Class Definition public class java.awt.event.KeyEvent extends java.awt.event.InputEvent { // Constants public final static int CHAR_UNDEFINED; public final static int KEY_FIRST; public final static int KEY_LAST; public final static int KEY_PRESSED; public final static int KEY_RELEASED; public final static int KEY_TYPED; public final static int VK_0; public final static int VK_1; public final static int VK_2;
http://localhost/java/javaref/awt/ch21_18.htm (1 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public
final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final
static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static
int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int
VK_3; VK_4; VK_5; VK_6; VK_7; VK_8; VK_9; VK_A; VK_ACCEPT; VK_ADD; VK_ALT; VK_B; VK_BACK_QUOTE; VK_BACK_SLASH; VK_BACK_SPACE; VK_C; VK_CANCEL; VK_CAPS_LOCK; VK_CLEAR; VK_CLOSE_BRACKET; VK_COMMA; VK_CONTROL; VK_CONVERT; VK_D; VK_DECIMAL; VK_DELETE; VK_DIVIDE; VK_DOWN; VK_E; VK_END; VK_ENTER; VK_EQUALS; VK_ESCAPE; VK_F; VK_F1; VK_F2; VK_F3; VK_F4; VK_F5; VK_F6; VK_F7; VK_F8; VK_F9; VK_F10; VK_F11; VK_F12;
http://localhost/java/javaref/awt/ch21_18.htm (2 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public
final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final final
static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static static
int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int int
VK_FINAL; VK_G; VK_H; VK_HELP; VK_HOME; VK_I; VK_INSERT; VK_J; VK_K; VK_KANA; VK_KANJI; VK_L; VK_LEFT; VK_M; VK_META; VK_MODECHANGE; VK_MULTIPLY; VK_N; VK_NONCONVERT; VK_NUM_LOCK; VK_NUMPAD0; VK_NUMPAD1; VK_NUMPAD2; VK_NUMPAD3; VK_NUMPAD4; VK_NUMPAD5; VK_NUMPAD6; VK_NUMPAD7; VK_NUMPAD8; VK_NUMPAD9; VK_O; VK_OPEN_BRACKET; VK_P; VK_PAGE_DOWN; VK_PAGE_UP; VK_PAUSE; VK_PERIOD; VK_PRINTSCREEN; VK_Q; VK_QUOTE; VK_R; VK_RIGHT; VK_S; VK_SCROLL_LOCK; VK_SEMICOLON; VK_SEPARATER;
http://localhost/java/javaref/awt/ch21_18.htm (3 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
public final static int VK_SHIFT; public final static int VK_SLASH; public final static int VK_SPACE; public final static int VK_SUBTRACT; public final static int VK_T; public final static int VK_TAB; public final static int VK_U; public final static int VK_UNDEFINED; public final static int VK_UP; public final static int VK_V; public final static int VK_W; public final static int VK_X; public final static int VK_Y; public final static int VK_Z; // Constructors public KeyEvent (Component source, int id, long when, int modifiers, int keyCode, char keyChar); // Class Methods public static String getKeyModifiersText(int modifiers); public static String getKeyText(int keyCode); // Instance Methods public char getKeyChar(); public int getKeyCode(); public boolean isActionKey(); public String paramString(); public void setKeyChar (char keyChar); public void setKeyCode (int keyCode); public void setModifiers (int modifiers); }
Constants CHAR_UNDEFINED public final static int CHAR_UNDEFINED This constant is used for key presses have that no associated character.
KEY_FIRST public final static int KEY_FIRST Specifies the beginning range of key event ID values.
http://localhost/java/javaref/awt/ch21_18.htm (4 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
KEY_LAST public final static int KEY_LAST Specifies the ending range of key event ID values.
KEY_PRESSED public final static int KEY_PRESSED An event ID type for a key press.
KEY_RELEASED public final static int KEY_RELEASED An event ID type for a key release.
KEY_TYPED public final static int KEY_TYPED An event ID type for a typed key (a press and a release).
VK_0 public final static int VK_0 The 0 key.
VK_1 public final static int VK_1 The 1 key.
VK_2 public final static int VK_2 The 2 key.
http://localhost/java/javaref/awt/ch21_18.htm (5 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_3 public final static int VK_3 The 3 key.
VK_4 public final static int VK_4 The 4 key.
VK_5 public final static int VK_5 The 5 key.
VK_6 public final static int VK_6 The 6 key.
VK_7 public final static int VK_7 The 7 key.
VK_8 public final static int VK_8 The 8 key.
VK_9 public final static int VK_9 The 9 key.
http://localhost/java/javaref/awt/ch21_18.htm (6 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_A public final static int VK_A The `a' key.
VK_ACCEPT public final static int VK_ACCEPT This constant is used for Asian keyboards.
VK_ADD public final static int VK_ADD The plus (+) key on the numeric keypad.
VK_ALT public final static int VK_ALT The Alt key.
VK_B public final static int VK_B The `b' key.
VK_BACK_QUOTE public final static int VK_BACK_QUOTE The backquote (`) key.
VK_BACK_SLASH public final static int VK_BACK_SLASH The backslash key.
http://localhost/java/javaref/awt/ch21_18.htm (7 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_BACK_SPACE public final static int VK_BACK_SPACE The Backspace key.
VK_C public final static int VK_C The `c' key.
VK_CANCEL public final static int VK_CANCEL The Cancel key.
VK_CAPS_LOCK public final static int VK_CAPS_LOCK The Caps Lock key.
VK_CLEAR public final static int VK_CLEAR The Clear key.
VK_CLOSE_BRACKET public final static int VK_CLOSE_BRACKET The close bracket `]' key.
VK_COMMA public final static int VK_COMMA The comma (,) key.
http://localhost/java/javaref/awt/ch21_18.htm (8 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_CONTROL public final static int VK_CONTROL The Control key.
VK_CONVERT public final static int VK_CONVERT This constant is used for Asian keyboards.
VK_D public final static int VK_D The `d' key.
VK_DECIMAL public final static int VK_DECIMAL The decimal (.) key on the numeric keypad.
VK_DELETE public final static int VK_DELETE The Delete key.
VK_DIVIDE public final static int VK_DIVIDE The divide (/) key on the numeric keypad.
VK_DOWN public final static int VK_DOWN The Down arrow key.
http://localhost/java/javaref/awt/ch21_18.htm (9 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_E public final static int VK_E The `e' key.
VK_END public final static int VK_END The End key.
VK_ENTER public final static int VK_ENTER The Enter key.
VK_EQUALS public final static int VK_ EQUALS The equals (=) key.
VK_ESCAPE public final static int VK_ESCAPE The Escape key.
VK_F public final static int VK_F The `f' key.
VK_F1 public final static int VK_F1 The F1 key.
http://localhost/java/javaref/awt/ch21_18.htm (10 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_F2 public final static int VK_F2 The F2 key.
VK_F3 public final static int VK_F3 The F3 key.
VK_F4 public final static int VK_F4 The F4 key.
VK_F5 public final static int VK_F5 The F5 key.
VK_F6 public final static int VK_F6 The F6 key.
VK_F7 public final static int VK_F7 The F7 key.
VK_F8 public final static int VK_F8 The F8 key.
http://localhost/java/javaref/awt/ch21_18.htm (11 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_F9 public final static int VK_F9 The F9 key.
VK_F10 public final static int VK_F10 The F10 key.
VK_F11 public final static int VK_F11 The F11 key.
VK_F12 public final static int VK_F12 The F12 key.
VK_FINAL public final static int VK_FINAL This constant is used for Asian keyboards.
VK_G public final static int VK_G The `g' key.
VK_H public final static int VK_H The `h' key.
http://localhost/java/javaref/awt/ch21_18.htm (12 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_HELP public final static int VK_HELP The Help key.
VK_HOME public final static int VK_HOME The Home key.
VK_I public final static int VK_I The `i' key.
VK_INSERT public final static int VK_INSERT The Insert key.
VK_J public final static int VK_J The `j' key.
VK_K public final static int VK_K The `k' key.
VK_KANA public final static int VK_KANA This constant is used for Asian keyboards.
http://localhost/java/javaref/awt/ch21_18.htm (13 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_KANJI public final static int VK_KANJI This constant is used for Asian keyboards.
VK_L public final static int VK_L The `l' key.
VK_LEFT public final static int VK_LEFT The Left arrow key.
VK_M public final static int VK_M The `m' key.
VK_MODECHANGE public final static int VK_MODECHANGE This constant is used for Asian keyboards.
VK_META public final static int VK_META The Meta key.
VK_MULTIPLY public final static int VK_MULTIPLY The * key on the numeric keypad.
http://localhost/java/javaref/awt/ch21_18.htm (14 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_N public final static int VK_N The `n' key.
VK_NONCONVERT public final static int VK_NONCONVERT This constant is used for Asian keyboards.
VK_NUM_LOCK public final static int VK_NUM_LOCK The Num Lock key.
VK_NUMPAD0 public final static int VK_NUMPAD0 The 0 key on the numeric keypad.
VK_NUMPAD1 public final static int VK_NUMPAD1 The 1 key on the numeric keypad.
VK_NUMPAD2 public final static int VK_NUMPAD2 The 2 key on the numeric keypad.
VK_NUMPAD3 public final static int VK_NUMPAD3 The 3 key on the numeric keypad.
http://localhost/java/javaref/awt/ch21_18.htm (15 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_NUMPAD4 public final static int VK_NUMPAD4 The 4 key on the numeric keypad.
VK_NUMPAD5 public final static int VK_NUMPAD5 The 5 key on the numeric keypad.
VK_NUMPAD6 public final static int VK_NUMPAD6 The 6 key on the numeric keypad.
VK_NUMPAD7 public final static int VK_NUMPAD7 The 7 key on the numeric keypad.
VK_NUMPAD8 public final static int VK_NUMPAD8 The 8 key on the numeric keypad.
VK_NUMPAD9 public final static int VK_NUMPAD9 The 9 key on the numeric keypad.
VK_O public final static int VK_O The `o' key.
http://localhost/java/javaref/awt/ch21_18.htm (16 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_OPEN_BRACKET public final static int VK_OPEN_BRACKET The open bracket `[` key.
VK_P public final static int VK_P The `p' key.
VK_PAGE_DOWN public final static int VK_PAGE_DOWN The Page Down key.
VK_PAGE_UP public final static int VK_PAGE_UP The Page Up key.
VK_PAUSE public final static int VK_PAUSE The Pause key.
VK_PERIOD public final static int VK_PERIOD The period (.) key.
VK_PRINTSCREEN public final static int VK_PRINTSCREEN The Print Screen key.
http://localhost/java/javaref/awt/ch21_18.htm (17 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_Q public final static int VK_Q The `q' key.
VK_QUOTE public final static int VK_QUOTE The quotation mark (") key.
VK_R public final static int VK_R The `r' key.
VK_RIGHT public final static int VK_RIGHT The Right arrow key.
VK_S public final static int VK_S The `s' key.
VK_SCROLL_LOCK public final static int VK_SCROLL_LOCK The Scroll Lock key.
VK_SEMICOLON public final static int VK_SEMICOLON The semicolon (;) key.
http://localhost/java/javaref/awt/ch21_18.htm (18 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_SEPARATER public final static int VK_SEPARATER The numeric separator key on the numeric keypad (i.e., the locale-dependent key used to separate groups of digits). A misspelling of VK_SEPARATOR.
VK_SHIFT public final static int VK_SHIFT The Shift key.
VK_SLASH public final static int VK_SLASH The slash (/) key.
VK_SPACE public final static int VK_SPACE The space key.
VK_SUBTRACT public final static int VK_SUBTRACT The subtract (-) key on the numeric keypad.
VK_T public final static int VK_T The `t' key.
VK_TAB public final static int VK_TAB The Tab key.
http://localhost/java/javaref/awt/ch21_18.htm (19 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_U public final static int VK_U The `u' key.
VK_UNDEFINED public final static int VK_UNDEFINED An undefined key.
VK_UP public final static int VK_UP The Up arrow key.
VK_V public final static int VK_V The `v' key.
VK_W public final static int VK_W The `w' key.
VK_X public final static int VK_X The `x' key.
VK_Y public final static int VK_Y The `y' key.
http://localhost/java/javaref/awt/ch21_18.htm (20 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
VK_Z public final static int VK_Z The `z' key.
Constructors KeyEvent public KeyEvent (Component source, int id, long when, int modifiers, int keyCode, char keyChar) Parameters source The object that generated the event. id The event type ID of the event. when When the event occurred, in milliseconds from the epoch. modifiers What modifier keys were pressed with this key. keyCode The code of the key. keyChar The character for this key. Description Constructs a KeyEvent with the given characteristics.
Class Methods getKeyModifiersText public static String getKeyModifiersText(int modifiers) Parameters modifiers
http://localhost/java/javaref/awt/ch21_18.htm (21 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
One or more modifier keys. Returns A string describing the modifiers.
getKeyText public static String getKeyText(int keyCode) Parameters keyCode One of the key codes. Returns A string describing the given key.
Instance Methods getKeyChar public char getKeyChar() Returns The character corresponding to this event. KEY_TYPED events have characters.
getKeyCode public int getKeyCode() Returns The integer key code corresponding to this event. This will be one of the constants defined above. KEY_PRESSED and KEY_RELEASED events have codes. Key codes are virtual keys, not actual. Pressing the `a' key is identical to `A', but has different modifiers. Same for `/' and `?' on a standard keyboard.
isActionKey public boolean isActionKey() Returns true if this event is for one of the action keys; false otherwise. Description
http://localhost/java/javaref/awt/ch21_18.htm (22 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
In general, an action key is a key that causes an action but has no printing equivalent. The action keys are the function keys, the arrow keys, Caps Lock, End, Home, Insert, Num Lock, Pause, Page Down, Page Up, Print Screen, and Scroll Lock. They do not generate a KEY_TYPED event, only KEY_PRESSED and KEY_RELEASED.
paramString public String paramString() Returns A string with current settings of the KeyEvent. Overrides ComponentEvent.paramString() Description Helper method for toString() to generate string of current settings.
setKeyChar public void setKeyChar(char keyChar) Parameters keyChar The new key character. Description Sets the character code of this KeyEvent.
setKeyCode public void setKeyCode (int keyCode) Parameters keyCode The new key code. Description Sets the key code of this KeyEvent.
http://localhost/java/javaref/awt/ch21_18.htm (23 of 24) [20/12/2001 11:13:59]
[Chapter 21] KeyEvent
setModifiers public void setModifiers (int modifiers) Parameters modifiers The new modifiers. Description This is a combination of the mask constants defined in java.awt.event.InputEvent.
See Also Component, ComponentEvent, InputEvent, KeyAdapter, KeyListener
KeyAdapter
http://localhost/java/javaref/awt/ch21_18.htm (24 of 24) [20/12/2001 11:13:59]
KeyListener
[Chapter 21] KeyListener
Chapter 21 java.awt.event Reference
KeyListener Name KeyListener
Description Objects that implement the KeyListener interface can receive KeyEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.KeyListener extends java.util.EventListener { // Instance Methods public abstract void keyPressed (KeyEvent e); public abstract void keyReleased (KeyEvent e); public abstract void keyTyped (KeyEvent e); }
http://localhost/java/javaref/awt/ch21_19.htm (1 of 3) [20/12/2001 11:14:01]
[Chapter 21] KeyListener
Interface Methods keyPressed public abstract void keyPressed (KeyEvent e) Parameters e The key event that occurred. Description Notifies the KeyListener that a key was pressed.
keyReleased public abstract void keyReleased (KeyEvent e) Parameters e The key event that occurred. Description Notifies the KeyListener that a key was released.
keyTyped public abstract void keyTyped (KeyEvent e) Parameters e The key event that occurred. Description Notifies the KeyListener that a key was typed (pressed and released).
See Also AWTEventMulticaster, EventListener, KeyEvent, KeyListener
KeyEvent
http://localhost/java/javaref/awt/ch21_19.htm (2 of 3) [20/12/2001 11:14:01]
MouseAdapter
[Chapter 21] KeyListener
http://localhost/java/javaref/awt/ch21_19.htm (3 of 3) [20/12/2001 11:14:01]
[Chapter 21] MouseAdapter
Chapter 21 java.awt.event Reference
MouseAdapter Name MouseAdapter
Description The MouseAdapter class implements the methods of MouseListener with empty functions. It may be easier for you to extend MouseAdapter, overriding only those methods you are interested in, than to implement MouseListener and provide the empty functions yourself.
Class Definition public abstract class java.awt.event.MouseAdapter extends java.lang.Object implements java.awt.event.MouseListener { // Instance Methods public void mouseClicked (MouseEvent e); public void mouseEntered (MouseEvent e); public void mouseExited (MouseEvent e); public void mousePressed (MouseEvent e); public void mouseReleased (MouseEvent e); }
http://localhost/java/javaref/awt/ch21_20.htm (1 of 3) [20/12/2001 11:14:03]
[Chapter 21] MouseAdapter
Instance Methods mouseClicked public void mouseClicked (MouseEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when the mouse button is clicked (pressed and released).
mouseEntered public void mouseEntered (MouseEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when the user moves the mouse cursor into a component.
mouseExited public void mouseExited (MouseEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when the moves the mouse cursor out of a component.
mousePressed public void mousePressed (MouseEvent e) Parameters http://localhost/java/javaref/awt/ch21_20.htm (2 of 3) [20/12/2001 11:14:03]
[Chapter 21] MouseAdapter
e The event that has occurred. Description Does nothing. Override this function to be notified when the mouse button is pressed.
mouseReleased public void mouseReleased (MouseEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when the mouse button is released.
See Also MouseEvent, MouseListener
KeyListener
http://localhost/java/javaref/awt/ch21_20.htm (3 of 3) [20/12/2001 11:14:03]
MouseEvent
[Chapter 21] MouseEvent
Chapter 21 java.awt.event Reference
MouseEvent Name MouseEvent
Description Mouse events are generated when the user moves and clicks the mouse.
Class Definition public class java.awt.event.MouseEvent extends java.awt.event.InputEvent { // Constants public final static int MOUSE_CLICKED; public final static int MOUSE_DRAGGED; public final static int MOUSE_ENTERED; public final static int MOUSE_EXITED; public final static int MOUSE_FIRST; public final static int MOUSE_LAST; public final static int MOUSE_MOVED; public final static int MOUSE_PRESSED; public final static int MOUSE_RELEASED; // Constructors public MouseEvent (Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger); // Instance Methods public int getClickCount(); public synchronized Point getPoint(); http://localhost/java/javaref/awt/ch21_21.htm (1 of 5) [20/12/2001 11:14:07]
[Chapter 21] MouseEvent
public public public public public
int getX(); int getY(); boolean isPopupTrigger(); String paramString(); synchronized void translatePoint (int x, int y);
}
Constants MOUSE_CLICKED public final static int MOUSE_CLICKED An event type ID indicating a mouse click.
MOUSE_DRAGGED public final static int MOUSE_DRAGGED An event type ID indicating a mouse move with the button held down.
MOUSE_ENTERED public final static int MOUSE_ENTERED An event type ID indicating that a mouse entered a component.
MOUSE_EXITED public final static int MOUSE_EXITED An event type ID indicating that a mouse left a component.
MOUSE_FIRST public final static int MOUSE_FIRST Specifies the beginning range of mouse event ID values.
MOUSE_LAST public final static int MOUSE_LAST Specifies the ending range of mouse event ID values.
MOUSE_MOVED public final static int MOUSE_MOVED An event type ID indicating a mouse move.
http://localhost/java/javaref/awt/ch21_21.htm (2 of 5) [20/12/2001 11:14:07]
[Chapter 21] MouseEvent
MOUSE_PRESSED public final static int MOUSE_PRESSED An event type ID indicating a mouse button press.
MOUSE_RELEASED public final static int MOUSE_RELEASED An event type ID indicating a mouse button release.
Constructors MouseEvent public MouseEvent (Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger) Parameters source The object that generated the event. id The event type ID of the event. when When the event occurred, in milliseconds from the epoch. modifiers What modifier keys were pressed with this key. x The horizontal location of the event. y The vertical location of the event. clickCount The number of times the mouse button has been clicked. popupTrigger A flag indicating if this event is a popup trigger event. Description Constructs a MouseEvent with the given characteristics.
http://localhost/java/javaref/awt/ch21_21.htm (3 of 5) [20/12/2001 11:14:07]
[Chapter 21] MouseEvent
Instance Methods getClickCount public int getClickCount() Returns The number of consecutive mouse button clicks for this event.
getPoint public synchronized Point getPoint() Returns The location where the event happened.
getX public int getX() Returns The horizontal location where the event happened.
getY public int getY() Returns The vertical location where the event happened.
isPopupTrigger public boolean isPopupTrigger() Returns Returns true if this event is the popup menu event for the run-time system.
paramString public String paramString() Returns String with current settings of the MouseEvent. Overrides ComponentEvent.paramString() Description
http://localhost/java/javaref/awt/ch21_21.htm (4 of 5) [20/12/2001 11:14:07]
[Chapter 21] MouseEvent
Helper method for toString() to generate string of current settings.
translatePoint public synchronized void translatePoint (int x, int y) Parameters x The horizontal amount of translation. y The vertical amount of translation. Description Translates the location of the event by the given amounts.
See Also Component, ComponentEvent, InputEvent, MouseAdapter, MouseListener, Point
MouseAdapter
http://localhost/java/javaref/awt/ch21_21.htm (5 of 5) [20/12/2001 11:14:07]
MouseListener
[Chapter 21] MouseListener
Chapter 21 java.awt.event Reference
MouseListener Name MouseListener
Description Objects that implement the MouseListener interface can receive non-motion oriented MouseEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.MouseListener extends java.util.EventListener { // Instance Methods public abstract void mouseClicked (MouseEvent e); public abstract void mouseEntered (MouseEvent e); public abstract void mouseExited (MouseEvent e); public abstract void mousePressed (MouseEvent e); public abstract void mouseReleased (MouseEvent e); } http://localhost/java/javaref/awt/ch21_22.htm (1 of 3) [20/12/2001 11:14:09]
[Chapter 21] MouseListener
Interface Methods mouseClicked public abstract void mouseClicked (MouseEvent e) Parameters e The key event that occurred. Description Notifies the MouseListener that the mouse button was clicked (pressed and released).
mouseEntered public abstract void mouseEntered (MouseEvent e) Parameters e The key event that occurred. Description Notifies the MouseListener that the mouse cursor has been moved into a component's coordinate space.
mouseExited public abstract void mouseExited (MouseEvent e) Parameters e The key event that occurred. Description Notifies the MouseListener that the mouse cursor has been moved out of a component's coordinate space.
mousePressed public abstract void mousePressed (MouseEvent e) Parameters
http://localhost/java/javaref/awt/ch21_22.htm (2 of 3) [20/12/2001 11:14:09]
[Chapter 21] MouseListener
e The key event that occurred. Description Notifies the MouseListener that the mouse button was pressed.
mouseReleased public abstract void mouseReleased (MouseEvent e) Parameters e The key event that occurred. Description Notifies the MouseListener that the mouse button was released.
See Also EventListener, MouseAdapter, MouseEvent
MouseEvent
http://localhost/java/javaref/awt/ch21_22.htm (3 of 3) [20/12/2001 11:14:09]
MouseMotionAdapter
[Chapter 21] MouseMotionAdapter
Chapter 21 java.awt.event Reference
MouseMotionAdapter Name MouseMotionAdapter
Description The MouseMotionAdapter class implements the methods of MouseMotionListener with empty functions. It may be easier for you to extend MouseMotionAdapter, overriding only those methods you are interested in, than to implement MouseMotionListener and provide the empty functions yourself.
Class Definition public abstract class java.awt.event.MouseMotionAdapter extends java.lang.Object implements java.awt.event.MouseMotionListener { // Instance Methods public void mouseDragged (MouseEvent e); public void mouseMoved (MouseEvent e); }
http://localhost/java/javaref/awt/ch21_23.htm (1 of 2) [20/12/2001 11:14:10]
[Chapter 21] MouseMotionAdapter
Instance Methods mouseDragged public void mouseDragged (MouseEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when the mouse is dragged.
mouseMoved public void mouseEntered (MouseEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when the mouse moves.
See Also MouseEvent, MouseMotionListener
MouseListener
http://localhost/java/javaref/awt/ch21_23.htm (2 of 2) [20/12/2001 11:14:10]
MouseMotionListener
[Chapter 21] MouseMotionListener
Chapter 21 java.awt.event Reference
MouseMotionListener Name MouseMotionListener
Description Objects that implement the MouseMotionListener interface can receive motion-oriented MouseEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.MouseMotionListener extends java.util.EventListener { // Instance Methods public abstract void mouseDragged (MouseEvent e); public abstract void mouseMoved (MouseEvent e); }
http://localhost/java/javaref/awt/ch21_24.htm (1 of 2) [20/12/2001 11:14:12]
[Chapter 21] MouseMotionListener
Interface Methods mouseDragged public abstract void mouseDragged (MouseEvent e) Parameters e The key event that occurred. Description Notifies the MouseMotionListener that the mouse has been dragged.
mouseMoved public abstract void mouseMoved (MouseEvent e) Parameters e The key event that occurred. Description Notifies the MouseMotionListener that the mouse has been moved.
See Also AWTEventMulticaster, EventListener, MouseEvent, MouseMotionAdapter
MouseMotionAdapter
http://localhost/java/javaref/awt/ch21_24.htm (2 of 2) [20/12/2001 11:14:12]
PaintEvent
[Chapter 21] PaintEvent
Chapter 21 java.awt.event Reference
PaintEvent Name PaintEvent
Description The PaintEvent class represents the paint and update operations that the AWT performs on components. There is no PaintListener interface, so the only way to catch these events is to override paint(Graphics) and update(Graphics) in Component. This class exists so that paint events will get serialized properly.
Class Definition public class java.awt.event.PaintEvent extends java.awt.event.ComponentEvent { // Constants public final static int PAINT; public final static int PAINT_FIRST; public final static int PAINT_LAST; public final static int UPDATE; // Constructor public PaintEvent (Component source, int id, Rectangle updateRect);
http://localhost/java/javaref/awt/ch21_25.htm (1 of 4) [20/12/2001 11:14:13]
[Chapter 21] PaintEvent
// Instance Methods public Rectangle getUpdateRect(); public String paramString(); public void setUpdateRect (Rectangle updateRect); }
Class Definition public class java.awt.event.PaintEvent extends java.awt.event.ComponentEvent { // Constants public final static int PAINT; public final static int PAINT_FIRST; public final static int PAINT_LAST; public final static int UPDATE; //Constructor public PaintEvent (Component source, int id, Rectangle updateRect); // Instance Methods public Rectangle getUpdateRect(); public String paramString(); public void setUpdateRect (Rectangle updateRect); }
Constants PAINT public final static int PAINT The paint event type.
PAINT_FIRST public final static int PAINT_FIRST Specifies the beginning range of paint event ID values.
PAINT_LAST public final static int PAINT_LAST Specifies the ending range of paint event ID values.
http://localhost/java/javaref/awt/ch21_25.htm (2 of 4) [20/12/2001 11:14:13]
[Chapter 21] PaintEvent
UPDATE public final static int UPDATE The update event type.
Constructor PaintEvent public PaintEvent (Component source, ind id, Rectangle updateRect) Parameters source The source of the event. id The event type ID. g The rectangular area to paint. Description Constructs a PaintEvent with the given characteristics.
Instance Methods getUpdateRect public Rectangle getUpdateRect() Returns The rectangular area that needs painting.
paramString public String paramString() Returns String with current settings of the PaintEvent. Overrides ComponentEvent.paramString() http://localhost/java/javaref/awt/ch21_25.htm (3 of 4) [20/12/2001 11:14:13]
[Chapter 21] PaintEvent
Description Helper method for toString() to generate string of current settings.
setUpdateRect public void setUpdateRect (Rectangle updateRect) Parameters updateRect The rectangular area to paint. Description Changes the rectangular area that this PaintEvent will paint.
See Also Component, ComponentEvent, Graphics
MouseMotionListener
http://localhost/java/javaref/awt/ch21_25.htm (4 of 4) [20/12/2001 11:14:13]
TextEvent
[Chapter 21] TextEvent
Chapter 21 java.awt.event Reference
TextEvent Name TextEvent
Description Text events are generated by text components when their contents change, either programmatically or by a user typing.
Class Definition public class java.awt.event.TextEvent extends java.awt.AWTEvent { // Constants public final static int TEXT_FIRST; public final static int TEXT_LAST; public final static int TEXT_VALUE_CHANGED; // Constructors public TextEvent (Object source, int id); // Instance Methods public String paramString(); }
http://localhost/java/javaref/awt/ch21_26.htm (1 of 3) [20/12/2001 11:14:17]
[Chapter 21] TextEvent
Constants TEXT_FIRST public final static int TEXT_FIRST Specifies the beginning range of text event ID values.
TEXT_LAST public final static int TEXT_LAST Specifies the ending range of text event ID values.
TEXT_VALUE_CHANGED public final static int TEXT_VALUE_CHANGED The only text event type; it indicates that the contents of something have changed.
Constructors TextEvent public TextEvent (Object source, int id) Parameters source The object that generated the event. id The type ID of the event. Description Constructs a TextEvent with the given characteristics.
Instance Methods paramString public String paramString() Returns
http://localhost/java/javaref/awt/ch21_26.htm (2 of 3) [20/12/2001 11:14:17]
[Chapter 21] TextEvent
String with current settings of the TextEvent. Overrides AWTEvent.paramString() Description Helper method for toString() to generate string of current settings.
See Also AWTEvent, TextListener
PaintEvent
http://localhost/java/javaref/awt/ch21_26.htm (3 of 3) [20/12/2001 11:14:17]
TextListener
[Chapter 21] TextListener
Chapter 21 java.awt.event Reference
TextListener Name TextListener
Description Objects that implement the TextListener interface can receive TextEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.TextListener extends java.util.EventListener { // Interface Methods public abstract void textValueChanged (TextEvent e); }
http://localhost/java/javaref/awt/ch21_27.htm (1 of 2) [20/12/2001 11:14:18]
[Chapter 21] TextListener
Interface Methods textValueChanged public abstract void textValueChanged (TextEvent e) Parameters e The text event that occurred. Description Notifies the TextListener that an event occurred.
See Also AWTEventMulticaster, EventListener, TextEvent
TextEvent
http://localhost/java/javaref/awt/ch21_27.htm (2 of 2) [20/12/2001 11:14:18]
WindowAdapter
[Chapter 21] WindowAdapter
Chapter 21 java.awt.event Reference
WindowAdapter Name WindowAdapter
Description The WindowAdapter class implements the methods of WindowListener with empty functions. It may be easier for you to extend WindowAdapter, overriding only those methods you are interested in, than to implement WindowListener and provide the empty functions yourself.
Class Definition public abstract class java.awt.event.WindowAdapter extends java.lang.Object implements java.awt.event.WindowListener { // Instance Methods public void windowActivated (WindowEvent e); public void windowClosed (WindowEvent e); public void windowClosing (WindowEvent e); public void windowDeactivated (WindowEvent e); public void windowDeiconified (WindowEvent e); public void windowIconified (WindowEvent e); public void windowOpened (WindowEvent e); }
http://localhost/java/javaref/awt/ch21_28.htm (1 of 4) [20/12/2001 11:14:20]
[Chapter 21] WindowAdapter
Instance Methods windowActivated public void windowActivated (WindowEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a window is activated.
windowClosed public void windowClosed (WindowEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a window is closed.
windowClosing public void windowClosing (WindowEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a window is in the process of closing.
windowDeactivated public void windowDeactivated (WindowEvent e) Parameters e The event that has occurred.
http://localhost/java/javaref/awt/ch21_28.htm (2 of 4) [20/12/2001 11:14:20]
[Chapter 21] WindowAdapter
Description Does nothing. Override this function to be notified when a window is deactivated.
windowDeiconified public void windowDeiconified (WindowEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when an iconified window is restored.
windowIconified public void windowIconified (WindowEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a window is iconified (minimized).
windowOpened public void windowOpened (WindowEvent e) Parameters e The event that has occurred. Description Does nothing. Override this function to be notified when a window is opened.
See Also WindowEvent, WindowListener
http://localhost/java/javaref/awt/ch21_28.htm (3 of 4) [20/12/2001 11:14:20]
[Chapter 21] WindowAdapter
TextListener
http://localhost/java/javaref/awt/ch21_28.htm (4 of 4) [20/12/2001 11:14:20]
WindowEvent
[Chapter 21] WindowEvent
Chapter 21 java.awt.event Reference
WindowEvent Name WindowEvent
Description Window events are generated when a window is opened, closed, iconified, or deiconified.
Class Definition public class java.awt.event.WindowEvent extends java.awt.event.ComponentEvent { // Constants public final static int WINDOW_ACTIVATED; public final static int WINDOW_CLOSED; public final static int WINDOW_CLOSING; public final static int WINDOW_DEACTIVATED; public final static int WINDOW_DEICONIFIED; public final static int WINDOW_FIRST; public final static int WINDOW_ICONIFIED; public final static int WINDOW_LAST; public final static int WINDOW_OPENED;
http://localhost/java/javaref/awt/ch21_29.htm (1 of 4) [20/12/2001 11:14:24]
[Chapter 21] WindowEvent
// Constructors public WindowEvent (Window source, int id); // Instance Methods public Window getWindow(); public String paramString(); }
Constants WINDOW_ACTIVATED public final static int WINDOW_ACTIVATED Event type ID indicating the window has been activated, brought to the foreground.
WINDOW_CLOSED public final static int WINDOW_CLOSED Event type ID indicating the window has closed.
WINDOW_CLOSING public final static int WINDOW_CLOSING Event type ID indicating the window is closing.
WINDOW_DEACTIVATED public final static int WINDOW_DEACTIVATED Event type ID indicating the window has been deactivated, placed in the background.
WINDOW_DEICONIFIED public final static int WINDOW_DEICONIFIED Event type ID indicating the window has been restored from an iconified state.
WINDOW_FIRST public final static int WINDOW_FIRST Specifies the beginning range of window event ID values.
http://localhost/java/javaref/awt/ch21_29.htm (2 of 4) [20/12/2001 11:14:24]
[Chapter 21] WindowEvent
WINDOW_ICONIFIED public final static int WINDOW_ICONIFIED Event type ID indicating the window has been iconified (minimized).
WINDOW_LAST public final static int WINDOW_LAST Specifies the ending range of window event ID values.
WINDOW_OPENED public final static int WINDOW_OPENED Event type ID indicating the window has opened.
Constructors WindowEvent public WindowEvent (Window source, int id) Parameters source The object that generated the event. id The event type ID of the event. Description Constructs a WindowEvent with the given characteristics.
Instance Methods getWindow public Window getWindow() Returns The window that generated this event.
http://localhost/java/javaref/awt/ch21_29.htm (3 of 4) [20/12/2001 11:14:24]
[Chapter 21] WindowEvent
paramString public String paramString() Returns String with current settings of the WindowEvent. Overrides ComponentEvent.paramString() Description Helper method for toString() to generate string of current settings.
See Also ComponentEvent, Window, WindowAdapter, WindowListener
WindowAdapter
http://localhost/java/javaref/awt/ch21_29.htm (4 of 4) [20/12/2001 11:14:24]
WindowListener
[Chapter 21] WindowListener
Chapter 21 java.awt.event Reference
WindowListener Name WindowListener
Description Objects that implement the WindowListener interface can receive WindowEvent objects. Listeners must first register themselves with objects that produce events. When events occur, they are then automatically propagated to all registered listeners.
Interface Definition public abstract interface java.awt.event.WindowListener extends java.util.EventListener { // Instance Methods public abstract void windowActivated (WindowEvent e); public abstract void windowClosed (WindowEvent e); public abstract void windowClosing (WindowEvent e); public abstract void windowDeactivated (WindowEvent e); public abstract void windowDeiconified (WindowEvent e); public abstract void windowIconified (WindowEvent e); http://localhost/java/javaref/awt/ch21_30.htm (1 of 4) [20/12/2001 11:14:27]
[Chapter 21] WindowListener
public abstract void windowOpened (WindowEvent e); }
Interface Methods windowActivated public abstract void windowActivated (WindowEvent e) Parameters e The event that occurred. Description Notifies the WindowListener that a window has been activated.
windowClosed public abstract void windowClosed (WindowEvent e) Parameters e The event that occurred. Description Notifies the WindowListener that a window has closed.
windowClosing public abstract void windowClosing (WindowEvent e) Parameters e The event that occurred. Description Notifies the WindowListener that a window is closing.
windowDeactivated public abstract void windowDeactivated (WindowEvent e) Parameters http://localhost/java/javaref/awt/ch21_30.htm (2 of 4) [20/12/2001 11:14:27]
[Chapter 21] WindowListener
e The event that occurred. Description Notifies the WindowListener that a window has been deactivated.
windowDeiconified public abstract void windowDeiconified (WindowEvent e) Parameters e The event that occurred. Description Notifies the WindowListener that a window has been restored from an iconified state.
windowIconified public abstract void windowIconified (WindowEvent e) Parameters e The event that occurred. Description Notifies the WindowListener that a window has iconified (minimized).
windowOpened public abstract void windowOpened (WindowEvent e) Parameters e The event that occurred. Description Notifies the WindowListener that a window has opened.
http://localhost/java/javaref/awt/ch21_30.htm (3 of 4) [20/12/2001 11:14:27]
[Chapter 21] WindowListener
See Also AWTEventMulticaster, EventListener, Window, WindowAdapter, WindowEvent
WindowEvent
http://localhost/java/javaref/awt/ch21_30.htm (4 of 4) [20/12/2001 11:14:27]
java.awt.image Reference
[Chapter 22] ColorModel
Chapter 22 java.awt.image Reference
ColorModel Name ColorModel
Description The abstract ColorModel class defines the way a Java program represents colors. It provides methods for extracting different color components from a pixel.
Class Definition public class java.awt.image.ColorModel extends java.lang.Object { // Variables protected int pixel_bits; // Constructors public ColorModel (int bits); // Class Methods public static ColorModel getRGBdefault(); // Instance Methods public void finalize(); http://localhost/java/javaref/awt/ch22_02.htm (1 of 4) [20/12/2001 11:14:29]
[Chapter 22] ColorModel
public public public public public public
abstract int getAlpha (int pixel); abstract int getBlue (int pixel); abstract int getGreen (int pixel); int getPixelSize(); abstract int getRed (int pixel); int getRGB (int pixel);
}
ProtectedVariables pixel_bits protected int pixel_bits The pixel_bits variable saves the ColorModel's bits setting (the total number of bits per pixel).
Constructors ColorModel public ColorModel (int bits) Parameters bits The number of bits required per pixel using this model. Description Constructs a ColorModel object.
Class Methods getRGBdefault public static ColorModel getRGBdefault() Returns The default ColorModel format, which uses 8 bits for each of a pixel's color components: alpha (transparency), red, green, and blue.
http://localhost/java/javaref/awt/ch22_02.htm (2 of 4) [20/12/2001 11:14:29]
[Chapter 22] ColorModel
Instance Methods finalize public void finalize() Overrides Object.finalize() Description Cleans up when this object is garbage collected.
getAlpha public abstract int getAlpha (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current alpha setting of the pixel.
getBlue public abstract int getBlue (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current blue setting of the pixel.
getGreen public abstract int getGreen (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns http://localhost/java/javaref/awt/ch22_02.htm (3 of 4) [20/12/2001 11:14:29]
[Chapter 22] ColorModel
The current green setting of the pixel.
getPixelSize public int getPixelSize() Returns The current pixel size for the color model.
getRed public abstract int getRed (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current red setting of the pixel.
getRGB public int getRGB (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current combined red, green, and blue settings of the pixel. Description Gets the color of pixel in the default RGB color model.
See Also DirectColorModel, IndexColorModel, Object
AreaAveragingScaleFilter
http://localhost/java/javaref/awt/ch22_02.htm (4 of 4) [20/12/2001 11:14:29]
CropImageFilter
[Chapter 22] CropImageFilter
Chapter 22 java.awt.image Reference
CropImageFilter Name CropImageFilter
Description The CropImageFilter class creates a smaller image by cropping (i.e., extracting a rectangular region from) a larger image.
Class Definition public class java.awt.image.CropImageFilter extends java.awt.image.ImageFilter { // Constructors public CropImageFilter (int x, int y, int width, int height); // Instance Methods public void setDimensions (int width, int height); public void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize); public void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize); public void setProperties (Hashtable properties); }
Constructors
http://localhost/java/javaref/awt/ch22_03.htm (1 of 4) [20/12/2001 11:14:32]
[Chapter 22] CropImageFilter
CropImageFilter public CropImageFilter (int x, int y, int width, int height) Parameters x x-coordinate of top-left corner of piece to crop. y y-coordinate of top-left corner of piece to crop. width Width of image to crop. height Height of image to crop. Description Constructs a CropImageFilter that crops the specified region from the original image.
Instance Methods setDimensions public void setDimensions (int width, int height) Parameters width Ignored parameter. height Ignored parameter. Overrides ImageFilter.setDimensions(int, int) Description Called with the original image's dimensions; these dimensions are ignored. The method in turn calls the ImageConsumer with the dimensions of the cropped image.
setPixels public void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y http://localhost/java/javaref/awt/ch22_03.htm (2 of 4) [20/12/2001 11:14:32]
[Chapter 22] CropImageFilter
y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Overrides ImageFilter.setPixels(int, int, int, int, ColorModel, byte[], int, int) Description Receives a rectangle of image data from the ImageProducer; crops these pixels and delivers them to any ImageConsumers. public void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. offset Offset from beginning of the pixels array.
http://localhost/java/javaref/awt/ch22_03.htm (3 of 4) [20/12/2001 11:14:32]
[Chapter 22] CropImageFilter
scansize Size of each line of data in pixels array. Overrides ImageFilter.setPixels(int, int, int, int, ColorModel, int[], int, int) Description Receives a rectangle of image data from the ImageProducer; crops these pixels and delivers them to any ImageConsumers.
setProperties public void setProperties (Hashtable properties) Parameters properties The properties for the image. Overrides ImageFilter.setProperties(Hashtable) Description Adds the "croprect" image property to the properties list.
See Also ColorModel, Hashtable, ImageFilter
ColorModel
http://localhost/java/javaref/awt/ch22_03.htm (4 of 4) [20/12/2001 11:14:32]
DirectColorModel
[Chapter 22] DirectColorModel
Chapter 22 java.awt.image Reference
DirectColorModel Name DirectColorModel
Description The DirectColorModel class provides a ColorModel that specifies a translation between pixels and alpha, red, green, and blue component values, where the color values are embedded directly within the pixel.
Class Definition public class java.awt.image.DirectColorModel extends java.awt.image.ColorModel { // Constructors public DirectColorModel (int bits, int redMask, int greenMask, int blueMask); public DirectColorModel (int bits, int redMask, int greenMask, int blueMask, int alphaMask); // Instance Methods public final int getAlpha (int pixel); public final int getAlphaMask(); public final int getBlue (int pixel); public final int getBlueMask(); http://localhost/java/javaref/awt/ch22_04.htm (1 of 5) [20/12/2001 11:14:34]
[Chapter 22] DirectColorModel
public public public public public
final final final final final
int int int int int
getGreen (int pixel); getGreenMask() getRed (int pixel); getRedMask(); getRGB (int pixel);
}
Constructors DirectColorModel public DirectColorModel (int bits, int redMask, int greenMask, int blueMask) Parameters bits The number of bits required per pixel of an image using this model. redMask The location of the red component of a pixel. greenMask The location of the green component of a pixel. blueMask The location of the blue component of a pixel. Throws IllegalArgumentException If the mask bits are not contiguous or overlap. Description Constructs a DirectColorModel object with the given size and color masks; the alpha (transparency) component is not used. public DirectColorModel (int bits, int redMask, int greenMask, int blueMask, int alphaMask) Parameters bits The number of bits required per pixel of an image using this model. redMask The location of the red component of a pixel. greenMask http://localhost/java/javaref/awt/ch22_04.htm (2 of 5) [20/12/2001 11:14:34]
[Chapter 22] DirectColorModel
The location of the green component of a pixel. blueMask The location of the blue component of a pixel. alphaMask The location of the alpha component of a pixel. Throws IllegalArgumentException If the mask bits are not contiguous or overlap. Description Constructs a DirectColorModel object with the given size and color masks.
Instance Methods getAlpha public final int getAlpha (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current alpha setting of the pixel. Overrides ColorModel.getAlpha(int)
getAlphaMask public final int getAlphaMask() Returns The current alpha mask setting of the color model.
getBlue public final int getBlue (int pixel) Parameters
http://localhost/java/javaref/awt/ch22_04.htm (3 of 5) [20/12/2001 11:14:34]
[Chapter 22] DirectColorModel
pixel A pixel encoded with this ColorModel. Returns The current blue setting of the pixel. Overrides ColorModel.getBlue(int)
getBlueMask public final int getBlueMask() Returns The current blue mask setting of the color model.
getGreen public final int getGreen (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current green setting of the pixel. Overrides ColorModel.getGreen(int)
getGreenMask public final int getGreenMask() Returns The current green mask setting of the color model.
getRed public final int getRed (int pixel) Parameters pixel
http://localhost/java/javaref/awt/ch22_04.htm (4 of 5) [20/12/2001 11:14:34]
[Chapter 22] DirectColorModel
A pixel encoded with this ColorModel. Returns The current red setting of the pixel. Overrides ColorModel.getRed(int)
getRedMask public final int getRedMask() Returns The current red mask setting of the color model.
getRGB public final int getRGB (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current combined red, green, and blue settings of the pixel. Overrides ColorModel.getRGB(int) Description Gets the color of pixel in the default RGB color model.
See Also ColorModel
CropImageFilter
http://localhost/java/javaref/awt/ch22_04.htm (5 of 5) [20/12/2001 11:14:34]
FilteredImageSource
[Chapter 22] FilteredImageSource
Chapter 22 java.awt.image Reference
FilteredImageSource Name FilteredImageSource
Description The FilteredImageSource class acts as glue to put an original ImageProducer and ImageFilter together to create a new image. As the ImageProducer for the new image, FilteredImageSource is responsible for registering image consumers for the new image.
Class Definition public class java.awt.image.FilteredImageSource extends java.lang.Object implements java.awt.image.ImageProducer { // Constructors public FilteredImageSource (ImageProducer original, ImageFilter filter); // Instance Methods public synchronized void addConsumer (ImageConsumer ic); public synchronized boolean isConsumer (ImageConsumer ic); public synchronized void removeConsumer (ImageConsumer ic); public void requestTopDownLeftRightResend (ImageConsumer ic); public void startProduction (ImageConsumer ic); } http://localhost/java/javaref/awt/ch22_05.htm (1 of 4) [20/12/2001 11:14:38]
[Chapter 22] FilteredImageSource
Constructors FilteredImageSource public FilteredImageSource (ImageProducer original, ImageFilter filter) Parameters original An ImageProducer that generates the image to be filtered. filter The ImageFilter to use to process image data delivered by original. Description Constructs a FilteredImageSource object to filter an image generated by an ImageProducer.
Class Methods addConsumer public synchronized void addConsumer (ImageConsumer ic) Parameters ic ImageConsumer interested in receiving the new image. Implements ImageProducer.addConsumer(ImageConsumer) Description Registers an ImageConsumer as interested in Image information.
isConsumer public synchronized boolean isConsumer (ImageConsumer ic) Parameters ic ImageConsumer to check. Returns
http://localhost/java/javaref/awt/ch22_05.htm (2 of 4) [20/12/2001 11:14:38]
[Chapter 22] FilteredImageSource
true if ImageConsumer is registered with this ImageProducer, false otherwise. Implements ImageProducer.isConsumer(ImageConsumer)
removeConsumer public synchronized void removeConsumer (ImageConsumer ic) Parameters ic ImageConsumer to remove. Implements ImageProducer.removeConsumer(ImageConsumer) Description Removes an ImageConsumer from the registered consumers for this ImageProducer.
requestTopDownLeftRightResend public void requestTopDownLeftRightResend (ImageConsumer ic) Parameters ic ImageConsumer to communicate with. Implements ImageProducer.requestTopDownLeftRightResend() Description Requests the retransmission of the Image data in top-down, left-to-right order.
startProduction public void startProduction (ImageConsumer ic) Parameters ic ImageConsumer to communicate with. Implements ImageProducer.startProduction(ImageConsumer) Description http://localhost/java/javaref/awt/ch22_05.htm (3 of 4) [20/12/2001 11:14:38]
[Chapter 22] FilteredImageSource
Registers ImageConsumer as interested in Image information and tells ImageProducer to start creating the filtered Image data immediately.
See Also ImageFilter, ImageConsumer, ImageProducer, Object
DirectColorModel
http://localhost/java/javaref/awt/ch22_05.htm (4 of 4) [20/12/2001 11:14:38]
ImageConsumer
[Chapter 22] ImageConsumer
Chapter 22 java.awt.image Reference
ImageConsumer Name ImageConsumer
Description ImageConsumer is an interface that provides the means to consume pixel data and render it for display.
Interface Definition public abstract interface java.awt.image.ImageConsumer { // Constants public final static int COMPLETESCANLINES; public final static int IMAGEABORTED; public final static int IMAGEERROR; public final static int RANDOMPIXELORDER; public final static int SINGLEFRAME; public final static int SINGLEFRAMEDONE; public final static int SINGLEPASS; public final static int STATICIMAGEDONE; public final static int TOPDOWNLEFTRIGHT; // Interface Methods public abstract void imageComplete (int status); public abstract void setColorModel (ColorModel model); http://localhost/java/javaref/awt/ch22_06.htm (1 of 6) [20/12/2001 11:14:40]
[Chapter 22] ImageConsumer
public abstract void setDimensions (int width, int height); public abstract void setHints (int hints); public abstract void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize); public abstract void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize); public abstract void setProperties (Hashtable properties); }
Constants COMPLETESCANLINES public final static int COMPLETESCANLINES Hint flag for the setHints(int) method; indicates that the image will be delivered one or more scanlines at a time.
IMAGEABORTED public final static int IMAGEABORTED Status flag for the imageComplete(int) method indicating that the loading process for the image aborted.
IMAGEERROR public final static int IMAGEERROR Status flag for the imageComplete(int) method indicating that an error happened during image loading.
RANDOMPIXELORDER public final static int RANDOMPIXELORDER Hint flag for the setHints(int) method; indicates that the pixels will be delivered in no particular order.
SINGLEFRAME public final static int SINGLEFRAME Hint flag for the setHints(int) method; indicates that the image consists of a single frame.
http://localhost/java/javaref/awt/ch22_06.htm (2 of 6) [20/12/2001 11:14:40]
[Chapter 22] ImageConsumer
SINGLEFRAMEDONE public final static int SINGLEFRAMEDONE Status flag for the imageComplete(int) method indicating a single frame of the image has loaded.
SINGLEPASS public final static int SINGLEPASS Hint flag for the setHints(int) method; indicates that each pixel will be delivered once (i.e., the producer will not make multiple passes over the image).
STATICIMAGEDONE public final static int STATICIMAGEDONE Status flag for the imageComplete(int) method indicating that the image has fully and successfully loaded, and that there are no additional frames.
TOPDOWNLEFTRIGHT public final static int TOPDOWNLEFTRIGHT Hint flag for the setHints(int) method; indicates that pixels will be delivered in a top to bottom, left to right order.
Interface Methods imageComplete public abstract void imageComplete (int status) Parameters status Image loading status flags. Description Called when the image, or a frame of an image sequence, is complete to report the completion status.
http://localhost/java/javaref/awt/ch22_06.htm (3 of 6) [20/12/2001 11:14:40]
[Chapter 22] ImageConsumer
setColorModel public abstract void setColorModel (ColorModel model) Parameters model The color model for the image. Description Tells the ImageConsumer the color model used for most of the pixels in the image.
setDimensions public abstract void setDimensions (int width, int height) Parameters width Width for image. height Height for image. Description Tells the consumer the image's dimensions.
setHints public abstract void setHints (int hints) Parameters hints Image consumption hints. Description Gives the consumer information about how pixels will be delivered.
setPixels public abstract void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize) Parameters x
http://localhost/java/javaref/awt/ch22_06.htm (4 of 6) [20/12/2001 11:14:40]
[Chapter 22] ImageConsumer
x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Description Delivers a rectangular block of pixels to the image consumer. public abstract void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. http://localhost/java/javaref/awt/ch22_06.htm (5 of 6) [20/12/2001 11:14:40]
[Chapter 22] ImageConsumer
offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Description Delivers a rectangular block of pixels to the image consumer.
setProperties public abstract void setProperties (Hashtable properties) Parameters properties The properties for the image. Description Delivers a Hashtable that contains the image's properties.
See Also ColorModel, Hashtable, ImageFilter, PixelGrabber, Object
FilteredImageSource
http://localhost/java/javaref/awt/ch22_06.htm (6 of 6) [20/12/2001 11:14:40]
ImageFilter
[Chapter 22] ImageFilter
Chapter 22 java.awt.image Reference
ImageFilter Name ImageFilter
Description The ImageFilter class sits between the ImageProducer and ImageConsumer as an image is being created to provide a filtered version of that image. Image filters are always used in conjunction with a FilteredImageSource. As an implementer of the ImageConsumer interface, an image filter receives pixel data from the original image's source and delivers it to another image consumer. The ImageFilter class implements a null filter (i.e., the new image is the same as the original); to produce a filter that modifies an image, create a subclass of ImageFilter.
Class Definition public class java.awt.image.ImageFilter extends java.lang.Object
http://localhost/java/javaref/awt/ch22_07.htm (1 of 7) [20/12/2001 11:14:43]
[Chapter 22] ImageFilter
implements java.awt.image.ImageConsumer, java.lang.Cloneable { // Variables protected ImageConsumer consumer; // Constructors public ImageFilter(); // Instance Methods public Object clone(); public ImageFilter getFilterInstance (ImageConsumer ic); public void imageComplete (int status); public void resendTopDownLeftRight (ImageProducer ip); public void setColorModel (ColorModel model); public void setDimensions (int width, int height); public void setHints (int hints); public void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize); public void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize); public void setProperties (Hashtable properties); }
Protected Variables consumer protected ImageConsumer consumer The consumer variable is a reference to the actual ImageConsumer for the Image.
Constructors ImageFilter public ImageFilter() Description Constructs an empty ImageFilter instance.
Instance Methods
http://localhost/java/javaref/awt/ch22_07.htm (2 of 7) [20/12/2001 11:14:43]
[Chapter 22] ImageFilter
clone public Object clone() Overrides Object.clone() Returns A copy of the ImageFilter instance.
getFilterInstance public ImageFilter getFilterInstance (ImageConsumer ic) Parameters ic The consumer in question. Returns A copy of the ImageFilter instance. Description Returns the filter that will do the filtering for ic.
imageComplete void imageComplete (int status) Parameters status Image loading completion status flags. Implements ImageConsumer.imageComplete(int) Description Called by the ImageProducer to indicate an image's completion status. ImageFilter passes these flags to the consumer unchanged.
resendTopDownLeftRight public void resendTopDownLeftRight (ImageProducer ip) Parameters
http://localhost/java/javaref/awt/ch22_07.htm (3 of 7) [20/12/2001 11:14:43]
[Chapter 22] ImageFilter
ip The ImageProducer generating the original image. Description Called by the ImageConsumer to ask the filter to resend the image data in the top-down, left-to-right order. In ImageFilter, this method calls the same method in the ImageProducer, thus relaying the request.
setColorModel void setColorModel (ColorModel model) Parameters model The color model for the image. Implements ImageConsumer.setColorModel(ColorModel) Description Sets the image's color model.
setDimensions void setDimensions (int width, int height) Parameters width Width for image. height Height for image. Implements ImageConsumer.setDimensions(int, int) Description Sets the image's dimensions.
setHints void setHints (int hints) Parameters
http://localhost/java/javaref/awt/ch22_07.htm (4 of 7) [20/12/2001 11:14:43]
[Chapter 22] ImageFilter
hints Image consumption hints. Implements ImageConsumer.setHints(int) Description Called by the ImageProducer to deliver hints about how the image data will be delivered. ImageFilter passes these hints on to the ImageConsumer.
setPixels void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Implements ImageConsumer.setPixels(int, int, int, int, ColorModel, byte[], int, int) Description
http://localhost/java/javaref/awt/ch22_07.htm (5 of 7) [20/12/2001 11:14:43]
[Chapter 22] ImageFilter
Delivers a rectangular block of pixels to the ImageFilter. ImageFilter passes these pixels on to the consumer unchanged. void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Implements ImageConsumer.setPixels(int, int, int, int, ColorModel, int[], int, int) Description Delivers a rectangular block of pixels to the ImageFilter. ImageFilter passes these pixels on to the consumer unchanged.
setProperties void setProperties (Hashtable properties) Parameters properties
http://localhost/java/javaref/awt/ch22_07.htm (6 of 7) [20/12/2001 11:14:43]
[Chapter 22] ImageFilter
The properties for the image. Implements ImageConsumer.setProperties(Hashtable) Description Initializes the image's properties. ImageFilter adds the property "filter" to the Hashtable, and passes the result on to the image consumer; the value of the property is the string returned by the filter's toString() method. If the property "filter" is already in the Hashtable, ImageFilter adds the string returned by its toString() method to the value already associated with that property.
See Also Cloneable, ColorModel, CropImageFilter, Hashtable, ImageConsumer, ImageProducer, Object, ReplicateImageFilter, RGBImageFilter
ImageConsumer
http://localhost/java/javaref/awt/ch22_07.htm (7 of 7) [20/12/2001 11:14:43]
ImageObserver
[Chapter 22] ImageObserver
Chapter 22 java.awt.image Reference
ImageObserver Name ImageObserver
Description ImageObserver is an interface that provides constants and the callback mechanism to receive asynchronous information about the status of an image as it loads.
Interface Definition public abstract interface java.awt.image.ImageObserver { // Constants public static final int ABORT; public static final int ALLBITS; public static final int ERROR; public static final int FRAMEBITS; public static final int HEIGHT; public static final int PROPERTIES; public static final int SOMEBITS; public static final int WIDTH; // Interface Methods public abstract boolean imageUpdate (Image image, int infoflags, int x, int y, int width, int height); } http://localhost/java/javaref/awt/ch22_08.htm (1 of 4) [20/12/2001 11:14:45]
[Chapter 22] ImageObserver
Constants ABORT public static final int ABORT The ABORT flag indicates that the image aborted during loading. An attempt to reload the image may succeed, unless ERROR is also set.
ALLBITS public static final int ALLBITS The ALLBITS flag indicates that the image has completely loaded successfully. The x, y, width, and height arguments to imageUpdate() should be ignored.
ERROR public static final int ERROR The ERROR flag indicates that an error happened during the image loading process. An attempt to reload the image will fail.
FRAMEBITS public static final int FRAMEBITS The FRAMEBITS flag indicates that a complete frame of a multi-frame image has loaded. The x, y, width, and height arguments to imageUpdate() should be ignored.
HEIGHT public static final int HEIGHT The HEIGHT flag indicates that the height information is available for an image; the image's height is in the height argument to imageUpdate().
PROPERTIES public static final int PROPERTIES The PROPERTIES flag indicates that the properties information is available for an image.
http://localhost/java/javaref/awt/ch22_08.htm (2 of 4) [20/12/2001 11:14:45]
[Chapter 22] ImageObserver
SOMEBITS public static final int SOMEBITS The SOMEBITS flag indicates that the image has started loading and some pixels are available. The bounding rectangle for the pixels that have been delivered so far is indicated by the x, y, width, and height arguments to imageUpdate().
WIDTH public static final int WIDTH The WIDTH flag indicates that the width information is available for an image; the image's width is in the width argument to imageUpdate().
Interface Methods imageUpdate public abstract boolean imageUpdate (Image image, int infoflags, int x, int y, int width, int height) Parameters image Image that is being loaded. infoflags The ImageObserver flags for the information that is currently available. x Meaning depends on infoflags that are set. y Meaning depends on infoflags that are set. width Meaning depends on infoflags that are set. height Meaning depends on infoflags that are set. Returns true if image has completed loading (successfully or unsuccessfully), false if additional information needs to be loaded. Description http://localhost/java/javaref/awt/ch22_08.htm (3 of 4) [20/12/2001 11:14:45]
[Chapter 22] ImageObserver
Provides the callback mechanism for the asynchronous loading of images.
See Also Component, Image, Object
ImageFilter
http://localhost/java/javaref/awt/ch22_08.htm (4 of 4) [20/12/2001 11:14:45]
ImageProducer
[Chapter 22] ImageProducer
Chapter 22 java.awt.image Reference
ImageProducer Name ImageProducer
Description ImageProducer is an interface that provides the methods necessary for the production of images and the communication with classes that implement the ImageConsumer interface.
Interface Definition public abstract interface java.awt.image.ImageProducer { // Interface Methods public abstract void addConsumer (ImageConsumer ic); public abstract boolean isConsumer (ImageConsumer ic); public abstract void removeConsumer (ImageConsumer ic); public abstract void requestTopDownLeftRightResend (ImageConsumer ic); public abstract void startProduction (ImageConsumer ic); }
http://localhost/java/javaref/awt/ch22_09.htm (1 of 3) [20/12/2001 11:14:49]
[Chapter 22] ImageProducer
Interface Methods addConsumer public abstract void addConsumer (ImageConsumer ic) Parameters ic An ImageConsumer that wants to receive image data. Description Registers an ImageConsumer as interested in image information.
isConsumer public abstract boolean isConsumer (ImageConsumer ic) Parameters ic ImageConsumer to check. Returns true if ImageConsumer has registered with the ImageProducer, false otherwise.
removeConsumer public abstract void removeConsumer (ImageConsumer ic) Parameters ic ImageConsumer to remove. Description Removes an ImageConsumer from registered consumers for this ImageProducer.
requestTopDownLeftRightResend public abstract void requestTopDownLeftRightResend (ImageConsumer ic) Parameters ic ImageConsumer to communicate with. Description http://localhost/java/javaref/awt/ch22_09.htm (2 of 3) [20/12/2001 11:14:49]
[Chapter 22] ImageProducer
Requests the retransmission of the image data in top-down, left-to-right order.
startProduction public abstract void startProduction (ImageConsumer ic) Parameters ic ImageConsumer to communicate with. Description Registers ImageConsumer as interested in image information and tells ImageProducer to start sending the image data immediately.
See Also FilteredImageSource, Image, ImageConsumer, ImageFilter, MemoryImageSource, Object
ImageObserver
http://localhost/java/javaref/awt/ch22_09.htm (3 of 3) [20/12/2001 11:14:49]
[Chapter 22] IndexColorModel
Chapter 22 java.awt.image Reference
IndexColorModel Name IndexColorModel
Description The IndexColorModel class is a ColorModel that uses a color map lookup table (with a maximum size of 256) to convert pixel values into their alpha, red, green, and blue component parts.
Class Definition public class java.awt.image.IndexColorModel extends java.awt.image.ColorModel { // Constructors public IndexColorModel (int bits, int size, byte[] colorMap, int start, boolean hasalpha); public IndexColorModel (int bits, int size, byte[] colorMap, int start, boolean hasalpha, int transparent); public IndexColorModel (int bits, int size, byte[] red, byte[] green, byte[] blue); public IndexColorModel (int bits, int size, byte[] red, byte[] green, byte[] blue, byte[] alpha); public IndexColorModel (int bits, int size, byte[] red, byte[] green, byte[] blue, int transparent); // Instance Methods http://localhost/java/javaref/awt/ch22_10.htm (1 of 9) [20/12/2001 11:14:51]
[Chapter 22] IndexColorModel
public public public public public public public public public public public
final final final final final final final final final final final
int getAlpha (int pixel); void getAlphas (byte[] alphas); int getBlue (int pixel); void getBlues (byte[] blues); int getGreen (int pixel); void getGreens (byte[] greens); int getMapSize(); int getRed (int pixel); void getReds (byte[] reds); int getRGB (int pixel); int getTransparentPixel();
}
Constructors IndexColorModel public IndexColorModel (int bits, int size, byte[] colorMap, int start, boolean hasalpha) Parameters bits The number of bits in a pixel. size The number of entries in the color map. Note: this is not the size of the colorMap parameter. colorMap Color component values in red, green, blue, alpha order; the alpha component is optional, and may not be present. start The starting position in colorMap array. hasalpha If hasalpha is true, alpha components are present in colorMap array. Throws ArrayIndexOutOfBoundsException If size is invalid. Description Constructs an IndexColorModel object with the given component settings. The size of colorMap must be at least 3*size+start, if hasalpha is false; if hasalpha is true,
http://localhost/java/javaref/awt/ch22_10.htm (2 of 9) [20/12/2001 11:14:51]
[Chapter 22] IndexColorModel
colorMap.length must be at least 4*size+start. public IndexColorModel (int bits, int size, byte[] colorMap, int start, boolean hasalpha, int transparent) Parameters bits The number of bits in a pixel. size The number of entries in the color map. Note: this is not the size of the colorMap parameter. colorMap Color component values in red, green, blue, alpha order; the alpha component is optional, and may not be present. start The starting position in colorMap array. hasalpha If hasalpha is true, alpha components are present in colorMap array. transparent Position of colorMap entry for transparent pixel entry. Throws ArrayIndexOutOfBoundsException If size invalid. Description Constructs an IndexColorModel object with the given component settings. The size of colorMap must be at least 3*size+start, if hasalpha is false; if hasalpha is true, colorMap.length must be at least 4*size+start. The color map has a transparent pixel; its location is given by transparent. public IndexColorModel (int bits, int size, byte[] red, byte[] green, byte[] blue) Parameters bits The number of bits in a pixel. size The number of entries in the color map. red http://localhost/java/javaref/awt/ch22_10.htm (3 of 9) [20/12/2001 11:14:51]
[Chapter 22] IndexColorModel
Red color component values. green Green color component values. blue Blue color component values. Throws ArrayIndexOutOfBoundsException If size invalid. Description Constructs an IndexColorModel object with the given component settings. There is no alpha component. The length of the red, green, and blue arrays must be greater than size. public IndexColorModel (int bits, int size, byte[] red, byte[] green, byte[] blue, byte[] alpha) Parameters bits The number of bits in a pixel. size The number of entries in the color map. red Red color component values. green Green color component values. blue Blue color component values. alpha Alpha component values. Throws ArrayIndexOutOfBoundsException If size is invalid. NullPointerException If size is positive and alpha array is null. Description http://localhost/java/javaref/awt/ch22_10.htm (4 of 9) [20/12/2001 11:14:51]
[Chapter 22] IndexColorModel
Constructs an IndexColorModel object with the given component settings. The length of the red, green, blue, and alpha arrays must be greater than size. public IndexColorModel (int bits, int size, byte[] red, byte[] green, byte[] blue, int transparent) Parameters bits The number of bits in a pixel. size The number of entries in the color map. red Red color component values. green Green color component values. blue Blue color component values. transparent Position of transparent pixel entry. Throws ArrayIndexOutOfBoundsException If size is invalid. Description Constructs an IndexColorModel object with the given component settings. The length of the red, green, blue, and alpha arrays must be greater than size. The color map has a transparent pixel; its location is given by transparent.
Instance Methods getAlpha public final int getAlpha (int pixel) Parameters pixel A pixel encoded with this ColorModel.
http://localhost/java/javaref/awt/ch22_10.htm (5 of 9) [20/12/2001 11:14:51]
[Chapter 22] IndexColorModel
Returns The current alpha setting of the pixel. Overrides ColorModel.getAlpha(int)
getAlphas public final void getAlphas (byte[] alphas) Parameters alphas The alpha values of the pixels in the color model. Description Copies the alpha values from the color map into the array alphas[].
getBlue public final int getBlue (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current blue setting of the pixel. Overrides ColorModel.getBlue(int)
getBlues public final void getBlues (byte[] blues) Parameters blues The blue values of the pixels in the color model. Description Copies the blue values from the color map into the array blues[].
http://localhost/java/javaref/awt/ch22_10.htm (6 of 9) [20/12/2001 11:14:51]
[Chapter 22] IndexColorModel
getGreen public final int getGreen (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current green setting of the pixel. Overrides ColorModel.getGreen(int)
getGreens public final void getGreens (byte[] greens) Parameters greens The green values of the pixels in the color model. Description Copies the green values from the color map into the array greens[].
getMapSize public final int getMapSize() Returns The current size of the color map table.
getRed public final int getRed (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current red setting of the pixel. Overrides http://localhost/java/javaref/awt/ch22_10.htm (7 of 9) [20/12/2001 11:14:51]
[Chapter 22] IndexColorModel
ColorModel.getRed(int)
getReds public final void getReds (byte[] reds) Parameters reds The red values of the pixels in the color model. Description Copies the red values from the color map into the array reds[].
getRGB public final int getRGB (int pixel) Parameters pixel A pixel encoded with this ColorModel. Returns The current combined red, green, and blue settings of the pixel. Overrides ColorModel.getRGB(int) Description Gets the color of pixel in the default RGB color model.
getTransparentPixel public final int getTransparentPixel() Returns The array index for the transparent pixel in the color model.
See Also ColorModel
http://localhost/java/javaref/awt/ch22_10.htm (8 of 9) [20/12/2001 11:14:51]
[Chapter 22] IndexColorModel
ImageProducer
http://localhost/java/javaref/awt/ch22_10.htm (9 of 9) [20/12/2001 11:14:51]
MemoryImageSource
[Chapter 22] MemoryImageSource
Chapter 22 java.awt.image Reference
MemoryImageSource Name MemoryImageSource
Description The MemoryImageSource class allows you to create images completely in memory. You provide an array of data; it serves as an image producer for that data. In the 1.1 release, new methods support using this class for animation (notably setAnimated() and the various overrides of newPixels()).
Class Definition public class java.awt.image.MemoryImageSource extends java.lang.Object implements java.awt.image.ImageProducer { // Constructors public MemoryImageSource (int w, int h, ColorModel cm, byte[] pix, int off, int scan); public MemoryImageSource (int w, int h, ColorModel cm, byte[] pix, int off, int scan, Hashtable props); public MemoryImageSource (int w, int h, ColorModel cm, int[] pix, int off, int scan); public MemoryImageSource (int w, int h, ColorModel cm, int[] pix, int off, int scan, Hashtable props); public MemoryImageSource (int w, int h, int[] pix, http://localhost/java/javaref/awt/ch22_11.htm (1 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
int off, int scan); public MemoryImageSource (int w, int h, int[] pix, int off, int scan, Hashtable props); // Instance Methods public synchronized void addConsumer (ImageConsumer ic); public synchronized boolean isConsumer (ImageConsumer ic); public void newPixels(); public synchronized void newPixels (int x, int y, int w, int h); public synchronized void newPixels (int x, int y, int w, int h, boolean framenotify); public synchronized void newPixels (byte[] newpix, ColorModel newmodel, int offset, int scansize); public synchronized void newPixels (int[] newpix, ColorModel newmodel, int offset, int scansize); public synchronized void removeConsumer (ImageConsumer ic); public void requestTopDownLeftRightResend (ImageConsumer ic); public synchronized void setAnimated (boolean animated); public synchronized void setFullBufferUpdates (boolean fullbuffers); public void startProduction (ImageConsumer ic); }
Constructors MemoryImageSource public MemoryImageSource (int w, int h, ColorModel cm, byte[] pix, int off, int scan) Parameters w Width of the image being created. h Height of the image being created. cm ColorModel of the image being created. pix Array of pixel information. off http://localhost/java/javaref/awt/ch22_11.htm (2 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
The offset of the first pixel in the array; elements prior to this pixel are ignored. scan The number of pixels per scan line in the array. Description Constructs a MemoryImageSource object with the given parameters to serve as an ImageProducer for a new image. public MemoryImageSource (int w, int h, ColorModel cm, byte[] pix, int off, int scan, Hashtable props) Parameters w Width of the image being created. h Height of the image being created. cm ColorModel of the image being created. pix Array of pixel information. off The offset of the first pixel in the array; elements prior to this pixel are ignored. scan The number of pixels per scan line in the array. props Hashtable of properties associated with image. Description Constructs a MemoryImageSource object with the given parameters to serve as an ImageProducer for a new image. public MemoryImageSource (int w, int h, ColorModel cm, int[] pix, int off, int scan) Parameters w Width of the image being created. h
http://localhost/java/javaref/awt/ch22_11.htm (3 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
Height of the image being created. cm ColorModel of the image being created. pix Array of pixel information. off The offset of the first pixel in the array; elements prior to this pixel are ignored. scan The number of pixels per scan line in the array. Description Constructs a MemoryImageSource object with the given parameters to serve as an ImageProducer for a new image. public MemoryImageSource (int w, int h, ColorModel cm, int[] pix, int off, int scan, Hashtable props) Parameters w Width of the image being created. h Height of the image being created. cm ColorModel of the image being created. pix Array of pixel information. off The offset of the first pixel in the array; elements prior to this pixel are ignored. scan The number of pixels per scan line in the array. props Hashtable of properties associated with image. Description Constructs a MemoryImageSource object with the given parameters to serve as an ImageProducer for a new image.
http://localhost/java/javaref/awt/ch22_11.htm (4 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
public MemoryImageSource (int w, int h, int[] pix, int off, int scan) Parameters w Width of the image being created. h Height of the image being created. pix Array of pixel information. off The offset of the first pixel in the array; elements prior to this pixel are ignored. scan The number of pixels per scan line in the array. Description Constructs a MemoryImageSource object with the given parameters to serve as an ImageProducer for a new image. public MemoryImageSource (int w, int h, int[] pix, int off, int scan, Hashtable props) Parameters w Width of the image being created. h Height of the image being created. pix Array of pixel information. off The offset of the first pixel in the array; elements prior to this pixel are ignored. scan The number of pixels per scan line in the array. props Hashtable of properties associated with image. Description Constructs a MemoryImageSource object with the given parameters to serve as an
http://localhost/java/javaref/awt/ch22_11.htm (5 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
ImageProducer for a new image.
Class Methods addConsumer public synchronized void addConsumer (ImageConsumer ic) Parameters ic ImageConsumer requesting image data. Implements ImageProducer.addConsumer(ImageConsumer) Description Registers an ImageConsumer as interested in Image information.
isConsumer public synchronized boolean isConsumer (ImageConsumer ic) Parameters ic ImageConsumer to check. Returns true if ImageConsumer is registered with this ImageProducer, false otherwise. Implements ImageProducer.isConsumer(ImageConsumer)
newPixels public synchronized void newPixels() Description Notifies the MemoryImageSource that there is new data available. The MemoryImageSource notifies all ImageConsumers that there is new data, sending the full rectangle and notifying the consumers that the frame is complete. public synchronized void newPixels (int x, int y, int w, int h, boolean framenotify)
http://localhost/java/javaref/awt/ch22_11.htm (6 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
Parameters x x coordinate of the top left corner of the new image data. y y coordinate of the top left corner of the new image data. w Width of the new image data. h Height of the new image data. Description Notifies the MemoryImageSource that there is new data available. The MemoryImageSource notifies all ImageConsumers that there is new data in the rectangle described by x, y, w, and h. The consumers are notified that the frame is complete. public synchronized void newPixels (int x, int y, int w, int h, boolean framenotify) Parameters x x coordinate of the top left corner of the new image data. y y coordinate of the top left corner of the new image data. w Width of the new image data. h Height of the new image data. framenotify Determines whether this is a complete frame or not. Description Notifies the MemoryImageSource that there is new data available. The MemoryImageSource notifies all ImageConsumers that there is new data in the rectangle described by x, y, w, and h. If framenotify is true, the consumers will also be notified that a frame is complete. public synchronized void newPixels (byte[] newpix, ColorModel newmodel, int offset, int scansize)
http://localhost/java/javaref/awt/ch22_11.htm (7 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
Parameters newpix New array of image data. newmodel The color model to use for the new data. offset Offset into the data array scansize Size of each line. Description Changes the image data for this MemoryImageSource and notifies its ImageConsumers that new data is available. public synchronized void newPixels (int[] newpix, ColorModel newmodel, int offset, int scansize) Parameters newpix New array of image data. newmodel The color model to use for the new data. offset Offset into the data array scansize Size of each line. Description Changes the image data for this MemoryImageSource and notifies its ImageConsumers that new data is available.
removeConsumer public void removeConsumer (ImageConsumer ic) Parameters ic ImageConsumer to remove. http://localhost/java/javaref/awt/ch22_11.htm (8 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
Implements ImageProducer.removeConsumer(ImageConsumer) Description Removes an ImageConsumer from registered consumers for this ImageProducer.
requestTopDownLeftRightResend public void requestTopDownLeftRightResend (ImageConsumer ic) Parameters ic ImageConsumer requesting image data. Implements ImageProducer.requestTopDownLeftRightResend(ImageConsumer) Description Requests the retransmission of the Image data in top-down, left-to-right order.
setAnimated public void setAnimated (boolean animated) Parameters animated Flag indicating whether this image is animated. Description To use this MemoryImageSource for animation, call setAnimated(true). The newPixels() methods will not work otherwise.
setFullBufferUpdates public void setFullBufferUpdates (boolean fullbuffers) Parameters fullbuffers true to send full buffers; false otherwise. Description This method is only important for animations; i.e., you should call setAnimated(true) before using this function. If you do request to send full buffers, then any rectangle parameters http://localhost/java/javaref/awt/ch22_11.htm (9 of 10) [20/12/2001 11:14:57]
[Chapter 22] MemoryImageSource
passed to newPixels() will be ignored and the entire image will be sent to the consumers.
startProduction public void startProduction (ImageConsumer ic) Parameters ic ImageConsumer requesting image data. Implements ImageProducer.startProduction(ImageConsumer) Description Registers ImageConsumer as interested in Image information and tells ImageProducer to start sending the image data immediately.
See Also ColorModel, Hashtable, ImageConsumer, ImageProducer, Object
IndexColorModel
http://localhost/java/javaref/awt/ch22_11.htm (10 of 10) [20/12/2001 11:14:57]
PixelGrabber
[Chapter 22] PixelGrabber
Chapter 22 java.awt.image Reference
PixelGrabber Name PixelGrabber
Description The PixelGrabber class is an ImageConsumer that captures the pixels from an image and saves them in an array.
Class Definition public class java.awt.image.PixelGrabber extends java.lang.Object implements java.awt.image.ImageConsumer { // Constructors public PixelGrabber (Image img, int x, int y, int w, int h, boolean forceRGB); public PixelGrabber (Image image, int x, int y, int width, int height, int[] pixels, int offset, int scansize); public PixelGrabber (ImageProducer ip, int x, int y, int width, int height, int[] pixels, int offset, int scansize); // Instance Methods public synchronized void abortGrabbing(); public synchronized ColorModel getColorModel(); http://localhost/java/javaref/awt/ch22_12.htm (1 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
public synchronized int getHeight(); public synchronized Object getPixels(); public synchronized int getStatus(); public synchronized int getWidth(); public boolean grabPixels() throws InterruptedException; public synchronized boolean grabPixels (long ms) throws InterruptedException; public synchronized void imageComplete (int status); public void setColorModel (ColorModel model); public void setDimensions (int width, int height); public void setHints (int hints); public void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize); public void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize); public void setProperties (Hashtable properties); public synchronized void startGrabbing(); public synchronized int status(); }
Constructors PixelGrabber public PixelGrabber (Image img, int x, int y, int w, int h, boolean forceRGB) Parameters img Image to use as source of pixel data. x x-coordinate of top-left corner of pixel data. y y-coordinate of top-left corner of pixel data. w Width of pixel data. h Height of pixel data. forceRGB http://localhost/java/javaref/awt/ch22_12.htm (2 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
true to force the use of the RGB color model; false otherwise. Description Constructs a PixelGrabber instance to grab the specified area of the image. public PixelGrabber (Image image, int x, int y, int width, int height, int[] pixels, int offset, int scansize) Parameters image Image to use as source of pixel data. x x-coordinate of top-left corner of pixel data. y y-coordinate of top-left corner of pixel data. width Width of pixel data. height Height of pixel data. pixels Where to store pixel data when grabPixels() called. offset Offset from beginning of each line in pixels array. scansize Size of each line of data in pixels array. Description Constructs a PixelGrabber instance to grab the specified area of the image and store the pixel data from this area in the array pixels[]. public PixelGrabber (ImageProducer ip, int x, int y, int width, int height, int[] pixels, int offset, int scansize) Parameters ip ImageProducer to use as source of pixel data. x
http://localhost/java/javaref/awt/ch22_12.htm (3 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
x-coordinate of top-left corner of pixel data. y y-coordinate of top-left corner of pixel data. width Width of pixel data. height Height of pixel data. pixels Where to store pixel data when grabPixels() called. offset Offset from beginning of each line in pixels array. scansize Size of each line of data in pixels array. Description Constructs a PixelGrabber instance to grab data from the specified area of the image generated by an ImageProducer and store the pixel data from this area in the array pixels[].
Instance Methods abortGrabbing public synchronized void abortGrabbing() Description Stops the PixelGrabber's image-grabbing process.
getColorModel public synchronized ColorModel getColorModel() Returns The color model the PixelGrabber is using for its array.
http://localhost/java/javaref/awt/ch22_12.htm (4 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
getHeight public synchronized int getHeight() Returns The height of the grabbed image, or -1 if the height is not known.
getPixels public synchronized Object getPixels() Returns The array of pixels. Description Either a byte array or an integer array is returned, or null if the size and format of the image are not yet known. Because the PixelGrabber may change its mind about what ColorModel it's using, different calls to this method may return different arrays until the image acquisition is complete.
getStatus public synchronized int getStatus() Returns A combination of ImageObserver flags indicating what data is available.
getWidth public synchronized int getWidth() Returns The width of the grabbed image, or -1 if the width is not known.
grabPixels public boolean grabPixels() throws InterruptedException Throws InterruptedException If image grabbing is interrupted before completion.
http://localhost/java/javaref/awt/ch22_12.htm (5 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
Returns true if the image has completed loading, false if the loading process aborted or an error occurred. Description Starts the process of grabbing the pixel data from the source and storing it in the array pixels[] from constructor. Returns when the image is complete, loading aborts, or an error occurs. public synchronized boolean grabPixels (long ms) throws InterruptedException Parameters ms Milliseconds to wait for completion. Returns true if image has completed loading, false if the loading process aborted, or an error or a timeout occurred. Throws InterruptedException If image grabbing is interrupted before completion. Description Starts the process of grabbing the pixel data from the source and storing it in the array pixels[] from constructor. Returns when the image is complete, loading aborts, an error occurs, or a timeout occurs.
imageComplete public synchronized void imageComplete (int status) Parameters status Image loading completion status flags. Implements ImageConsumer.imageComplete(int) Description Called by the ImageProducer to indicate that the image has been delivered.
http://localhost/java/javaref/awt/ch22_12.htm (6 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
setColorModel void setColorModel (ColorModel model) Parameters model The color model for the image. Implements ImageConsumer.setColorModel(ColorModel) Description Does nothing.
setDimensions void setDimensions (int width, int height) Parameters width Width for image. height Height for image. Implements ImageConsumer.setDimensions(int, int) Description Does nothing.
setHints void setHints (int hints) Parameters hints Image consumption hints. Implements ImageConsumer.setHints(int) Description Does nothing. http://localhost/java/javaref/awt/ch22_12.htm (7 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
setPixels void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Implements ImageConsumer.setPixels(int, int, int, int, ColorModel, byte[], int, int) Description Called by the ImageProducer to deliver pixel data from the image. void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y
http://localhost/java/javaref/awt/ch22_12.htm (8 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Implements ImageConsumer.setPixels(int, int, int, int, ColorModel, int[], int, int) Description Called by the ImageProducer to deliver pixel data from the image.
setProperties void setProperties (Hashtable properties) Parameters properties The properties for the image. Implements ImageConsumer.setProperties(Hashtable) Description Does nothing.
startGrabbing public synchronized void startGrabbing() Description http://localhost/java/javaref/awt/ch22_12.htm (9 of 10) [20/12/2001 11:15:01]
[Chapter 22] PixelGrabber
Starts the PixelGrabber's image-grabbing process.
status public synchronized int status () Returns The ImageObserver flags OR'ed together representing the available information about the image. Replaced by getStatus().
See Also ColorModel, Hashtable, Image, ImageConsumer, ImageProducer, InterruptedException, MemoryImageSource, Object
MemoryImageSource
http://localhost/java/javaref/awt/ch22_12.htm (10 of 10) [20/12/2001 11:15:01]
ReplicateScaleFilter
[Chapter 22] ReplicateScaleFilter
Chapter 22 java.awt.image Reference
ReplicateScaleFilter Name ReplicateScaleFilter
Description The ReplicateScaleFilter class uses a simple-minded algorithm to scale an image. If the image is to be reduced, rows and columns of pixels are removed. If the image is to be expanded, rows and columns are duplicated (replicated).
Class Definition public class ReplicateScaleFilter extends java.awt.image.ImageFilter { // Variables protected int destHeight; protected int destWidth; protected Object outpixbuf; protected int srcHeight; protected int srcWidth; protected int[] srccols; protected int[] srcrows;
http://localhost/java/javaref/awt/ch22_13.htm (1 of 6) [20/12/2001 11:15:03]
[Chapter 22] ReplicateScaleFilter
// Constructor public ReplicateScaleFilter(int width, int height); // Instance Methods public void setDimensions (int w, int h); public void setPixels(int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize); public void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize); public void setProperties(Hashtable props); }
Variables destHeight protected int destHeight Height of the scaled image.
destWidth protected int destWidth Width of the scaled image.
outpixbuf protected Object outpixbuf An internal buffer.
srcHeight protected int srcHeight Height of the original image.
srcWidth protected int srcWidth Width of the original image.
http://localhost/java/javaref/awt/ch22_13.htm (2 of 6) [20/12/2001 11:15:03]
[Chapter 22] ReplicateScaleFilter
srccols protected int[] srccols Internal array used to map incoming columns to outgoing columns.
srcrows protected int[] srcrows Internal array used to map incoming rows to outgoing rows.
Constructor ReplicateScaleFilter public ReplicateScaleFilter (int width, int height) Parameters width Width of scaled image. height Height of scaled image. Description Constructs a ReplicateScaleFilter that scales the original image to the specified size. If both width and height are -1, the destination image size will be set to the source image size. If either one of the parameters is -1, it will be set to preserve the aspect ratio of the original image.
Instance Methods setDimensions public void setDimensions (int w, int h) Parameters w Width of the source image. h Height of the source image. Overrides http://localhost/java/javaref/awt/ch22_13.htm (3 of 6) [20/12/2001 11:15:03]
[Chapter 22] ReplicateScaleFilter
ImageFilter.setDimensions(int, int) Description Sets the size of the source image.
setPixels void setPixels (int x, int y, int w, int h, ColorModel model, byte[] pixels, int off, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. w Width of the rectangle of pixel data delivered with this method call. h Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. off Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Overrides ImageFilter.setPixels(int, int, int, int, ColorModel, byte[], int, int) Description Receives a rectangle of image data from the ImageProducer; scales these pixels and delivers them to any ImageConsumers. void setPixels (int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize) Parameters http://localhost/java/javaref/awt/ch22_13.htm (4 of 6) [20/12/2001 11:15:03]
[Chapter 22] ReplicateScaleFilter
x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. w Width of the rectangle of pixel data delivered with this method call. h Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. off Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Overrides ImageFilter.setPixels(int, int, int, int, ColorModel, int[], int, int) Description Receives a rectangle of image data from the ImageProducer; scales these pixels and delivers them to any ImageConsumers.
setProperties public void setProperties (Hashtable props) Parameters props The properties for the image. Overrides ImageFilter.setProperties(Hashtable) Description Adds the "rescale" image property to the properties list.
http://localhost/java/javaref/awt/ch22_13.htm (5 of 6) [20/12/2001 11:15:03]
[Chapter 22] ReplicateScaleFilter
See Also ColorModel, Hashtable, ImageConsumer, ImageFilter, ImageProducer
PixelGrabber
http://localhost/java/javaref/awt/ch22_13.htm (6 of 6) [20/12/2001 11:15:03]
RGBImageFilter
[Chapter 22] RGBImageFilter
Chapter 22 java.awt.image Reference
RGBImageFilter Name RGBImageFilter
Description RGBImageFilter is an abstract class that helps you filter images based on each pixel's color and position. In most cases, the only method you need to implement in subclasses is filterRGB(), which returns a new pixel value based on the old pixel's color and position. RGBImageFilter cannot be used to implement filters that depend on the value of neighboring pixels, or other factors aside from color and position.
Class Definition public abstract class java.awt.image.RGBImageFilter extends java.awt.image.ImageFilter { // Variables protected boolean canFilterIndexColorModel; protected ColorModel newmodel; protected ColorModel oldmodel; // Instance Methods public IndexColorModel filterIndexColorModel (IndexColorModel icm); public abstract int filterRGB (int x, int y, int rgb); public void filterRGBPixels (int x, int y, int width, int height, int[] pixels, int off, int scansize); http://localhost/java/javaref/awt/ch22_14.htm (1 of 6) [20/12/2001 11:15:07]
[Chapter 22] RGBImageFilter
public void setColorModel (ColorModel model); public void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize); public void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize); public void substituteColorModel (ColorModel oldModel, ColorModel newModel); }
Variables canFilterIndexColorModel protected boolean canFilterIndexColorModel Setting the canFilterIndexColorModel variable to true indicates the filter can filter IndexColorModel images. To filter an IndexColorModel, the filter must depend only on color, not on position.
newmodel protected ColorModel newmodel A place to store a new ColorModel.
origmodel protected ColorModel origmodel A place to store an old ColorModel.
Instance Methods filterIndexColorModel public IndexColorModel filterIndexColorModel (IndexColorModel icm) Parameters icm Color model to filter. Returns Filtered color model.
http://localhost/java/javaref/awt/ch22_14.htm (2 of 6) [20/12/2001 11:15:07]
[Chapter 22] RGBImageFilter
Description Helper method for setColorModel() that runs the entire color table of icm through the filterRGB() method of the subclass. Used only if canFilterIndexColorModel is true, and the image uses an IndexColorModel.
filterRGB public abstract int filterRGB (int x, int y, int rgb) Parameters x x-coordinate of pixel data. y y-coordinate of pixel data. rgb Color value of pixel to filter. Returns New color value of pixel. Description Subclasses implement this method to provide a filtering function that generates new pixels.
filterRGBPixels public void filterRGBPixels (int x, int y, int width, int height, int[] pixels, int off, int scansize) Parameters x x-coordinate of top-left corner of pixel data within entire image. y y-coordinate of top-left corner of pixel data within entire image. width Width of pixel data within entire image. height Height of pixel data within entire image. pixels
http://localhost/java/javaref/awt/ch22_14.htm (3 of 6) [20/12/2001 11:15:07]
[Chapter 22] RGBImageFilter
Image data. off Offset from beginning of each line in pixels array. scansize Size of each line of data in pixels array. Description Helper method for setPixels() that filters each element of the pixels buffer through the subclass's filterRGB() method.
setColorModel public void setColorModel (ColorModel model) Parameters model The color model for the image. Overrides ImageFilter.setColorModel(ColorModel) Description Sets the image's color model.
setPixels public void setPixels (int x, int y, int width, int height, ColorModel model, byte[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model
http://localhost/java/javaref/awt/ch22_14.htm (4 of 6) [20/12/2001 11:15:07]
[Chapter 22] RGBImageFilter
Color model of image data. pixels Image data. offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Overrides ImageFilter.setPixels(int, int, int, int, ColorModel, byte[], int, int) Description Called by the ImageProducer to deliver a rectangular block of pixels for filtering. public void setPixels (int x, int y, int width, int height, ColorModel model, int[] pixels, int offset, int scansize) Parameters x x-coordinate of top-left corner of pixel data delivered with this method call. y y-coordinate of top-left corner of pixel data delivered with this method call. width Width of the rectangle of pixel data delivered with this method call. height Height of the rectangle of pixel data delivered with this method call. model Color model of image data. pixels Image data. offset Offset from beginning of the pixels array. scansize Size of each line of data in pixels array. Overrides
http://localhost/java/javaref/awt/ch22_14.htm (5 of 6) [20/12/2001 11:15:07]
[Chapter 22] RGBImageFilter
ImageFilter.setPixels(int, int, int, int, ColorModel, int[], int, int) Description Called by the ImageProducer to deliver a rectangular block of pixels for filtering.
substituteColorModel public void substituteColorModel (ColorModel oldModel, ColorModel newModel) Parameters oldModel New value for origmodel variable. newModel New value for newmodel variable. Description Helper method for setColorModel() to initialize the protected variables newmodel and origmodel.
See Also ColorModel, ImageFilter
ReplicateScaleFilter
http://localhost/java/javaref/awt/ch22_14.htm (6 of 6) [20/12/2001 11:15:07]
java.awt.peer Reference
[Chapter 23] CanvasPeer
Chapter 23 java.awt.peer Reference
CanvasPeer Name CanvasPeer
Description CanvasPeer is an interface that defines the basis for canvases.
Interface Definition public abstract interface java.awt.peer.CanvasPeer extends java.awt.peer.ComponentPeer { }
See Also ComponentPeer
ButtonPeer
http://localhost/java/javaref/awt/ch23_02.htm [20/12/2001 11:15:09]
CheckboxMenuItemPeer
[Chapter 23] CheckboxMenuItemPeer
Chapter 23 java.awt.peer Reference
CheckboxMenuItemPeer Name CheckboxMenuItemPeer
Description CheckboxMenuItemPeer is an interface that defines the basis for checkbox menu items.
Interface Definition public abstract interface java.awt.peer.CheckboxMenuItemPeer extends java.awt.peer.MenuItemPeer { // Interface Methods public abstract void setState (boolean condition); }
http://localhost/java/javaref/awt/ch23_03.htm (1 of 2) [20/12/2001 11:15:13]
[Chapter 23] CheckboxMenuItemPeer
Interface Methods setState public abstract void setState (boolean condition) Parameters condition New state for checkbox menu item's peer. Description Changes the state of checkbox menu item's peer.
See Also MenuComponentPeer, MenuItemPeer
CanvasPeer
http://localhost/java/javaref/awt/ch23_03.htm (2 of 2) [20/12/2001 11:15:13]
CheckboxPeer
[Chapter 23] CheckboxPeer
Chapter 23 java.awt.peer Reference
CheckboxPeer Name CheckboxPeer
Description CheckboxPeer is an interface that defines the basis for checkbox components.
Interface Definition public abstract interface java.awt.peer.CheckboxPeer extends java.awt.peer.ComponentPeer { // Interface Methods public abstract void setCheckboxGroup (CheckboxGroup group); public abstract void setLabel (String label); public abstract void setState (boolean state); }
Interface Methods
http://localhost/java/javaref/awt/ch23_04.htm (1 of 2) [20/12/2001 11:15:17]
[Chapter 23] CheckboxPeer
setCheckboxGroup public abstract void setCheckboxGroup (CheckboxGroup group) Parameters group New group to put the checkbox peer in. Description Changes the checkbox group to which the checkbox peer belongs; implicitly removes the peer from its old group, if any.
setLabel public abstract void setLabel (String label) Parameters label New text for label of checkbox's peer. Description Changes the text of the label of the checkbox's peer.
setState public abstract void setState (boolean state) Parameters state New state for the checkbox's peer. Description Changes the state of the checkbox's peer.
See Also CheckboxGroup, ComponentPeer, String
CheckboxMenuItemPeer
http://localhost/java/javaref/awt/ch23_04.htm (2 of 2) [20/12/2001 11:15:17]
ChoicePeer
[Chapter 23] ChoicePeer
Chapter 23 java.awt.peer Reference
ChoicePeer Name ChoicePeer
Description ChoicePeer is an interface that defines the basis for choice components.
Interface Definition public abstract interface java.awt.peer.ChoicePeer extends java.awt.peer.ComponentPeer { // Interface Methods public abstract void add (String item, int index); public abstract void addItem (String item, int position); public abstract void remove (int index); public abstract void select (int position); }
http://localhost/java/javaref/awt/ch23_05.htm (1 of 3) [20/12/2001 11:15:19]
[Chapter 23] ChoicePeer
Interface Methods add public abstract void add (String item, int index) Parameters item Text of the entry to add. index Position in which to add the entry; position 0 is the first entry in the list. Description Adds a new entry to the available choices at the designated position.
addItem public abstract void addItem (String item, int position) Parameters item Text of the entry to add. position Position in which to add the entry; position 0 is the first entry in the list. Description Adds a new entry to the available choices at the designated position.
remove public abstract void remove (int index) Parameters index Position of the item to remove. Description Removes an entry at the given position.
http://localhost/java/javaref/awt/ch23_05.htm (2 of 3) [20/12/2001 11:15:19]
[Chapter 23] ChoicePeer
select public abstract void select (int position) Parameters position Position to make selected entry. Description Makes the given entry the selected one for the choice's peer.
See Also ComponentPeer, String
CheckboxPeer
http://localhost/java/javaref/awt/ch23_05.htm (3 of 3) [20/12/2001 11:15:19]
[Chapter 23] ComponentPeer
Chapter 23 java.awt.peer Reference
ComponentPeer Name ComponentPeer
Description ComponentPeer is an interface that defines the basis for all non-menu GUI peer interfaces.
Interface Definition public abstract interface java.awt.peer.ComponentPeer { // Interface Methods public abstract int checkImage (Image image, int width, int height, http://localhost/java/javaref/awt/ch23_06.htm (1 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
ImageObserver observer); public abstract Image createImage (ImageProducer producer); public abstract Image createImage (int width, int height); public abstract void disable(); public abstract void dispose(); public public public public
abstract abstract abstract abstract
void enable(); ColorModel getColorModel(); FontMetrics getFontMetrics (Font f); Graphics getGraphics();
public abstract Point getLocationOnScreen(); public abstract Dimension getMinimumSize(); public abstract Dimension getPreferredSize(); public abstract Toolkit getToolkit(); public abstract boolean handleEvent (Event e); public abstract void hide(); public abstract boolean isFocusTraversable(); public abstract Dimension minimumSize(); public abstract void paint (Graphics g); public abstract public abstract ImageObserver public abstract public abstract public abstract
Dimension preferredSize (); boolean prepareImage (Image image, int width, int height, observer); void print (Graphics g); void repaint (long tm, int x, int y, int width, int height); void requestFocus();
public abstract void reshape (int x, int y, int width, int height); public abstract void setBackground (Color c); public abstract void setBounds (int x, int y, int width, int height); public abstract void setCursor (Cursor cursor); public abstract void setEnabled (boolean b); public abstract void setFont (Font f); public abstract void setForeground (Color c); public abstract void setVisible (boolean b); public abstract void show(); }
Interface Methods checkImage public abstract int checkImage (Image image, int width, int height, ImageObserver observer) Parameters image Image to check. http://localhost/java/javaref/awt/ch23_06.htm (2 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
width Horizontal size to which the image will be scaled. height Vertical size to which the image will be scaled. observer An ImageObserver to monitor image loading; normally, the object on which the image will be rendered. Returns ImageObserver flags ORed together indicating status. Description Checks status of image construction.
createImage public abstract Image createImage (ImageProducer producer) Parameters producer An object that implements the ImageProducer interface to create a new image. Returns Newly created image instance. Description Creates an Image based upon an ImageProducer. public abstract Image createImage (int width, int height) Parameters width Horizontal size for in-memory Image. height Vertical size for in-memory Image. Returns Newly created image instance. Description Creates an in-memory Image for double buffering.
disable public abstract void disable()
http://localhost/java/javaref/awt/ch23_06.htm (3 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
Description Disables component so that it is unresponsive to user interactions. Replaced by setEnabled(false).
dispose public abstract void dispose() Description Releases resources used by peer.
enable public abstract void enable() Description Enables component so that it is responsive to user interactions. Replaced by setEnabled(true).
getColorModel public abstract ColorModel getColorModel() Returns ColorModel used to display the current component.
getFontMetrics public abstract FontMetrics getFontMetrics (Font f) Parameters f A font whose metrics are desired. Returns Font sizing information for the desired font.
getGraphics public abstract Graphics getGraphics() Throws InternalException If acquiring a graphics context is unsupported Returns Component's graphics context.
http://localhost/java/javaref/awt/ch23_06.htm (4 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
getLocationOnScreen public abstract Point getLocationOnScreen() Returns The location of the component in the screen's coordinate space.
getMinimumSize public abstract Dimension getMinimumSize() Returns The minimum dimensions of the component.
getPreferredSize public abstract Dimension getPreferredSize() Returns The preferred dimensions of the component.
getToolkit public abstract Toolkit getToolkit() Returns Toolkit of Component.
handleEvent public abstract boolean handleEvent (Event e) Parameters e Event instance identifying what caused the method to be called. Returns true if the peer handled the event, false to propagate the event to the parent container. Description High-level event handling routine.
hide public abstract void hide() Description http://localhost/java/javaref/awt/ch23_06.htm (5 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
Hides the component. Replaced by setVisible(false).
isFocusTraversable public abstract boolean isFocusTraversable() Returns true if the peer can be tabbed onto, false otherwise. Description Determines if this peer is navigable using the keyboard.
minimumSize public abstract Dimension minimumSize() Returns The minimum dimensions of the component. Replaced by getMinimumSize().
paint public abstract void paint (Graphics g) Parameters g Graphics context of the component. Description Draws something in graphics context.
preferredSize public abstract Dimension preferredSize() Returns The preferred dimensions of the component. Replaced by getPreferredSize().
prepareImage public abstract boolean prepareImage (Image image, int width, int height, ImageObserver observer) Parameters image Image to load. width http://localhost/java/javaref/awt/ch23_06.htm (6 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
Horizontal size to which the image will be scaled. height Vertical size to which the image will be scaled. observer An ImageObserver to monitor image loading; normally, the object on which the image will be rendered. Returns true if the image has already loaded, false otherwise. Description Forces the image to start loading.
print public abstract void print (Graphics g) Parameters g Graphics context of component. Description Print something from the graphics context.
repaint public abstract void repaint (long tm, int x, int y, int width, int height) Parameters tm Millisecond delay allowed before repaint. x Horizontal origin of bounding box to redraw. y Vertical origin of bounding box to redraw. width Width of bounding box to redraw. height Height of bounding box to redraw. Description Requests scheduler to redraw portion of component within a time period.
http://localhost/java/javaref/awt/ch23_06.htm (7 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
requestFocus public abstract void requestFocus() Description Requests this Component gets the input focus.
reshape public abstract void reshape (int x, int y, int width, int height) Parameters x New horizontal position for component. y New vertical position for component. width New width for component. height New height for component. Description Relocates and resizes the component's peer. Replaced by setBounds(int, int, int, int).
setBackground public abstract void setBackground (Color c) Parameters c New color for the background. Description Changes the background color of the component.
setBounds public abstract void setBounds (int x, int y, int width, int height) Parameters x New horizontal position for component. y New vertical position for component. http://localhost/java/javaref/awt/ch23_06.htm (8 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
width New width for component. height New height for component. Description Relocates and resizes the component's peer.
setCursor public abstract void setCursor (Cursor cursor) Parameters cursor New cursor. Description Changes the cursor of the component.
setEnabled public abstract void setEnabled (boolean b) Parameters b true to enable the peer; false to disable it. Description Enables or disables the peer.
setFont public abstract void setFont (Font f) Parameters f New font for the component. Description Changes the font used to display text in the component.
setForeground public abstract void setForeground (Color c) Parameters
http://localhost/java/javaref/awt/ch23_06.htm (9 of 10) [20/12/2001 11:15:24]
[Chapter 23] ComponentPeer
c New foreground color for the component. Description Changes the foreground color of the component.
setVisible public abstract void setVisible (boolean b) Parameters b true to show the peer; false to hide it. Description Shows or hides the peer.
show public abstract void show() Description Makes the peer visible. Replaced by setVisible(true).
See Also ButtonPeer, CanvasPeer, CheckboxPeer, ChoicePeer, Color, ColorModel, ContainerPeer, Cursor, Dimension, Event, Font, FontMetrics, Graphics, Image, ImageObserver, ImageProducer, LabelPeer, ListPeer, ScrollbarPeer, TextComponentPeer, Toolkit
ChoicePeer
http://localhost/java/javaref/awt/ch23_06.htm (10 of 10) [20/12/2001 11:15:24]
ContainerPeer
[Chapter 23] ContainerPeer
Chapter 23 java.awt.peer Reference
ContainerPeer Name ContainerPeer
Description ContainerPeer is an interface that defines the basis for containers.
Interface Definition public abstract interface java.awt.peer.ContainerPeer extends java.awt.peer.ComponentPeer { // Interface Methods public abstract void beginValidate(); public abstract void endValidate(); public abstract Insets getInsets(); public abstract Insets insets(); http://localhost/java/javaref/awt/ch23_07.htm (1 of 2) [20/12/2001 11:15:26]
[Chapter 23] ContainerPeer
}
Interface Methods beginValidate public abstract void beginValidate() Description Notifies the peer that the Container is going to validate its contents.
endValidate public abstract void endValidate() Description Notifies the peer that the Container is finished validating its contents.
getInsets public Insets getInsets() Returns Current Insets of container's peer.
insets public Insets insets() Returns Current Insets of container's peer. Replaced by getInsets().
See Also ComponentPeer, Insets, PanelPeer, ScrollPanePeer, WindowPeer
ComponentPeer
http://localhost/java/javaref/awt/ch23_07.htm (2 of 2) [20/12/2001 11:15:26]
DialogPeer
[Chapter 23] DialogPeer
Chapter 23 java.awt.peer Reference
DialogPeer Name DialogPeer
Description DialogPeer is an interface that defines the basis for a dialog box.
Interface Definition public abstract interface java.awt.peer.DialogPeer extends java.awt.peer.WindowPeer { // Interface Methods public abstract void setResizable (boolean resizable); public abstract void setTitle (String title); }
http://localhost/java/javaref/awt/ch23_08.htm (1 of 2) [20/12/2001 11:15:30]
[Chapter 23] DialogPeer
Interface Methods setResizable public abstract void setResizable (boolean resizable) Parameters resizable true if the dialog's peer should allow resizing; false to prevent resizing. Description Changes the resize state of the dialog's peer.
setTitle public abstract void setTitle (String title) Parameters title New title for the dialog's peer. Description Changes the title of the dialog's peer.
See Also FileDialogPeer, String, WindowPeer
ContainerPeer
http://localhost/java/javaref/awt/ch23_08.htm (2 of 2) [20/12/2001 11:15:30]
FileDialogPeer
[Chapter 23] FileDialogPeer
Chapter 23 java.awt.peer Reference
FileDialogPeer Name FileDialogPeer
Description FileDialogPeer is an interface that defines the basis for a file dialog box.
Interface Definition public abstract interface java.awt.peer.FileDialogPeer extends java.awt.peer.DialogPeer { // Interface Methods public abstract void setDirectory (String directory); public abstract void setFile (String file); public abstract void setFilenameFilter (FilenameFilter filter); } http://localhost/java/javaref/awt/ch23_09.htm (1 of 3) [20/12/2001 11:15:35]
[Chapter 23] FileDialogPeer
Interface Methods setDirectory public abstract void setDirectory (String directory) Parameters directory Initial directory for file dialog's peer. Description Changes the directory displayed in the file dialog's peer.
setFile public abstract void setFile (String file) Parameters file Initial filename for the file dialog's peer. Description Changes the default file selection for the file dialog's peer.
setFilenameFilter public abstract void setFilenameFilter (FilenameFilter filter) Parameters filter Initial filter for file dialog's peer. Description Changes the current filename filter of the file dialog's peer.
See Also DialogPeer, FilenameFilter, String
http://localhost/java/javaref/awt/ch23_09.htm (2 of 3) [20/12/2001 11:15:35]
[Chapter 23] FileDialogPeer
DialogPeer
http://localhost/java/javaref/awt/ch23_09.htm (3 of 3) [20/12/2001 11:15:35]
FontPeer
[Chapter 23] FontPeer
Chapter 23 java.awt.peer Reference
FontPeer Name FontPeer
Description FontPeer is an interface that defines the basis for fonts.
Interface Definition public abstract interface java.awt.peer.FontPeer { }
See Also ComponentPeer
FileDialogPeer
http://localhost/java/javaref/awt/ch23_10.htm [20/12/2001 11:15:36]
FramePeer
[Chapter 23] FramePeer
Chapter 23 java.awt.peer Reference
FramePeer Name FramePeer
Description FramePeer is an interface that defines the basis for a frame.
Interface Definition public abstract interface java.awt.peer.FramePeer extends java.awt.peer.WindowPeer { // Interface Methods public abstract void setIconImage (Image image); public abstract void setMenuBar (MenuBar bar); public abstract void setResizable (boolean resizable); public abstract void setTitle (String title); }
http://localhost/java/javaref/awt/ch23_11.htm (1 of 3) [20/12/2001 11:15:40]
[Chapter 23] FramePeer
Interface Methods setIconImage public abstract void setIconImage (Image image) Parameters image New image to use for frame peer's icon. Description Changes the icon associated with the frame's peer.
setMenuBar public abstract void setMenuBar (MenuBar bar) Parameters bar New MenuBar to use for the frame's peer. Description Changes the menu bar of the frame.
setResizable public abstract void setResizable (boolean resizable) Parameters resizable true if the frame's peer should allow resizing, false to prevent resizing. Description Changes the resize state of the frame's peer.
setTitle public abstract void setTitle (String title) Parameters title New title to use for the frame's peer.
http://localhost/java/javaref/awt/ch23_11.htm (2 of 3) [20/12/2001 11:15:40]
[Chapter 23] FramePeer
Description Changes the title of the frame's peer.
See Also Image, MenuBar, String, WindowPeer
FontPeer
http://localhost/java/javaref/awt/ch23_11.htm (3 of 3) [20/12/2001 11:15:40]
LabelPeer
[Chapter 23] LabelPeer
Chapter 23 java.awt.peer Reference
LabelPeer Name LabelPeer
Description LabelPeer is an interface that defines the basis for label components.
Interface Definition public abstract interface java.awt.peer.LabelPeer extends java.awt.peer.ComponentPeer { // Interface Methods public abstract void setAlignment (int alignment); public abstract void setText (String label); }
Interface Methods
http://localhost/java/javaref/awt/ch23_12.htm (1 of 2) [20/12/2001 11:15:44]
[Chapter 23] LabelPeer
setAlignment public abstract void setAlignment (int alignment) Parameters alignment New alignment for label's peer. Description Changes the current alignment of label's peer.
setText public abstract void setText (String label) Parameters label New text for label's peer. Description Changes the current text of label's peer.
See Also ComponentPeer, String
FramePeer
http://localhost/java/javaref/awt/ch23_12.htm (2 of 2) [20/12/2001 11:15:44]
LightweightPeer
[Chapter 23] LightweightPeer
Chapter 23 java.awt.peer Reference
LightweightPeer Name LightweightPeer
Description LightweightPeer is an interface that defines the basis for components that don't have a visual representation. When you directly subclass Component or Container, a LightweightPeer is used.
Interface Definition public abstract interface java.awt.peer.LightweightPeer extends java.awt.peer.ComponentPeer { }
See Also ComponentPeer
LabelPeer
http://localhost/java/javaref/awt/ch23_13.htm (1 of 2) [20/12/2001 11:15:45]
ListPeer
[Chapter 23] LightweightPeer
http://localhost/java/javaref/awt/ch23_13.htm (2 of 2) [20/12/2001 11:15:45]
[Chapter 23] ListPeer
Chapter 23 java.awt.peer Reference
ListPeer Name ListPeer
Description ListPeer is an interface that defines the basis for list components.
Interface Definition public abstract interface java.awt.peer.ListPeer extends java.awt.peer.ComponentPeer { // Interface Methods public abstract void add (String item, int index); public abstract void addItem (String item, int index); public abstract void clear(); public abstract void delItems (int start, int end); public abstract void deselect (int index); public abstract Dimension getMinimumSize (int rows); public abstract Dimension getPreferredSize (int rows); public abstract int[] getSelectedIndexes();
http://localhost/java/javaref/awt/ch23_14.htm (1 of 6) [20/12/2001 11:15:48]
[Chapter 23] ListPeer
public abstract void makeVisible (int index); public abstract Dimension minimumSize (int rows); public abstract Dimension preferredSize (int rows); public abstract void removeAll(); public abstract void select (int position); public abstract void setMultipleMode (boolean b); public abstract void setMultipleSelections (boolean value); }
Interface Methods add public abstract void add (String item, int index) Parameters item Text of an entry to add to the list. index Position in which to add the entry; position 0 is the first entry in the list. Description Adds a new entry to the available choices of the list's peer at the designated position.
addItem public abstract void addItem (String item, int index) Parameters item Text of an entry to add to the list. index Position in which to add the entry; position 0 is the first entry in the list. Description Adds a new entry to the available choices of the list's peer at the designated position. Replaced by add(String, int).
http://localhost/java/javaref/awt/ch23_14.htm (2 of 6) [20/12/2001 11:15:48]
[Chapter 23] ListPeer
clear public abstract void clear() Description Clears all the entries out of the list's peer. Replaced by removeAll().
delItems public abstract void delItems (int start, int end) Parameters start Starting position of entries to delete. end Ending position of entries to delete. Description Removes a set of entries from the list's peer.
deselect public abstract void deselect (int index) Parameters index Position to deselect. Description Deselects entry at designated position, if selected.
getMinimumSize public abstract Dimension getMinimumSize (int rows) Parameters rows Number of rows within list's peer to size. Returns The minimum dimensions of a list's peer of the given size.
http://localhost/java/javaref/awt/ch23_14.htm (3 of 6) [20/12/2001 11:15:48]
[Chapter 23] ListPeer
getPreferredSize public abstract Dimension getPreferredSize (int rows) Parameters rows Number of rows within list's peer to size. Returns The preferred dimensions of a list's peer of the given size.
getSelectedIndexes public abstract int[] getSelectedIndexes() Returns Array of positions of currently selected entries in list's peer.
makeVisible public abstract void makeVisible (int index) Parameters index Position to make visible on screen. Description Ensures an item is displayed on the screen in the list's peer.
minimumSize public abstract Dimension minimumSize (int rows) Parameters rows Number of rows within list's peer to size. Returns The minimum dimensions of a list's peer of the given size. Replaced by getMinimumSize(int).
http://localhost/java/javaref/awt/ch23_14.htm (4 of 6) [20/12/2001 11:15:48]
[Chapter 23] ListPeer
preferredSize public abstract Dimension preferredSize (int rows) Parameters rows Number of rows within list's peer to size. Returns The preferred dimensions of a list's peer of the given size. Replaced by getPreferredSize(int).
removeAll public abstract void removeAll() Description Clears all the entries out of the list's peer.
select public abstract void select (int position) Parameters position Position to select; 0 indicates the first item in the list. Description Makes the given entry the selected item for the list's peer; deselects other selected entries if multiple selections are not enabled.
setMultipleMode public abstract void setMultipleMode (boolean value) Parameters value true to allow multiple selections within the list's peer; false to disallow multiple selections. Description Changes list peer's selection mode. http://localhost/java/javaref/awt/ch23_14.htm (5 of 6) [20/12/2001 11:15:48]
[Chapter 23] ListPeer
setMultipleSelections public abstract void setMultipleSelections (boolean value) Parameters value true to allow multiple selections within the list's peer; false to disallow multiple selections. Description Changes list peer's selection mode. Replaced by setMultipleMode(boolean).
See Also ComponentPeer, Dimension, String
LightweightPeer
http://localhost/java/javaref/awt/ch23_14.htm (6 of 6) [20/12/2001 11:15:48]
MenuBarPeer
[Chapter 23] MenuBarPeer
Chapter 23 java.awt.peer Reference
MenuBarPeer Name MenuBarPeer
Description MenuBarPeer is an interface that defines the basis for menu bars.
Interface Definition public abstract interface java.awt.peer.MenuBarPeer extends java.awt.peer.MenuComponentPeer { // Interface Methods public abstract void addHelpMenu (Menu m); public abstract void addMenu (Menu m); public abstract void delMenu (int index); }
Interface Methods
http://localhost/java/javaref/awt/ch23_15.htm (1 of 2) [20/12/2001 11:15:50]
[Chapter 23] MenuBarPeer
addHelpMenu public abstract void addHelpMenu (Menu m) Parameters m Menu to designate as the help menu with the menu bar's peer. Description Sets a particular menu to be the help menu of the menu bar's peer.
addMenu public abstract void addMenu (Menu m) Parameters m Menu to add to the menu bar's peer Description Adds a menu to the menu bar's peer.
delMenu public abstract void delMenu (int index) Parameters index Menu position to delete from the menu bar's peer. Description Deletes a menu from the menu bar's peer.
See Also Menu, MenuComponentPeer
ListPeer
http://localhost/java/javaref/awt/ch23_15.htm (2 of 2) [20/12/2001 11:15:50]
MenuComponentPeer
[Chapter 23] MenuComponentPeer
Chapter 23 java.awt.peer Reference
MenuComponentPeer Name MenuComponentPeer
Description MenuComponentPeer is an interface that defines the basis for all menu GUI peer interfaces.
Interface Definition public abstract interface java.awt.peer.MenuComponentPeer { // Interface Methods public abstract void dispose(); }
Interface Methods dispose public abstract void dispose() Description
http://localhost/java/javaref/awt/ch23_16.htm (1 of 2) [20/12/2001 11:15:52]
[Chapter 23] MenuComponentPeer
Releases resources used by peer.
See Also MenuBarPeer, MenuItemPeer
MenuBarPeer
http://localhost/java/javaref/awt/ch23_16.htm (2 of 2) [20/12/2001 11:15:52]
MenuItemPeer
[Chapter 23] MenuItemPeer
Chapter 23 java.awt.peer Reference
MenuItemPeer Name MenuItemPeer
Description MenuBarPeer is an interface that defines the basis for menu bars.
Interface Definition public abstract interface java.awt.peer.MenuItemPeer extends java.awt.peer.MenuComponentPeer { // Interface Methods public abstract void disable(); public abstract void enable(); public abstract void setEnabled (boolean b); public abstract void setLabel (String label); }
http://localhost/java/javaref/awt/ch23_17.htm (1 of 3) [20/12/2001 11:15:57]
[Chapter 23] MenuItemPeer
Interface Methods disable public abstract void disable() Description Disables the menu item's peer so that it is unresponsive to user interactions. Replaced by setEnabled(false).
enable public abstract void enable() Description Enables the menu item's peer so that it is responsive to user interactions. Replaced by setEnabled(true).
setEnabled public abstract void setEnabled (boolean b) Parameters b true to enable the peer; false to disable it. Description Enables or disables the menu item's peer.
setLabel public abstract void setLabel (String label) Parameters label New text to appear on the menu item's peer. Description Changes the label of the menu item's peer.
http://localhost/java/javaref/awt/ch23_17.htm (2 of 3) [20/12/2001 11:15:57]
[Chapter 23] MenuItemPeer
See Also CheckboxMenuItemPeer, MenuComponentPeer, MenuPeer, String
MenuComponentPeer
http://localhost/java/javaref/awt/ch23_17.htm (3 of 3) [20/12/2001 11:15:57]
MenuPeer
[Chapter 23] MenuPeer
Chapter 23 java.awt.peer Reference
MenuPeer Name MenuPeer
Description MenuPeer is an interface that defines the basis for menus.
Interface Definition public abstract interface java.awt.peer.MenuPeer extends java.awt.peer.MenuItemPeer { // Interface Methods public abstract void addItem (MenuItem item); public abstract void addSeparator(); public abstract void delItem (int index); }
http://localhost/java/javaref/awt/ch23_18.htm (1 of 2) [20/12/2001 11:15:59]
[Chapter 23] MenuPeer
Interface Methods addItem public abstract void addItem (MenuItem item) Parameters item MenuItem to add to the menu's peer Description Adds a menu item to the menu's peer.
addSeparator public abstract void addSeparator() Description Adds a menu separator to the menu's peer.
delItem public abstract void delItem (int index) Parameters index MenuItem position to delete from the menu's peer. Description Deletes a menu item from the menu's peer.
See Also MenuItem, MenuItemPeer
MenuItemPeer
http://localhost/java/javaref/awt/ch23_18.htm (2 of 2) [20/12/2001 11:15:59]
PanelPeer
[Chapter 23] PanelPeer
Chapter 23 java.awt.peer Reference
PanelPeer Name PanelPeer
Description PanelPeer is an interface that defines the basis for a panel.
Interface Definition public abstract interface java.awt.peer.PanelPeer extends java.awt.peer.ContainerPeer { }
See Also ContainerPeer
http://localhost/java/javaref/awt/ch23_19.htm (1 of 2) [20/12/2001 11:16:00]
[Chapter 23] PanelPeer
MenuPeer
http://localhost/java/javaref/awt/ch23_19.htm (2 of 2) [20/12/2001 11:16:00]
PopupMenuPeer
[Chapter 23] PopupMenuPeer
Chapter 23 java.awt.peer Reference
PopupMenuPeer Name PopupMenuPeer
Description PopupMenuPeer is an interface that defines the basis for a popup menu.
Interface Definition public abstract interface java.awt.peer.PopupMenuPeer extends java.awt.peer.MenuPeer { // Interface Methods public abstract void show (Event e); }
http://localhost/java/javaref/awt/ch23_20.htm (1 of 2) [20/12/2001 11:16:04]
[Chapter 23] PopupMenuPeer
Interface Methods show public abstract void show (Event e) Parameters e A mouse down event that begins the display of the popup menu. Description Shows the peer at the location encapsulated in e.
See Also Event, MenuPeer
PanelPeer
http://localhost/java/javaref/awt/ch23_20.htm (2 of 2) [20/12/2001 11:16:04]
ScrollbarPeer
[Chapter 23] ScrollbarPeer
Chapter 23 java.awt.peer Reference
ScrollbarPeer Name ScrollbarPeer
Description ScrollbarPeer is an interface that defines the basis for scrollbar components.
Interface Definition public abstract interface java.awt.peer.ScrollbarPeer extends java.awt.peer.ComponentPeer { // Interface Methods public abstract void setLineIncrement (int amount); public abstract void setPageIncrement (int amount); public abstract void setValues (int value, int visible, int minimum, int maximum); }
Interface Methods setLineIncrement public abstract void setLineIncrement (int amount) Parameters amount New line increment amount. Description Changes the line increment amount for the scrollbar's peer.
http://localhost/java/javaref/awt/ch23_21.htm (1 of 2) [20/12/2001 11:16:06]
[Chapter 23] ScrollbarPeer
setPageIncrement public abstract void setPageIncrement (int amount) Parameters amount New paging increment amount. Description Changes the paging increment amount for the scrollbar's peer.
setValues public abstract void setValues (int value, int visible, int minimum, int maximum) Parameters value New value for the scrollbar's peer. visible New slider width. minimum New minimum value for the scrollbar's peer. maximum New maximum value for the scrollbar's peer. Description Changes the settings of the scrollbar's peer to the given amounts.
See Also ComponentPeer
PopupMenuPeer
http://localhost/java/javaref/awt/ch23_21.htm (2 of 2) [20/12/2001 11:16:06]
ScrollPanePeer
[Chapter 23] ScrollPanePeer
Chapter 23 java.awt.peer Reference
ScrollPanePeer Name ScrollPanePeer
Description ScrollPanePeer is an interface that defines the basis for a scrolling container.
Interface Definition public abstract interface java.awt.peer.ScrollPanePeer extends java.awt.peer.ContainerPeer { // Interface Methods public abstract void childResized (int w, int h); public abstract int getHScrollbarHeight(); public abstract int getVScrollbarWidth(); public abstract void setScrollPosition (int x, int y); public abstract void setUnitIncrement (Adjustable adj, int u); public abstract void setValue (Adjustable adj, int v); }
http://localhost/java/javaref/awt/ch23_22.htm (1 of 4) [20/12/2001 11:16:09]
[Chapter 23] ScrollPanePeer
Interface Methods childResized public abstract void childResized (int w, int h) Parameters w The new child width. h The new child height. Description Tells the peer that the child has a new size.
getHScrollbarHeight public abstract int getHScrollbarHeight() Returns Height that a horizontal scrollbar would occupy. Description The height is returned regardless of whether the scrollbar is showing or not.
getVScrollbarWidth public abstract int getVScrollbarWidth() Returns Width that a vertical scrollbar would occupy. Description The width is returned regardless of whether the scrollbar is showing or not.
setScrollPosition public abstract void setScrollPosition (int x, int y) Parameters x
http://localhost/java/javaref/awt/ch23_22.htm (2 of 4) [20/12/2001 11:16:09]
[Chapter 23] ScrollPanePeer
The new horizontal position. y The new vertical position. Description Changes the coordinate of the child component that is displayed at the origin of the ScrollPanePeer.
setUnitIncrement public abstract void setUnitIncrement (Adjustable adj, int u) Parameters adj The Adjustable object to change. u The new value. Description Changes the unit increment of the given Adjustable object.
setValue public abstract void setValue (Adjustable adj, int v) Parameters adj The Adjustable object to change. v The new value. Description Changes the value of the given Adjustable object.
See Also Adjustable, ContainerPeer, Scrollbar
ScrollbarPeer
http://localhost/java/javaref/awt/ch23_22.htm (3 of 4) [20/12/2001 11:16:09]
TextAreaPeer
[Chapter 23] ScrollPanePeer
http://localhost/java/javaref/awt/ch23_22.htm (4 of 4) [20/12/2001 11:16:09]
[Chapter 23] TextAreaPeer
Chapter 23 java.awt.peer Reference
TextAreaPeer Name TextAreaPeer
Description TextAreaPeer is an interface that defines the basis for text areas.
Interface Definition public abstract interface java.awt.peer.TextAreaPeer extends java.awt.peer.TextComponentPeer { // Interface Methods public abstract Dimension getMinimumSize (int rows, int columns); public abstract Dimension getPreferredSize (int rows, int columns); public abstract void insert (String string, int position); public abstract void insertText (String string, int position); public abstract Dimension minimumSize (int rows, int columns); public abstract Dimension preferredSize (int rows, int columns); public abstract void replaceRange (String string, int startPosition, int endPosition); http://localhost/java/javaref/awt/ch23_23.htm (1 of 4) [20/12/2001 11:16:14]
[Chapter 23] TextAreaPeer
public abstract void replaceText (String string, int startPosition, int endPosition); }
Interface Methods getMinimumSize public abstract Dimension getMinimumSize (int rows, int columns) Parameters rows Number of rows within the text area's peer. columns Number of columns within the text area's peer. Returns The minimum dimensions of a text area's peer of the given size.
getPreferredSize public abstract Dimension getPreferredSize (int rows, int columns) Parameters rows Number of rows within the text area's peer. columns Number of columns within the text area's peer. Returns The preferred dimensions of a text area's peer of the given size.
insert public abstract void insert (String string, int position) Parameters string Content to place within the text area's peer. position Location at which to insert the content.
http://localhost/java/javaref/awt/ch23_23.htm (2 of 4) [20/12/2001 11:16:14]
[Chapter 23] TextAreaPeer
Description Places additional text within the text area's peer.
insertText public abstract void insertText (String string, int position) Parameters string Content to place within the text area's peer. position Location at which to insert the content. Description Places additional text within the text area's peer. Replaced by insert(String, int).
minimumSize public abstract Dimension minimumSize (int rows, int columns) Parameters rows Number of rows within the text area's peer. columns Number of columns within the text area's peer. Returns The minimum dimensions of a text area's peer of the given size. Replaced by getMinimumSize(int, int).
preferredSize public abstract Dimension preferredSize (int rows, int columns) Parameters rows Number of rows within the text area's peer. columns Number of columns within the text area's peer. Returns The preferred dimensions of a text area's peer of the given size. Replaced by http://localhost/java/javaref/awt/ch23_23.htm (3 of 4) [20/12/2001 11:16:14]
[Chapter 23] TextAreaPeer
getPreferredSize(int, int).
replaceRange public abstract void replaceRange (String string, int startPosition, int endPosition) Parameters string New content to place in the text area's peer. startPosition Starting position of the content to replace. endPosition Ending position of the content to replace. Description Replaces a portion of the text area peer's content with the given text.
replaceText public abstract void replaceText (String string, int startPosition, int endPosition) Parameters string New content to place in the text area's peer. startPosition Starting position of the content to replace. endPosition Ending position of the content to replace. Description Replaces a portion of the text area peer's content with the given text. Replaced by replaceRange(String, int, int).
See Also Dimension, String, TextComponentPeer
ScrollPanePeer
http://localhost/java/javaref/awt/ch23_23.htm (4 of 4) [20/12/2001 11:16:14]
TextComponentPeer
[Chapter 23] TextComponentPeer
Chapter 23 java.awt.peer Reference
TextComponentPeer Name TextComponentPeer
Description TextComponentPeer is an interface that defines the basis for text components.
Interface Definition public abstract interface java.awt.peer.TextComponentPeer extends java.awt.peer.ComponentPeer { // Interface Methods public public public public public
abstract abstract abstract abstract abstract
int getCaretPosition(); int getSelectionEnd(); int getSelectionStart(); String getText(); void select (int selectionStart, int selectionEnd);
public abstract void setCaretPosition (int pos);
http://localhost/java/javaref/awt/ch23_24.htm (1 of 4) [20/12/2001 11:16:16]
[Chapter 23] TextComponentPeer
public abstract void setEditable (boolean state); public abstract void setText (String text); }
Interface Methods getCaretPosition public abstract int getCaretPosition() Returns The current position of the caret (text cursor).
getSelectionEnd public abstract int getSelectionEnd() Returns The ending cursor position of any selected text.
getSelectionStart public abstract int getSelectionStart() Returns The initial position of any selected text.
getText public abstract String getText() Returns The current contents of the text component's peer.
select public abstract void select (int selectionStart, int selectionEnd) Parameters selectionStart Beginning position of the text to select.
http://localhost/java/javaref/awt/ch23_24.htm (2 of 4) [20/12/2001 11:16:16]
[Chapter 23] TextComponentPeer
selectionEnd Ending position of the text to select. Description Selects text in the text component's peer.
selectCaretPosition public abstract void selectCaretPosition (int pos) Parameters pos New caret position. Description Changes the position of the caret (text cursor).
setEditable public abstract void setEditable (boolean state) Parameters state true if the user can change the contents of the text component's peer (i.e., true to make the peer editable); false to make the peer read-only. Description Allows you to change the current editable state of the text component's peer.
setText public abstract void setText (String text) Parameters text New text for the text component's peer . Description Sets the content of the text component's peer.
http://localhost/java/javaref/awt/ch23_24.htm (3 of 4) [20/12/2001 11:16:16]
[Chapter 23] TextComponentPeer
See Also ComponentPeer, String, TextAreaPeer, TextFieldPeer
TextAreaPeer
http://localhost/java/javaref/awt/ch23_24.htm (4 of 4) [20/12/2001 11:16:16]
TextFieldPeer
[Chapter 23] TextFieldPeer
Chapter 23 java.awt.peer Reference
TextFieldPeer Name TextFieldPeer
Description TextFieldPeer is an interface that defines the basis for text fields.
Interface Definition public abstract interface java.awt.peer.TextFieldPeer extends java.awt.peer.TextComponentPeer { // Interface Methods public abstract Dimension getMinimumSize (int rows, int columns); public abstract Dimension getPreferredSize (int rows, int columns); public abstract Dimension minimumSize (int rows, int columns); public abstract Dimension preferredSize (int rows, int columns); public abstract void setEchoChar (char echoChar); public abstract void setEchoCharacter (char c); } http://localhost/java/javaref/awt/ch23_25.htm (1 of 3) [20/12/2001 11:16:19]
[Chapter 23] TextFieldPeer
Interface Methods getMinimumSize public abstract Dimension getMinimumSize (int rows) Parameters rows Number of rows within the text field's peer. Returns The minimum dimensions of a text field's peer of the given size.
getPreferredSize public abstract Dimension getPreferredSize (int rows) Parameters rows Number of rows within the text field's peer. Returns The preferred dimensions of a text field's peer of the given size.
minimumSize public abstract Dimension minimumSize (int rows) Parameters rows Number of rows within the text field's peer. Returns Replaced by getMinimumSize(int).
preferredSize public abstract Dimension preferredSize (int rows) Parameters rows
http://localhost/java/javaref/awt/ch23_25.htm (2 of 3) [20/12/2001 11:16:19]
[Chapter 23] TextFieldPeer
Number of rows within the text field's peer. Returns Replaced by getPreferredSize(int).
setEchoChar public abstract void setEchoChar (char c) Parameters c The character to display for all input. Description Changes the character that is displayed to the user for every character he or she types in the text field.
setEchoCharacter public abstract void setEchoCharacter (char c) Parameters c The character to display for all input. Description Replaced by setEchoChar(char).
See Also Dimension, TextComponentPeer
TextComponentPeer
http://localhost/java/javaref/awt/ch23_25.htm (3 of 3) [20/12/2001 11:16:19]
WindowPeer
[Chapter 23] WindowPeer
Chapter 23 java.awt.peer Reference
WindowPeer Name WindowPeer
Description WindowPeer is an interface that defines the basis for a window.
Interface Definition public abstract interface java.awt.peer.WindowPeer extends java.awt.peer.ContainerPeer { // Interface Methods public abstract void toBack(); public abstract void toFront(); }
http://localhost/java/javaref/awt/ch23_26.htm (1 of 2) [20/12/2001 11:16:21]
[Chapter 23] WindowPeer
Interface Methods toBack public abstract void toBack() Description Puts the window's peer in the background of the display.
toFront public abstract void toFront() Description Brings the window's peer to the foreground of the display.
See Also ContainerPeer, DialogPeer, FramePeer
TextFieldPeer
http://localhost/java/javaref/awt/ch23_26.htm (2 of 2) [20/12/2001 11:16:21]
Using Properties and Resources
[Appendix A] A.2 Server Properties
Appendix A Using Properties and Resources
A.2 Server Properties Java programs can read properties from any file to which they have access. Applications, of course, can open files on the platform where they execute; applets cannot. However, applets can read certain files from the server. Example A.1 is an applet that reads a properties file from its server and uses those properties to customize itself. This is a useful technique for developers working on commercial applets: you can deliver an applet to a customer and let the customer customize the applet by providing a property sheet. The alternative, having the applet read all of its customizations from HTML parameter tags, is a bit more clumsy. Server properties let you distinguish between global customizations like company name (which would be the same on all instances of the applet) and situation-specific customizations, like the name of the animation the user wants to display (the user may use the same applet for many animation sequences). The company name should be configured through a style sheet; the animation filename should be configured by using a tag. Example A.1 uses a properties list to read a message and font information. Following the source is the actual property file. The property file must be in the same directory as the HTML file because we use getDocumentBase() to build the property file's URL. Once we have loaded the property list, we can use getProperty() to read individual properties. Unfortunately, in Java 1.0, we cannot use the Font class's methods to read the font information directly; getFont() can only read properties from the system property list. Therefore, we need to read the font size, name, and type as strings, and call the Font constructor using the pieces as arguments. Java 1.1 does a lot to fix this problem; we'll see how in the next section. Example A.1: Getting Properties from a Server File import java.util.Properties; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.MalformedURLException; public class Prop extends java.applet.Applet { Properties p; String theMessage; http://localhost/java/javaref/awt/appa_02.htm (1 of 3) [20/12/2001 11:16:24]
[Appendix A] A.2 Server Properties
public void init () { p = new Properties(); try { URL propSource = new URL (getDocumentBase(), "prop.list"); InputStream propIS = propSource.openStream(); p.load(propIS); p.list(System.out); initFromProps(p); propIS.close(); } catch (MalformedURLException e) { System.out.println ("Invalid URL"); } catch (IOException e) { System.out.println ("Error loading properties"); } } public void initFromProps (Properties p) { String fontsize = p.getProperty ("MyProg.font.size"); String fontname = p.getProperty ("MyProg.font.name"); String fonttype = p.getProperty ("MyProg.font.type"); String message = p.getProperty ("MyProg.message"); int size; int type; if (fontsize == null) { size = 12; } else { size = Integer.parseInt (fontsize); } if (fontname == null) { fontname = "TimesRoman"; } type = Font.PLAIN; if (fonttype != null) { fonttype.toLowerCase(); boolean bold = (fonttype.indexOf ("bold") != -1); boolean italic = (fonttype.indexOf ("italic") != -1); if (bold) type |= Font.BOLD; if (italic) type |= Font.ITALIC; } if (message == null) { theMessage = "Welcome to Java"; } else { theMessage = message; } setFont (new Font (fontname, type, size)); } public void paint (Graphics g) { http://localhost/java/javaref/awt/appa_02.htm (2 of 3) [20/12/2001 11:16:24]
[Appendix A] A.2 Server Properties
g.drawString (theMessage, 50, 50); } } The file prop.list : MyProg.font.size=20 MyProg.font.type=italic-bold MyProg.font.name=Helvetica MyProg.message=Hello World Figure A.1 results from using this applet with this property file. Figure A.1: Reading server properties
System Properties
http://localhost/java/javaref/awt/appa_02.htm (3 of 3) [20/12/2001 11:16:24]
Resource Bundles
[Appendix A] A.3 Resource Bundles
Appendix A Using Properties and Resources
A.3 Resource Bundles Java 1.1 adds two new pieces to make its property lists more general and flexible. The first is the ability to use localized resource bundles; the second is the use of resource files. Resource bundles let you write internationalized programs. The general idea is that any string you want to display (for example, a button label) shouldn't be specified as a literal constant. Instead, you want to look up the string in a table of equivalents--a "resource bundle"--that contains equivalent strings for different locales. For example, the string "yes" is equivalent to "ja", "si", "oui", and many other language-specific alternatives. A resource bundle lets your program look up the right alternative at run-time, depending on the user's locale. The list of alternatives must be implemented as a subclass of ResourceBundle or ListResourceBundle, in which you provide a key value pair for each label. For each locale you support, a separate subclass and list must be provided. Then you look up the appropriate string through the ResourceBundle.getString() method. A complete example of how to use resource bundles could easily require an entire chapter; I hope this is enough information to get you started.[1] [1] See the Java Fundamental Classes Reference for a more complete description. Resource bundles have one important implication for more mundane programs. Resource bundles can be saved in files and read at run-time. To support them, Java 1.1 has added the ability to load arbitrary properties files. In Example A.1, we looked for the prop.list file on the applet server. What if we want to permit users to modify the default font to be what they want, not what we think they want? With Java 1.0, that could not be done because there was no way for an applet to access the local filesystem. Now, with Java 1.1, you can access read-only resource files located in the CLASSPATH. To do so, you use the Class.getResource() method, which takes the name of a properties list file as an argument. This method returns the URL of the file requested, which could be available locally or on the applet server; where it actually looks depends on the ClassLoader. Once the file is found, treat it as a Properties file, as in Example A.1, or do anything you want with it. A similar method, Class.getResourceAsStream(), returns the InputStream to work with, instead of the URL. Example A.2 is similar to Example A.1. The file prop11.list includes three properties: the font to use, a message, and an image. We need only a single property because we can use the new Font.decode() method to convert a complete font specification into a Font object: we don't need to load the font information in pieces, as we did in the earlier example. As an added bonus, this example displays an image. The name of the image is given by the property MyProg.image. Like the property file itself, the image file can be located anywhere. Here's the properties list, which should be placed in the file http://localhost/java/javaref/awt/appa_03.htm (1 of 3) [20/12/2001 11:16:25]
[Appendix A] A.3 Resource Bundles
prop11.list: MyProg.font=Helvetica-italic-30 MyProg.message=Hello World MyProg.image=ora-icon.gif And the code for the applet is in Example A.2. Example A.2: Getting Properties from a Resource File // Java 1.1 only import java.io.*; import java.net.*; import java.awt.*; import java.util.Properties; import java.applet.Applet; public class Prop11 extends Applet { Image im; Font f; String msg; public void paint (Graphics g) { g.setFont (f); if (im != null) g.drawImage (im, 50, 100, this); if (msg != null) g.drawString (msg, 50, 50); } public void init () { InputStream is = getClass().getResourceAsStream("prop11.list"); Properties p = new Properties(); try { p.load (is); f = Font.decode(p.getProperty("MyProg.font")); msg = p.getProperty("MyProg.message"); String name = p.getProperty("MyProg.image"); URL url = getClass().getResource(name); im = getImage (url); } catch (IOException e) { System.out.println ("error loading props..."); } } }
http://localhost/java/javaref/awt/appa_03.htm (2 of 3) [20/12/2001 11:16:25]
[Appendix A] A.3 Resource Bundles
Server Properties
http://localhost/java/javaref/awt/appa_03.htm (3 of 3) [20/12/2001 11:16:25]
HTML Markup For Applets
[Appendix C] C.2 Test Program
Appendix C Platform-Specific Event Handling
C.2 Test Program The test program, compList, listed in Source Code shows the events peers pass along to the Java run-time system. You can then examine the output to see how the run-time system reacts to the different events. When you run compList, the screen looks something like the one in Figure C.1. Figure C.1: Test program
How to Use the Program Java does not have an automated record and playback feature, so the work is left for you to do. The program displays 10 components: Label, Button, Scrollbar, List, multiselection List, Choice, Checkbox, TextField, TextArea, and Canvas (the black box in Figure C.1). Basically, you must manually trigger every event for every component. For every component on the screen (except Done), do the following: With the mouse Move the cursor over the object, press the mouse button and release, and drag the cursor over the object. With the keyboard Press and release an alphabetic key, press and release the Home and End keys, arrow keys, and function keys. Do this for every component, even for components like Button and Label that have no logical reason for http://localhost/java/javaref/awt/appc_02.htm (1 of 4) [20/12/2001 11:16:28]
[Appendix C] C.2 Test Program
using keyboard events. For items with choices Select and deselect a few choices; double-click and single-click selections. For the scrollbar Click on each arrow, drag the slider, and click in the paging area (the space between each arrow and the slider). For the text field Press Enter. When finished Press the Done button, and analyze the results. Run the program again (without exiting), and check the results again. Try to trigger any specific events that you expect but didn't appear in the output from the first pass. Generating some events requires a little work. For example, on a Macintosh, in order to get the MOUSE_UP and MOUSE_DRAG events, you must do a MOUSE_DOWN off the component; otherwise, the MOUSE_DOWN/MOUSE_UP combination turns into an ACTION_EVENT, if that component can generate it. NOTE: The SunTest business unit of Sun Microsystems has an early version of a record and playback Java GUI testing tool called JavaSTAR. Information about it is available at http://www.suntest.com/JavaSTAR/JavaSTAR.html. In the future, it may be possible to use JavaSTAR to help automate this process.
Source Code The following is the source code for the test program: import java.awt.*; import java.util.*; import java.applet.*; public class compList extends Applet { Button done = new Button ("Done"); Hashtable values = new Hashtable(); public void init () { add (new Label ("Label")); add (new Button ("Button")); add (new Scrollbar (Scrollbar.HORIZONTAL, 50, 25, 0, 255)); List l1 = new List (3, false); l1.addItem ("List 1"); l1.addItem ("List 2"); l1.addItem ("List 3"); l1.addItem ("List 4"); l1.addItem ("List 5"); add (l1); List l2 = new List (3, true); l2.addItem ("Multi 1"); l2.addItem ("Multi 2"); l2.addItem ("Multi 3"); l2.addItem ("Multi 4"); l2.addItem ("Multi 5"); add (l2); http://localhost/java/javaref/awt/appc_02.htm (2 of 4) [20/12/2001 11:16:28]
[Appendix C] C.2 Test Program
Choice c = new Choice (); c.addItem ("Choice 1"); c.addItem ("Choice 2"); c.addItem ("Choice 3"); c.addItem ("Choice 4"); c.addItem ("Choice 5"); add (c); add (new Checkbox ("Checkbox")); add (new TextField ("TextField", 10)); add (new TextArea ("TextArea", 3, 20)); Canvas c1 = new Canvas (); c1.resize (50, 50); c1.setBackground (Color.blue); add (c1); add (done); } public boolean handleEvent (Event e) { if (e.target == done) { if (e.id == Event.ACTION_EVENT) { System.out.println (System.getProperty System.out.println (System.getProperty System.out.println (System.getProperty System.out.println (System.getProperty System.out.println (values); } }else { Vector v; Class c = e.target.getClass(); v = (Vector)values.get(c); if (v == null) v = new Vector(); Integer i = new Integer (e.id); if (!v.contains (i)) { v.addElement (i); values.put (c, v); } } return super.handleEvent (e); }
("java.vendor")); ("java.version")); ("java.class.version")); ("os.name"));
} An HTML document to display the applet in a browser should look something like the following: <APPLET code="compList.class" height=300 width=300>
Examining Results The results of the program are sent to standard output when you click on the Done button. What happens to the output depends on the platform. It may be sent to a log file (Internet Explorer), the Java Console (Netscape Navigator), or the command line (appletviewer). The following is sample output from Internet Explorer 3.0 on a Windows 95 platform.
http://localhost/java/javaref/awt/appc_02.htm (3 of 4) [20/12/2001 11:16:28]
[Appendix C] C.2 Test Program
Microsoft Corp. 1.0.2 45.3 Windows 95 {class java.awt.Canvas=[504, 503, 1004, 501, 506, 502, 505, 1005, 401, 402, 403, 404], class java.awt.Choice=[1001, 401, 402, 403, 404], class java.awt.Checkbox=[1001, 402, 401, 403, 404], class compList=[504, 503, 501, 506, 502, 505, 1004, 1005], class java. awt.TextField=[401, 402, 403, 404], class java.awt.List=[701, 1001, 401, 402, 403, 404, 702], class java.awt.Scrollbar=[602, 605, 604, 603, 601], class java.awt.TextArea=[401, 402, 403, 404], class java.awt.Button=[1001, 401, 402, 403, 404]} In addition to some identifying information about the run-time environment, the program displays a list of classes and the events they passed. The integers represent the event constants of the Event class; for example, Canvas received events with identifiers 504, 503, etc. The events are not sorted, so you can see the order in which they were sent. Unfortunately, you have to look up these constants in the source code yourself. The class listed as compList is the applet itself and shows you the events that the Applet class receives.
The Results
http://localhost/java/javaref/awt/appc_02.htm (4 of 4) [20/12/2001 11:16:28]
Image Loading
[Appendix D] D.2 A Brief Tour of sun.awt.image
Appendix D Image Loading
D.2 A Brief Tour of sun.awt.image The classes in sun.awt.image do the behind-the-scenes work for rendering an image from a file or across the network. This information is purely for the curious; you should never have to work with these classes yourself. Image The Image class in this package represents a concrete Image instance. It contains the basis for the Image class that is actually used on the run-time platform, which exists in the package for the specific environment. For instance, the sun.awt.win32 package includes the W32Image ( Java 1.0), the sun.awt.windows package includes WImage ( Java 1.1), while the sun.awt.motif package includes the X11Image, and the sun.awt.macos package includes the MacImage. ImageRepresentation The ImageRepresentation is the ImageConsumer that watches the creation of the image and notifies the ImageObserver when it is time to update the display. It plays an important part in the overall control of the Image production process. Image sources A Java image can come from three different sources: memory (through createImage()), local disk, or the network (through getImage()). ❍ OffScreenImageSource implements ImageProducer for a single framed image in memory. When an Image created from an OffScreenImageSource is drawn with drawImage(), the ImageObserver parameter can be null since all the image information is already in memory and there is no need for periodic updating as more is retrieved from disk. You can get the graphics context of OffScreenImageSource images and use the context to draw on the image area. This is how double buffering works. ❍ InputStreamImageSource implements ImageProducer for an image that comes from disk or across the network. When an Image created from an InputStreamImageSource is drawn with drawImage(), the ImageObserver parameter should be the component being drawn on (usually this) since the image information will be loaded periodically with the help of the ImageObserver interface). This class determines how to decode the image type and initializes the ImageDecoder to
http://localhost/java/javaref/awt/appd_02.htm (1 of 2) [20/12/2001 11:16:29]
[Appendix D] D.2 A Brief Tour of sun.awt.image
one of GifImageDecoder, JPEGImageDecoder, or XbmImageDecoder, although that can be overridden by a subclass. It can use a ContentHandler to work with unknown image types. ❍ FileImageSource is a subclass of InputStreamImageSource for images that come from the filesystem. It uses the filename to determine the type of image to decode and checks the security manager to ensure that access is allowed. ❍ URLImageSource is a subclass of InputStreamImageSource for images that are specified by a URL. ❍ ByteArrayImageSource ( Java 1.1 only) is a subclass of InputStreamImageSource for images that are created by calling Toolkit.createImage(byte[]). Image decoders An ImageDecoder is utilized to convert the image source to an image object. If there is no decoder for an image type, it can be read in with the help of a ContentHandler or your own class that implements ImageProducer, like the PPMImageDecoder shown in Chapter 12, Image Processing. GifImageDecoder reads in an image file in the GIF format. ❍ JPEGImageDecoder reads in an image file in the JPEG format. ❍ XbmImageDecoder reads in an image file in the XBM format. Although XBM support is not required by the language specification, support is provided with Netscape Navigator, Internet Explorer, HotJava, and the Java Developer's Kit from Sun. ImageFetcher ❍
The ImageFetcher class fetches the actual image from its source. This class creates a separate daemon thread to fetch each image. The thread is run at a higher priority than the default but not at the maximum priority.
How Images are Loaded
http://localhost/java/javaref/awt/appd_02.htm (2 of 2) [20/12/2001 11:16:29]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
B background colors SystemColor Methods Component Methods highlighted text : SystemColor Methods images : Graphics Methods windows : SystemColor Methods beep( ) : Toolkit Methods BITFTP, obtaining examples by : BITFTP BLOCK_ constants : AdjustmentEvent blue (color) Color Methods ColorModel Methods DirectColorModel IndexColorModel blurring filter (example) : ImageFilter Methods BOLD constant : The Font Class BorderLayout( ) : BorderLayout Methods BorderLayout layout BorderLayout BorderLayout BorderLayout borders caption, color of SystemColor Methods inset : Insets Methods windows, color of : SystemColor Methods
http://localhost/java/javaref/awt/index/idx_b.htm (1 of 2) [20/12/2001 11:16:31]
Index
BOTTOM_ALIGNMENT constant : Component Methods bounds( ) : Component Methods brighter( ) : Color Methods browsers : Other Java Books and Resources getting information about : AppletStub Interface status line for Applet Methods AppletContext Interface buffers (see memory) buttons : The Button class Button class The Button class Buttons Button button events : Button Events button mask constants : InputEvent ButtonPeer interface : ButtonPeer ImageButton class : The Button class keyboard events and : Button Events mouse (see mouse events) raised rectangles for : Graphics Methods ByteArrayImageSource class : A Brief Tour of sun.awt.image bytesWidth( ) : The FontMetrics Class
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_b.htm (2 of 2) [20/12/2001 11:16:31]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
C CAB files : The Applet Tag CABBASE parameter name ( tag) : The Applet Tag calculator example : A Simple Calculator Canvas( ) : Canvas Methods Canvas class The Canvas class Canvas Canvas CanvasPeer interface : CanvasPeer captions, colors for SystemColor Methods CardLayout( ) : CardLayout Methods CardLayout layout CardLayout CardLayout CardLayout carets : TextComponent Methods cascading filters : Cascading Filters centering (see alignment) CENTER_ALIGNMENT constant : Component Methods chains, listener (see AWTEventMulticaster class) characters drawing : Graphics Methods echoing : TextField Methods width of : The FontMetrics Class charsWidth( ) : The FontMetrics Class
http://localhost/java/javaref/awt/index/idx_c.htm (1 of 9) [20/12/2001 11:16:35]
Index
charWidth( ) : The FontMetrics Class CHAR_UNDEFINED constant : KeyEvent checkAll( ) : MediaTracker Methods Checkbox( ) : Checkbox Methods checkboxes Checkbox component The Checkbox and CheckboxGroup classes Checkbox Checkbox checkbox events : Checkbox Events checkbox menu events : CheckboxMenuItem Events CheckboxGroup class The Checkbox and CheckboxGroup classes CheckboxGroup CheckboxGroup CheckboxMenuItem class CheckboxMenuItem CheckboxMenuItem CheckboxMenuItemPeer interface : CheckboxMenuItemPeer state of : Checkbox Methods CheckboxGroup( ) : CheckboxGroup Methods CheckboxMenuItem( ) : CheckboxMenuItem Methods checkID( ) : MediaTracker Methods checkImage( ) ImageObserver interface : Component Methods Toolkit class : Toolkit Methods Choice( ) : Component Methods Choice component The Choice class Choice Choice ChoicePeer interface : ChoicePeer circles (see ovals) classes (see also under specific class name) http://localhost/java/javaref/awt/index/idx_c.htm (2 of 9) [20/12/2001 11:16:35]
Index
adapter : The Java 1.1 Event Model AWTEvent class : The Java 1.1 Event Model clear( ) : List Methods clearRect( ) : Graphics Methods clickCount variable : Variables clicking mouse buttons (see mouse events) Clipboard( ) : Clipboard Methods clipboards New Features of AWT in Java 1.1 Clipboards Toolkit Methods Reading and Writing the Clipboard Clipboard class Clipboard Clipboard ClipboardOwner interface ClipboardOwner Interface ClipboardOwner StringSelection class StringSelection StringSelection clipping area : Graphics Methods clipRect( ) : Graphics Methods clone( ) GridBagConstraints class : GridBagConstraints Methods ImageFilter class : ImageFilter Methods Insets class : Insets Methods CODE parameter (<APPLET> tag) : The Applet Tag CODEBASE parameter (<APPLET> tag) : The Applet Tag Color( ) : Color Methods ColorModel( ) : ColorModel Methods colors Color
http://localhost/java/javaref/awt/index/idx_c.htm (3 of 9) [20/12/2001 11:16:35]
Index
background SystemColor Methods Component Methods highlighted text : SystemColor Methods images : Graphics Methods windows : SystemColor Methods caption SystemColor Methods Color class Color Methods Color ColorModel class ColorModel ColorModel DirectColorModel class DirectColorModel DirectColorModel foreground Graphics Methods Component Methods IndexColorModel class IndexColorModel IndexColorModel menus and : SystemColor Methods pop-up help and : SystemColor Methods predefined Color Methods SystemColor Using Desktop Colors SystemColor class SystemColor SystemColor XOR mode and : Graphics Methods columns (see alignment) http://localhost/java/javaref/awt/index/idx_c.htm (4 of 9) [20/12/2001 11:16:35]
Index
columnWeights[ ] variable : GridBagLayout Methods columnWidths[ ] variable : GridBagLayout Methods comparing colors : Color Methods dimensional sizes : Dimension Methods fonts : The Font Class insets : Insets Methods menu shortcuts : MenuShortcut Methods MIME types : DataFlavor Methods points : Point Methods rectangles : Rectangle Methods COMPLETE constant : MediaTracker Methods COMPLETESCANLINES constant : ImageConsumer Interface compList program : Test Program Component( ) : Component Methods COMPONENT_ constants ComponentEvent ContainerEvent ComponentAdapter class : ComponentAdapter ComponentAdapter interface : ComponentListener and ComponentAdapter componentAdded( ) : ContainerListener and ContainerAdapter ComponentEvent( ) : ComponentEvent ComponentEvent class ComponentEvent ComponentEvent componentHidden( ) : ComponentListener and ComponentAdapter ComponentListener interface ComponentListener and ComponentAdapter ComponentListener componentMoved( ) Constants ComponentListener and ComponentAdapter componentRemoved( ) : ContainerListener and ContainerAdapter http://localhost/java/javaref/awt/index/idx_c.htm (5 of 9) [20/12/2001 11:16:35]
Index
componentResized( ) : ComponentListener and ComponentAdapter components Components Component CardLayout layout for CardLayout CardLayout CardLayout Component class Component Methods Component ComponentPeer interface : ComponentPeer designing : Creating Your Own Component handling events in : Component Events padding around : GridBagConstraints Methods peers for (see peers) state of : Component Methods componentShown( ) : ComponentListener and ComponentAdapter constants (see also under specific constant name) alignment : Component Methods AWTEvent class : AWTEvent cursor shapes : Cursor Constants for each keyboard key : KeyEvent Event class : Constants for cursor shapes : Frame Constants predefined colors Color Methods SystemColor Using Desktop Colors consume( ) AWTEvent class : AWTEvent InputEvent class : InputEvent Container( ) : Container Methods CONTAINER_ constants : ContainerEvent http://localhost/java/javaref/awt/index/idx_c.htm (6 of 9) [20/12/2001 11:16:35]
Index
ContainerAdapter class : ContainerAdapter ContainerEvent( ) : ContainerEvent ContainerEvent class : ContainerEvent ContainerListener interface : ContainerListener containers Containers Containers Container class Container Container ContainerAdapter interface : ContainerListener and ContainerAdapter ContainerEvent class : ContainerEvent ContainerListener interface : ContainerListener and ContainerAdapter ContainerPeer interface : ContainerPeer contains( ) Container class : Component Methods Polygon class : Polygon Methods Rectangle class : Rectangle Methods content types DataFlavor DataFlavor ContinuousAudioDataStream class : ContinuousAudioDataStream control color : SystemColor Methods Control key (see modifiers) controlDkShadow color : SystemColor Methods controlDown( ) : Event Methods controlHighlight color : SystemColor Methods controlLtHighlight color : SystemColor Methods controlShadow color : SystemColor Methods controlText color : SystemColor Methods converting colors formats (RGB/HSB) : Color Methods images to pixels : PixelGrabber http://localhost/java/javaref/awt/index/idx_c.htm (7 of 9) [20/12/2001 11:16:35]
Index
coordinates (see also points) coordinate system (see graphics) of events : Variables GridBagLayout components : GridBagConstraints Methods mouse event : MouseEvent copyArea( ) : Graphics Methods CornerLayout layout (example) : A New LayoutManager: CornerLayout corners, rounded : Graphics Methods countComponents( ) : Container Methods countItems( ) Choice component : Component Methods List component : List Methods Menu class : Menu Methods countMenus( ) : MenuBar Methods create( ) : Graphics Methods createImage( ) Component class Graphics Methods Component Methods Toolkit class : Toolkit Methods cropping images : Graphics Methods CropImageFilter class CropImageFilter CropImageFilter CTRL key (see modifiers) Cursor( ) : Cursor Methods cursors components and : Component Methods Cursor class Cursor Cursor Frame class constants for : Frame Constants
http://localhost/java/javaref/awt/index/idx_c.htm (8 of 9) [20/12/2001 11:16:35]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_c.htm (9 of 9) [20/12/2001 11:16:35]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
D darker( ) : Color Methods data Data Transfer DataFlavor class DataFlavor DataFlavor Transferable interface Transferable Interface Transferable DataFlavor( ) : DataFlavor Methods date (see time and date) debugging by overriding event handlers : Basic Event Handlers decode( ) Color class : Color Methods Font class : The Font Class de-emphasizing with color Color Methods SystemColor Methods Displaying Colors delegation model for event handling : The Java 1.1 Event Model deleteMenuShortcut( ) : MenuItem Methods deleteShortcut( ) : MenuBar Methods deleting applets : Applet Methods Graphics objects Graphics Methods
http://localhost/java/javaref/awt/index/idx_d.htm (1 of 4) [20/12/2001 11:16:37]
Index
ImageConsumers (see removeConsumer( )) layout components (see removeLayoutComponent( )) listener interfaces AWTEventMulticaster menu shortcuts MenuItem Methods MenuBar Methods objects from MediaTracker : MediaTracker Methods peers (see removeNotify( )) delItem( ) : List Methods delItems( ) : List Methods deliverEvent( ) : Identifying the Target Component class : Component Events Container class : Container Methods descent, font : The FontMetrics Class deselect( ) : List Methods DESELECTED constant : ItemEvent desktop colors (see SystemColor class) destroy( ) : Applet Methods Dialog( ) : Dialog Constructors and Methods dialogs Dialog and FileDialog Dialogs Dialog class Dialogs Dialog DialogPeer interface : DialogPeer for files (see FileDialog class) Dimension( ) : Dimension Methods Dimension class Dimension Dimension dimensions (see size) DirectColorModel( ) : DirectColorModel http://localhost/java/javaref/awt/index/idx_d.htm (2 of 4) [20/12/2001 11:16:37]
Index
DirectColorModel class DirectColorModel DirectColorModel disable( ) Container class : Component Methods MenuItem class : MenuItem Methods disableEvents( ) Component class : Component Events MenuItem class : MenuItem Events disabling LayoutManager : Disabling the LayoutManager dispatchEvent( ) : MenuComponent Methods dispose( ) Frame class : Frame Methods Graphics class : Graphics Methods Window class : Window Methods documentation (see help) doLayout( ) Component class : Component Methods Container class : Container Methods ScrollPane container : ScrollPane Methods double buffering : Double Buffering draw3DRect( ) : Graphics Methods drawArc( ) : Graphics Methods drawBytes( ) : Graphics Methods drawChars( ) : Graphics Methods drawImage( ) : Graphics Methods drawing (see graphics) drawLine( ) : Graphics Methods drawOval( ) : Graphics Methods drawPolygon( ) : Graphics Methods drawPolyline( ) : Graphics Methods drawRect( ) : Graphics Methods drawRoundRect( ) : Graphics Methods drawString( ) : Graphics Methods http://localhost/java/javaref/awt/index/idx_d.htm (3 of 4) [20/12/2001 11:16:37]
Index
DynamicFilter class (example) : ImageFilter Methods
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_d.htm (4 of 4) [20/12/2001 11:16:37]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
E echoCharIsSet( ) : TextField Methods echoing characters : TextField Methods enable( ) Container class : Component Methods MenuItem class : MenuItem Methods enableEvents( ) Component class : Component Events MenuItem class : MenuItem Events end( ) : Methods equality (see comparing) equals( ) Color class : Color Methods of data flavors (MIME types) : DataFlavor Methods Dimension class : Dimension Methods Font class : The Font Class Insets class : Insets Methods MenuShortcut class : MenuShortcut Methods Point class : Point Methods Rectangle class : Rectangle Methods ERROR constant : ImageObserver Interface ERRORED constant : MediaTracker Methods errors AWTError FileDialog class and Navigator : FileDialog multimedia : MediaTracker Methods when loading images : MediaTracker Methods
http://localhost/java/javaref/awt/index/idx_e.htm (1 of 4) [20/12/2001 11:16:38]
Index
Event( ) : Event Methods EventQueue( ) : Using an event multicaster events New Features of AWT in Java 1.1 Events Events checkbox : Checkbox Events components and : Component Events containers and : Container Methods Event class The Event Class Event event methods : Event Methods event multicasters AWTEventMulticaster AWTEventMulticaster event queue The Java 1.1 Event Model Using an event multicaster Toolkit Methods EventQueue event triggers : Event Triggers event types : The Java 1.1 Event Model EventQueue class The Java 1.1 Event Model Using an event multicaster EventQueue FileDialog class and : Constants focus (see focus events) frames and : Frame Events handlers Dealing With Events Basic Event Handlers
http://localhost/java/javaref/awt/index/idx_e.htm (2 of 4) [20/12/2001 11:16:38]
Index
handling at component level : Component Events Java 1.0 model of : Java 1.0 Event Model Java 1.1 model of : The Java 1.1 Event Model keyboard (see keyboard events) listeners (see listener interfaces) lists and Choice Events List Events menu MenuComponent Methods MenuItem Events CheckboxMenuItem Events Using Java 1.1 Events mouse (see mouse events) platforms and : Platform-Specific Event Handling scrolling (see scrolling, scrolling events) target of Identifying the Target Variables TextArea class and : TextArea Events TextComponent class and : TextComponent Events TextField class and : TextField Events types of : Dealing With Events windows and Window Events Frame Events example programs, obtaining : Obtaining the Example Programs exceptions (see also errors; under specific exception) AWT Exceptions and Errors MIME content type : UnsupportedFlavorException
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
http://localhost/java/javaref/awt/index/idx_e.htm (3 of 4) [20/12/2001 11:16:38]
Index
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_e.htm (4 of 4) [20/12/2001 11:16:38]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
F family, font : The Font Class fetching images : A Brief Tour of sun.awt.image FileDialog( ) : FileDialog Methods FileDialog class Dialog and FileDialog FileDialog FileDialog events for : Constants FileDialogPeer interface : FontPeer FileImageSource class : A Brief Tour of sun.awt.image fill variable (GridBagContraints class) : GridBagConstraints Methods fill3DRect( ) : Graphics Methods fillArc( ) : Graphics Methods fillOval( ) : Graphics Methods fillPolygon( ) : Graphics Methods fillRect( ) : Graphics Methods fillRoundRect( ) : Graphics Methods FilteredImageSource( ) : FilteredImageSource FilteredImageSource class FilteredImageSource FilteredImageSource filterIndexColorModel( ) : RGBImageFilter filtering images : ImageFilter cascading filters : Cascading Filters filterRGB( ) : RGBImageFilter filterRGBPixels( ) : RGBImageFilter http://localhost/java/javaref/awt/index/idx_f.htm (1 of 4) [20/12/2001 11:16:39]
Index
finalize( ) ColorModel class : ColorModel Methods Graphics class : Graphics Methods PrintJob class : Methods first( ) : CardLayout Methods flavors, data (see data) flipping images : Graphics Methods FlowLayout( ) : FlowLayout Methods FlowLayout layout FlowLayout FlowLayout FlowLayout flush( ) : Image Methods focus components and : Component Methods focus events Constants Component Events FocusEvent class FocusEvent FocusEvent listeners for (see listener interfaces) TextArea class and : TextArea Events TextField class and : TextField Events FocusAdapter, FocusListener interfaces FocusListener and FocusAdapter FocusAdapter FocusListener FOCUS_ constants : FocusEvent FocusEvent( ) : FocusEvent focusGained( ) Constants FocusListener and FocusAdapter
http://localhost/java/javaref/awt/index/idx_f.htm (2 of 4) [20/12/2001 11:16:39]
Index
focusLost( ) Constants FocusListener and FocusAdapter Font( ) : The Font Class FontMetrics class : FontMetrics fonts Fonts Component Methods Font class The Font Class Font font size Fonts The Font Class character width : The FontMetrics Class font height : The FontMetrics Class FontMetrics class : FontMetrics graphics and : Graphics Methods FontPeer class : The Font Class FontX class : The Font Class graphics and : Graphics Methods menus and : MenuComponent Methods style of The Font Class foreground colors : Graphics Methods foreground colors : Component Methods Frame( ) : Frame Constructors FRAMEBITS constant : ImageObserver Interface frames Frames Frames centering text in (example) : The FontMetrics Class Frame class http://localhost/java/javaref/awt/index/idx_f.htm (3 of 4) [20/12/2001 11:16:39]
Index
Frame Constants Frame FramePeer interface : FramePeer menubars on : MenuBar menus in (see menus) FTP, obtaining examples by : FTP Ftpmail, obtaining examples by : Ftpmail
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_f.htm (4 of 4) [20/12/2001 11:16:39]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
G gap settings BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout : GridLayout Methods garbage collection : Graphics Methods getActionCommand( ) ActionEvent class : ActionEvent Button component : Button Methods MenuItem class : MenuItem Events getAdjustable( ) : AdjustmentEvent getAdjustmentType( ) : AdjustmentEvent getAlignment( ) FlowLayout layout : FlowLayout Methods Label component : Label Methods getAlignmentX( ) Component class : Component Methods Container class : Container Methods getAlignmentY( ) Component class : Component Methods Container class : Container Methods getAlpha( ) : DirectColorModel ColorModel class : ColorModel Methods DirectColorModel class : DirectColorModel IndexColorModel class : IndexColorModel getAlphas( ) : IndexColorModel
http://localhost/java/javaref/awt/index/idx_g.htm (1 of 14) [20/12/2001 11:16:43]
Index
getApplet( ) : AppletContext Interface getAppletContext( ) Applet class : Applet Methods AppletStub interface : AppletStub Interface getAppletInfo( ) : Applet Methods getApplets( ) : AppletContext Interface getAscent( ) : The FontMetrics Class getAudioClip( ) Applet class : Applet Methods AppletContext interface : AppletContext Interface getBackground( ) : Component Methods getBlockIncrement( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods getBlue( ) Color class : Color Methods ColorModel class : ColorModel Methods DirectColorModel class : DirectColorModel IndexColorModel class : IndexColorModel getBlueMask( ) : DirectColorModel getBlues( ) : IndexColorModel getBounds( ) : Polygon Methods Component class : Component Methods Polygon class : Polygon Methods Rectangle class : Rectangle Methods Shape class : Shape Method getCaretPosition( ) : TextComponent Methods getCheckboxGroup( ) : Checkbox Methods getClickCount( ) : MouseEvent getClip( ) : Graphics Methods getClipBounds( ) : Graphics Methods getClipRect( ) : Graphics Methods getCodeBase( ) Applet class : Applet Methods http://localhost/java/javaref/awt/index/idx_g.htm (2 of 14) [20/12/2001 11:16:43]
Index
AppletStub interface : AppletStub Interface getColFraction( ) : VariableGridLayout getColor( ) Color class : Color Methods Graphics class : Graphics Methods getColorModel( ) : Component Methods PixelGrabber class : PixelGrabber Toolkit class : Toolkit Methods getColumns( ) GridLayout layout : GridLayout Methods TextArea class : TextArea Methods TextField class : TextField Methods getComponent( ) ComponentEvent class : ComponentEvent Container class : Container Methods ContainerEvent class : ContainerEvent getComponentAt( ) Component class : Component Methods Container class : Container Methods getComponentCount( ) : Container Methods getComponents( ) : Container Methods getConstraints( ) : GridBagLayout Methods getContainer( ) : ContainerEvent getContents( ) : Clipboard Methods getCurrent( ) : CheckboxGroup Methods getCursor( ) : Component Methods getCursorType( ) : Frame Methods getData( ) : AudioStream getDefaultCursor( ) : Cursor Methods getDefaultToolkit( ) : Toolkit Methods getDescent( ) The FontMetrics Class getDirectory( ) : FileDialog Methods getDocumentBase( ) http://localhost/java/javaref/awt/index/idx_g.htm (3 of 14) [20/12/2001 11:16:43]
Index
Applet class : Applet Methods AppletStub interface : AppletStub Interface getEchoChar( ) : TextField Methods getDecent( ) : The FontMetrics Class getErrorsAny( ) : MediaTracker Methods getErrorsID( ) : MediaTracker Methods getFamily( ) : The Font Class getFile( ) : FileDialog Methods getFilenameFilter( ) : FileDialog Methods getFilterInstance( ) : ImageFilter Methods getFocusOwner( ) : Window Methods getFont( ) Component class : Component Methods Font class : The Font Class FontMetrics class : The FontMetrics Class Graphics class : Graphics Methods MenuComponent class : MenuComponent Methods MenuContainer interface : MenuContainer Methods getFontList( ) : Toolkit Methods getFontMetrics( ) Graphics Methods Component Methods Toolkit Methods getForeground( ) : Component Methods getGraphics( ) : Component Methods Component class : Graphics Image class : Image Methods PrintJob class : Methods getGreen( ) Color class : Color Methods ColorModel class : ColorModel Methods DirectColorModel class : DirectColorModel IndexColorModel class : IndexColorModel
http://localhost/java/javaref/awt/index/idx_g.htm (4 of 14) [20/12/2001 11:16:43]
Index
getGreenMask( ) : DirectColorModel getGreens( ) : IndexColorModel getHAdjustable( ) : ScrollPane Methods getHeight( ) : Image Methods FontMetrics class The FontMetrics Class PixelGrabber class : PixelGrabber getHelpMenu( ) : MenuBar Methods getHgap( ) BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout : GridLayout Methods getHSBColor( ) : Color Methods getHScrollbarHeight( ) : ScrollPane Methods getHumanPresentableName( ) : DataFlavor Methods getIconImage( ) : Frame Methods getID( ) : AWTEvent getImage( ) Applet class Graphics Methods Applet Methods AppletContext interface : AppletContext Interface Toolkit class Graphics Methods Toolkit Methods getInsets( ) : Container Methods getItem( ) AWTEvent class : ItemEvent Choice component : Component Methods List component : List Methods Menu class : Menu Methods getItemCount( ) Choice component : Component Methods http://localhost/java/javaref/awt/index/idx_g.htm (5 of 14) [20/12/2001 11:16:43]
Index
List component : List Methods Menu class : Menu Methods getItems( ) : List Methods getItemSelectable( ) : ItemEvent getKey( ) : MenuShortcut Methods getKeyChar( ) : KeyEvent getKeyModifiersText( ) : KeyEvent getKeyText( ) : KeyEvent getLabel( ) : Button Methods Checkbox component : Checkbox Methods MenuItem class : MenuItem Methods getLayout( ) : Container Methods getLayoutAlignmentX( ) BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods GridBagLayout layout : GridBagLayout Methods LayoutManager2 interface : The LayoutManager2 Interface getLayoutAlignmentY( ) BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods GridBagLayout layout : GridBagLayout Methods LayoutManager2 interface : The LayoutManager2 Interface getLayoutDimensions( ) : GridBagLayout Methods getLayoutOrigin( ) : GridBagLayout Methods getLayoutWeights( ) : GridBagLayout Methods getLeading( ) : The FontMetrics Class getLength( ) : AudioStream getLineIncrement( ) : Scrollbar Methods getLocale( ) : IllegalComponentStateException Applet class : Applet Methods Component class : Component Methods Window class : Window Methods getLocation( )
http://localhost/java/javaref/awt/index/idx_g.htm (6 of 14) [20/12/2001 11:16:43]
Index
Component class : Component Methods Point class : Point Methods Rectangle class : Rectangle Methods getLocationOnScreen( ) Component Methods IllegalComponentStateException getMapSize( ) : IndexColorModel getMaxAdvance( ) : The FontMetrics Class getMaxAscent( ) : The FontMetrics Class getMaxDescent( ) : The FontMetrics Class getMaximum( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods getMaximumSize( ) Component class : Component Methods Container class : Container Methods getMenu( ) : MenuBar Methods getMenuBar( ) : Frame Methods getMenuCount( ) : MenuBar Methods getMenuShortcut( ) : MenuItem Methods getMenuShortcutKeyMask( ) : Toolkit Methods getMimeType( ) : DataFlavor Methods getMinimum( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods getMinimumSize( ) Component class : Component Methods Container class : Container Methods List component : List Methods TextArea class : TextArea Methods TextField class : TextField Methods getMode( ) : FileDialog Methods getModifiers( ) ActionEvent class : ActionEvent http://localhost/java/javaref/awt/index/idx_g.htm (7 of 14) [20/12/2001 11:16:43]
Index
InputEvent class : InputEvent getName( ) Clipboard class : Clipboard Methods Component class : Component Methods Font class : The Font Class MenuComponent class : MenuComponent Methods getNextEvent( ) : Using an event multicaster getOrientation( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods getPageDimension( ) : Methods getPageIncrement( ) : Scrollbar Methods getPageResolution( ) : Methods getParameter( ) Applet class : Applet Methods AppletStub interface : AppletStub Interface getParameterInfo( ) : Applet Methods getParent( ) Component class : Component Methods MenuComponent class : MenuComponent Methods getPeer( ) Container class : Component Methods Font class : The Font Class MenuComponent class : MenuComponent Methods getPixels( ) : PixelGrabber getPixelSize( ) : ColorModel Methods getPoint( ) : MouseEvent getPredefinedCursor( ) : Cursor Methods getPreferredSize( ) Component class : Component Methods Container class : Container Methods List component : List Methods TextArea class : TextArea Methods TextField class : TextField Methods http://localhost/java/javaref/awt/index/idx_g.htm (8 of 14) [20/12/2001 11:16:43]
Index
getPrintJob( ) PrintGraphics interface : Methods Toolkit class : Toolkit Methods getProperty( ) Image class : Image Methods Toolkit class : Toolkit Methods getRed( ) Color class : Color Methods ColorModel class : ColorModel Methods DirectColorModel class : DirectColorModel IndexColorModel class : IndexColorModel getRedMask( ) : DirectColorModel getReds( ) : IndexColorModel getRepresentationClass( ) : DataFlavor Methods getRGB( ) Color class : Color Methods ColorModel class : ColorModel Methods DirectColorModel class : DirectColorModel IndexColorModel class : IndexColorModel SystemColor class : SystemColor Methods getRGBdefault( ) : ColorModel Methods getRowFraction( ) : VariableGridLayout getRows( ) : GridLayout Methods List component : List Methods TextArea class : TextArea Methods getScaledInstance( ) Image Methods getScreenResolution( ) : Toolkit Methods getScreenSize( ) : Toolkit Methods getScrollbarDisplayPolicy( ) : ScrollPane Methods getScrollbarVisibility( ) : TextArea Methods getScrollPosition( ) : ScrollPane Methods getSelectedCheckbox( ) : CheckboxGroup Methods getSelectedIndex( ) : Component Methods http://localhost/java/javaref/awt/index/idx_g.htm (9 of 14) [20/12/2001 11:16:43]
Index
List component : List Methods getSelectedIndexes( ) : List Methods getSelectedItem( ) Choice component : Component Methods List component : List Methods getSelectedItems( ) CheckboxMenuItem class : CheckboxMenuItem Methods List component : List Methods getSelectedObjects( ) Checkbox component : Checkbox Methods Choice component : Component Methods ItemSelectable interface : Methods List component : List Methods getSelectedText( ) : TextComponent Methods getSelectionEnd( ) : TextComponent Methods getSelectionStart( ) : TextComponent Methods getShortcutMenuItem( ) : MenuBar Methods getSize( ) Component class : Component Methods Dimension class : Dimension Methods Font class : The Font Class Rectangle class : Rectangle Methods getSource( ) : Image Methods getState( ) Checkbox component : Checkbox Methods CheckboxMenuItem class : CheckboxMenuItem Methods getStateChange( ) : ItemEvent getStatus( ) : PixelGrabber getStyle( ) : The Font Class getSystemClipboard( ) : Toolkit Methods getSystemEventQueue( ) : Toolkit Methods getSystemEventQueueImpl( ) : Toolkit Methods getText( ) Label component : Label Methods http://localhost/java/javaref/awt/index/idx_g.htm (10 of 14) [20/12/2001 11:16:43]
Index
TextComponent class : TextComponent Methods getTitle( ) Dialog class : Dialog Constructors and Methods Frame class : Frame Methods getToolkit( ) Component class : Component Methods Window class : Window Methods getTransferData( ) StringSelection class : StringSelection Methods Transferable interface : Transferable Interface getTransferDataFlavors( ) DataFlavor class : Transferable Interface StringSelection class : StringSelection Methods getTransparentPixel( ) : IndexColorModel getTreeLock( ) : Component Methods getType( ) : Cursor Methods getUnitIncrement( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods getUpdateRect( ) : PaintEvent getVAdjustable( ) : ScrollPane Methods getValue( ) Adjustable interface : Methods of the Adjustable Interface AdjustmentEvent class : AdjustmentEvent Scrollbar class : Scrollbar Methods getVgap( ) BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout : GridLayout Methods getViewportSize( ) : ScrollPane Methods getVisible( ) : Scrollbar Methods getVisibleAmount( ) Adjustable interface : Methods of the Adjustable Interface http://localhost/java/javaref/awt/index/idx_g.htm (11 of 14) [20/12/2001 11:16:43]
Index
Scrollbar class : Scrollbar Methods getVisibleIndex( ) : List Methods getVScrollbarWidth( ) : ScrollPane Methods getWarningString( ) : Window Methods getWhen( ) : InputEvent getWidth( ) Image class : Image Methods PixelGrabber class : PixelGrabber getWidths( ) : The FontMetrics Class getWindow( ) : WindowEvent getX( ) : MouseEvent getY( ) : MouseEvent gotFocus( ) Component class : Component Events TextArea class : TextArea Events TextField class and : TextField Events GOT_FOCUS event Constants TextField Events TextArea Events grabPixels( ) : PixelGrabber graphics animation (see animation) Canvas class for The Canvas class Canvas Canvas components and : Component Methods Container class and : Container Methods coordinate space Graphics Methods Point Methods double buffering : Double Buffering Graphics class http://localhost/java/javaref/awt/index/idx_g.htm (12 of 14) [20/12/2001 11:16:43]
Index
Graphics Graphics images (see images) multimedia and : MediaTracker PaintEvent class PaintEvent PaintEvent printing PrintGraphics Interface PrintGraphics shapes and (see shapes) XOR mode : Graphics Methods green (color) Color Methods ColorModel Methods DirectColorModel IndexColorModel GridBagConstraints( ) : GridBagConstraints Methods GridBagConstraints class : GridBagConstraints GridBagLayout( ) : GridBagLayout Methods GridBagLayout layout GridBagLayout GridBagLayout GridBagLayout GridBagConstraints class : GridBagConstraints gridheight, gridwidth variables (GridBagConstraints class) : GridBagConstraints Methods GridLayout( ) : GridLayout Methods GridLayout layout GridLayout GridLayout GridLayout grow( ) : Rectangle Methods
http://localhost/java/javaref/awt/index/idx_g.htm (13 of 14) [20/12/2001 11:16:43]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_g.htm (14 of 14) [20/12/2001 11:16:43]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
H handleEvent( ) : Dealing With Events Component class : Component Events hashCode( ) Color class : Color Methods Font class : The Font Class Point class : Point Methods Rectangle class : Rectangle Methods height (see size) HEIGHT parameter (<APPLET> tag) : The Applet Tag help help menus : MenuBar Methods pop-up help colors : SystemColor Methods resources for further reading : Other Java Books and Resources hide( ) : Component Methods highlighting with color Color Methods SystemColor Methods Displaying Colors horizontal alignment (see alignment) character width : The FontMetrics Class gaps (see gap settings) HorizBagLayout : HorizBagLayout scrollbars (see scrolling) size (see size) HSB colors
http://localhost/java/javaref/awt/index/idx_h.htm (1 of 2) [20/12/2001 11:16:45]
Index
Color Methods HSBtoRGB( ) : Color Methods HSPACE parameter (<APPLET> tag) : The Applet Tag
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_h.htm (2 of 2) [20/12/2001 11:16:45]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
I IllegalComponentStateException exception IllegalComponentStateException IllegalComponentStateException IMAGEABORTED constant : ImageConsumer Interface imageComplete( ) : ImageConsumer Interface ImageFilter class : ImageFilter Methods PixelGrabber class : PixelGrabber IMAGEERROR constant : ImageConsumer Interface images (see loading images) Graphics Methods Image Processing ImageProducer animation with : Simple Animation applets and : Applet Methods AreaAveragingScaleFilter class : AreaAveragingScaleFilter components and : Component Methods converting to pixels : PixelGrabber cropping : CropImageFilter decoders for : A Brief Tour of sun.awt.image double buffering : Double Buffering DynamicFilter class (example) : ImageFilter Methods FilteredImageSource class : FilteredImageSource Image class A Brief Tour of sun.awt.image Image Image http://localhost/java/javaref/awt/index/idx_i.htm (1 of 6) [20/12/2001 11:16:47]
Index
image filters : ImageFilter ImageButton class : The Button class ImageConsumer interface ImageConsumer ImageConsumer ImageFetcher class : A Brief Tour of sun.awt.image ImageFilter class ImageFilter Methods ImageFilter ImageObserver interface Graphics Methods ImageObserver ImageObserver ImageProducer interface ImageProducer ImageProducer ImageProducer object : Image Methods ImageRepresentation consumer : A Brief Tour of sun.awt.image InputStreamImageSource class : A Brief Tour of sun.awt.image loading (see loading images) MemoryImageSource class MemoryImageSource MemoryImageSource modifying : PixelGrabber multimedia and : MediaTracker PixelGrabber class : PixelGrabber PPMImageDecoder class (example) : ImageConsumer Interface ReplicateScaleFilter class ReplicateScaleFilter ReplicateScaleFilter RGBImageFilter class RGBImageFilter RGBImageFilter
http://localhost/java/javaref/awt/index/idx_i.htm (2 of 6) [20/12/2001 11:16:47]
Index
scrolling (example) : Scrolling An Image size of Image Methods ImageObserver Interface ImageConsumer Interface sources, classes for : A Brief Tour of sun.awt.image Toolkit class and : Toolkit Methods imageUpdate( ) Component Methods ImageObserver Interface inactiveCaption color : SystemColor Methods inactiveCaptionBorder color : SystemColor Methods inactiveCaptionText color : SystemColor Methods incrementaldraw parameter : Component Methods IndexColorModel class IndexColorModel IndexColorModel info color : SystemColor Methods infoText color : SystemColor Methods inheritance : Introduction to the Reference Chapters init( ) Applet class : Applet Methods MediaTracker class : Using a MediaTracker input : User Input Checkbox component Checkbox Checkbox CheckboxGroup class CheckboxGroup CheckboxGroup Choice component Choice Choice dialogs (see dialogs; FileDialog class) http://localhost/java/javaref/awt/index/idx_i.htm (3 of 6) [20/12/2001 11:16:47]
Index
InputEvent class InputEvent InputEvent keyboard : The TextField and TextArea classes List component : Lists menus for (see menus) multiline text (see text, TextArea class) single-line text (see text, TextField class) text (see text) insert( ) Choice component : Component Methods Menu class : Menu Methods TextArea class : TextArea Methods inserting text : TextComponent Methods insertSeparator( ) : Menu Methods insets( ) : Container Methods Insets class Insets Insets inside( ) Container class : Component Methods Polygon class : Polygon Methods Rectangle class : Rectangle Methods interfaces (see also under specific interface) listeners (see listener interfaces) peer (see peers) InterruptedException, waiting and : MediaTracker Methods intersection( ) : Rectangle Methods intersections with rectangles : Rectangle Methods intersects( ) : Rectangle Methods invalidate( ) Component class : Component Methods Container class : Container Methods
http://localhost/java/javaref/awt/index/idx_i.htm (4 of 6) [20/12/2001 11:16:47]
Index
invalidateLayout( ) : The LayoutManager2 Interface BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods GridBagLayout layout : GridBagLayout Methods isActionKey( ) : KeyEvent isActive( ) Applet class : Applet Methods AppletStub interface : AppletStub Interface isAltDown( ) : InputEvent isAncestorOf( ) : Container Methods isBold( ) : The Font Class isConsumed( ) AWTEvent class : AWTEvent InputEvent class : InputEvent isConsumer( ) FilteredImageSource class : FilteredImageSource ImageProducer interface : ImageProducer Interface MemoryImageSource class : MemoryImageSource isControlDown( ) : InputEvent isDataFlavorSupported( ) DataFlavor class : Transferable Interface StringSelection class : StringSelection Methods isEditable( ) : TextComponent Methods isEmpty( ) : Rectangle Methods isEnabled( ) Component class : Component Methods MenuItem class : MenuItem Methods isErrorAny( ) : MediaTracker Methods isErrorID( ) : MediaTracker Methods isFocusTraversable( ) : Component Methods isIndexSelected( ) : List Methods isItalic( ) : The Font Class isMetaDown( ) : InputEvent isMimeTypeEqual( ) : DataFlavor Methods http://localhost/java/javaref/awt/index/idx_i.htm (5 of 6) [20/12/2001 11:16:47]
Index
isModal( ) : Dialog Constructors and Methods isMultipleMode( ) : List Methods isPlain( ) : The Font Class isPopupTrigger( ) : MouseEvent isResizable( ) Dialog class : Dialog Constructors and Methods Frame classM : Frame Methods isSelected( ) : List Methods isShiftDown( ) : InputEvent isShowing( ) : Component Methods isTearOff( ) : Menu Methods isTemporary( ) : FocusEvent isValid( ) : Component Methods isVisible( ) : Component Methods ITALIC constant : The Font Class ITEM_ constants : ItemEvent ItemEvent class ItemEvent ItemEvent ItemListener interface ItemListener ItemListener ItemSelectable interface ItemSelectable ItemSelectable itemStateChanged( ) Constants ItemListener
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_i.htm (6 of 6) [20/12/2001 11:16:47]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
J JAR files : The Applet Tag Java resources for further reading : Other Java Books and Resources versions of : Preface Java 1.0 Event class constants : Constants event handling Java 1.0 Event Model The Java 1.1 Event Model mouse buttons in : Working With Mouse Buttons in Java 1.0 JavaBeans : Deprecated Methods and JavaBeans
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_j.htm [20/12/2001 11:16:49]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
K KEY_ constants : KeyEvent KEY_ events Constants KeyEvent key text properties : KeyEvent keyboard events (see also events) Constants buttons and : Button Events Checkbox component and : Checkbox Events Choice component and : Choice Events constants for each key : KeyEvent Event class constants for : Constants key variable : Variables KeyAdapter class : KeyAdapter KeyEvent class KeyEvent KeyEvent KeyListener interface : KeyListener KeyListener, KeyAdapter interfaces : KeyListener and KeyAdapter List component and : List Events listeners for (see listener interfaces) modifiers for Variables Constants Event Methods
http://localhost/java/javaref/awt/index/idx_k.htm (1 of 3) [20/12/2001 11:16:50]
Index
InputEvent KeyEvent MenuShortcut Methods key modifier text properties : KeyEvent TextArea class and : TextArea Events TextField class and : TextField Events keyboard input : The TextField and TextArea classes keyboard shortcuts MenuShortcut MenuBar Methods keyDown( ) Button component : Button Events Checkbox component : Checkbox Events Choice component and : Choice Events Component class : Component Events Event class : Constants List component : List Events TextArea class : TextArea Events TextField class : TextField Events keyEvent( ) : KeyEvent keyPressed( ) Constants KeyListener and KeyAdapter keyReleased( ) Constants KeyListener and KeyAdapter keyTyped( ) : KeyListener and KeyAdapter keyUp( ) Button component : Button Events Checkbox component : Checkbox Events Choice component and : Choice Events Component class : Component Events Event class : Constants List component : List Events http://localhost/java/javaref/awt/index/idx_k.htm (2 of 3) [20/12/2001 11:16:50]
Index
TextArea class : TextArea Events TextField class : TextField Events
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_k.htm (3 of 3) [20/12/2001 11:16:50]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
L Label( ) : Label Methods labels Label component Static Text Labels Label LabelPeer interface : LabelPeer for menu items : MenuItem Methods last( ) : CardLayout Methods lastPageFirst( ) : Methods layout( ) Component class : Component Methods ScrollPane container : ScrollPane Methods layoutContainer( ) : Methods of the LayoutManager Interface BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout GridLayout Methods GridBagLayout Methods HorizBagLayout layout : HorizBagLayout LayoutManager interface : LayoutManager Methods OrientableFlowLayout layout : OrientableFlowLayout VariableGridLayout layout : VariableGridLayout VerticalBagLayout layout : VerticalBagLayout layouts
http://localhost/java/javaref/awt/index/idx_l.htm (1 of 5) [20/12/2001 11:16:53]
Index
Layouts Layouts Other Layouts Available on the Net BorderLayout BorderLayout BorderLayout BorderLayout CardLayout CardLayout CardLayout CardLayout combining : Combining Layouts containers and : Container Methods CornerLayout (example) : A New LayoutManager: CornerLayout designing : Designing Your Own LayoutManager disabling LayoutManager : Disabling the LayoutManager FlowLayout FlowLayout FlowLayout FlowLayout GridBagConstraints class GridBagConstraints GridBagConstraints GridBagLayout GridBagLayout GridBagLayout GridBagLayout GridLayout GridLayout GridLayout GridLayout HorizBagLayout : HorizBagLayout LayoutManager interface Layouts http://localhost/java/javaref/awt/index/idx_l.htm (2 of 5) [20/12/2001 11:16:53]
Index
The LayoutManager Interface LayoutManager LayoutManager2 interface The LayoutManager2 Interface LayoutManager2 OrientableFlowLayout : OrientableFlowLayout scrollbar : ScrollPane Methods from sun.awt package : The sun.awt Layout Collection VariableGridLayout : VariableGridLayout VerticalBagLayout : VerticalBagLayout leading, font : The FontMetrics Class LEFT_ALIGNMENT constant : Component Methods LightweightPeer interface New Features of AWT in Java 1.1 The Peer Interfaces LightweightPeer line increment, scrollbars : Scrollbar Methods lines : Graphics Methods arcs : Graphics Methods connecting to form polygons : Graphics Methods width of : Graphics Methods list( ) Component class : Component Methods Container class : Container Methods List class The List class List Methods LIST_ events : List Events listener interfaces The Java 1.1 Event Model Event Listener Interfaces and Adapters AWTEventMulticaster class AWTEventMulticaster
http://localhost/java/javaref/awt/index/idx_l.htm (3 of 5) [20/12/2001 11:16:53]
Index
AWTEventMulticaster for checkbox events : Checkbox Events components and : Component Events containers and : Container Methods for list events Choice Events List Events for menu events : CheckboxMenuItem Events for menu item events : MenuItem Events for scrolling events : Scrollbar Events for text events TextComponent Events TextField Events TextField class and : TextField Events windows and : Window Events lists checkboxes (see checkboxes) List component Lists List list events Constants Choice Events List Events ListPeer interface : ListPeer pop-up : Choice LiveConnect : The Applet Tag LOADING constant : MediaTracker Methods loading images How Images are Loaded MediaTracker ImageObserver constants for : ImageObserver Interface status of (see status, loading)
http://localhost/java/javaref/awt/index/idx_l.htm (4 of 5) [20/12/2001 11:16:53]
Index
Locale class : Component Methods locate( ) Component class : Component Methods Container class : Container Methods location( ) Component class : Component Methods GridBagLayout layout : GridBagLayout Methods loop( ) : AudioClip Interface lostFocus( ) Component class : Component Events TextArea class : TextArea Events TextField class and : TextField Events lostOwnership( ) ClipboardOwner interface : ClipboardOwner Interface StringSelection class : StringSelection Methods LOST_FOCUS event Constants TextField Events TextArea Events
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_l.htm (5 of 5) [20/12/2001 11:16:53]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
M mail servers, obtaining examples by : Ftpmail makeVisible( ) : List Methods Mandelbrot program (example) : MemoryImageSource maxAscent value : The FontMetrics Class maximumLayoutSize( ) : The LayoutManager2 Interface BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods GridBagLayout layout : GridBagLayout Methods MAYSCRIPT parameter (<APPLET> tag) : The Applet Tag MediaTracker class : MediaTracker Methods memory (see also performance) color and : ColorModel garbage collection : Graphics Methods image data size : PixelGrabber MemoryImageSource class MemoryImageSource MemoryImageSource Menu( ) : Menu Methods MenuBar( ) : MenuBar Methods MenuComponent( ) : MenuComponent Methods MenuItem( ) : MenuItem Methods menus Menus Would You Like to Choose from the Menu? Putting It All Together checkboxes (see checkboxes)
http://localhost/java/javaref/awt/index/idx_m.htm (1 of 6) [20/12/2001 11:16:58]
Index
colors of : SystemColor Methods help menus : MenuBar Methods Menu class Menu Menu menu events MenuComponent Methods MenuItem Events CheckboxMenuItem Events Using Java 1.1 Events MenuBar class MenuBar MenuBar MenuBarPeer interface : MenuBarPeer MenuComponent class MenuComponent MenuComponent MenuComponentPeer interface : MenuComponentPeer MenuContainer interface MenuContainer MenuContainer MenuItem class MenuItem MenuItem MenuItemPeer interface : MenuItemPeer MenuPeer interface : MenuPeer MenuShortcut class MenuShortcut MenuShortcut pop-up (see pop-up menus) MenuShortcut( ) : MenuShortcut Methods menuText color : SystemColor Methods Meta key (see modifiers) metaDown( ) : Event Methods http://localhost/java/javaref/awt/index/idx_m.htm (2 of 6) [20/12/2001 11:16:58]
Index
methods renaming for Java 1.1 Deprecated Methods and JavaBeans Abstract Window Toolkit Overview MIME content types DataFlavor DataFlavor minimumLayoutSize( ) : Methods of the LayoutManager Interface BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout GridLayout Methods GridBagLayout Methods HorizBagLayout layout : HorizBagLayout LayoutManager interface : LayoutManager Methods OrientableFlowLayout layout : OrientableFlowLayout VerticalBagLayout layout : VerticalBagLayout minimumSize( ) Component class : Component Methods Container class : Container Methods List component : List Methods TextArea class : TextArea Methods TextField class : TextField Methods modes, FileDialog class : FileDialog Methods modifiers action event : ActionEvent getModifiers( ) InputEvent ActionEvent keyboard Variables Constants
http://localhost/java/javaref/awt/index/idx_m.htm (3 of 6) [20/12/2001 11:16:58]
Index
Event Methods InputEvent KeyEvent key modifier text properties : KeyEvent mouse button Constants Event Methods InputEvent modifiers, keyboard for menu shortcuts : MenuShortcut Methods monitor resolution : Toolkit Methods monitor size : Toolkit Methods MOUSE_ constants : MouseEvent mouse events (see also events) Constants buttom modifiers : Event Methods button modifiers Constants InputEvent clickCount variable : Variables Component class and : Component Events in Java 1.0 : Working With Mouse Buttons in Java 1.0 listeners for (see listener interfaces) MouseAdapter class : MouseAdapter MouseAdapter interfaces : MouseListener and MouseAdapter MouseEvent class MouseEvent MouseEvent MouseListener interface : MouseListener MouseListener interfaces : MouseListener and MouseAdapter MouseMotionAdapter class : MouseMotionAdapter MouseMotionAdapter interface : MouseMotionListener and MouseMotionAdapter
http://localhost/java/javaref/awt/index/idx_m.htm (4 of 6) [20/12/2001 11:16:58]
Index
MouseMotionListener class : MouseMotionListener MouseMotionListener interface : MouseMotionListener and MouseMotionAdapter scrollbars and : Scrollbar Events mouse for text selection : TextComponent Methods mouseClicked( ) : MouseListener and MouseAdapter mouseDown( ) Component class : Component Events Event class : Constants mouseDrag( ) Component class : Component Events Event class : Constants mouseDragged( ) Constants MouseMotionListener and MouseMotionAdapter mouseEnter( ) Component class : Component Events Event class : Constants mouseEntered( ) Constants MouseListener and MouseAdapter MouseEvent( ) : MouseEvent mouseExit( ) Component class : Component Events Event class : Constants mouseExited( ) Constants MouseListener and MouseAdapter mouseMove( ) Component class : Component Events Event class : Constants mouseMoved( ) Constants MouseMotionListener and MouseMotionAdapter mousePressed( ) http://localhost/java/javaref/awt/index/idx_m.htm (5 of 6) [20/12/2001 11:16:58]
Index
Constants MouseListener and MouseAdapter mouseReleased( ) Constants MouseListener and MouseAdapter mouseUp( ) Component class : Component Events Event class : Constants move( ) Component class : Component Methods Point class : Point Methods multiline input (see text, TextArea class) multimedia : MediaTracker MediaTracker class MediaTracker Methods MediaTracker multithreading (see threads)
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_m.htm (6 of 6) [20/12/2001 11:16:58]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
N names clipboards : Clipboard Methods of components : Component Methods of data flavors (MIME types) : DataFlavor Methods of fonts : The Font Class menu components : MenuComponent Methods NAME parameter <APPLET> tag : The Applet Tag tag : The Applet Tag Netscape Navigator : Abstract Window Toolkit Overview FileDialog class and : FileDialog newPixels( ) : MemoryImageSource newsgroups, Java-related : Other Java Books and Resources next( ) : CardLayout Methods nextFocus( ) : Component Methods normalizeMimeType( ) : DataFlavor Methods normalizeMimeTypeParameter( ) : DataFlavor Methods
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_n.htm [20/12/2001 11:16:59]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
O OBJECT parameter (<APPLET> tag) : The Applet Tag objects image (see images) positioning and sizing : Component Methods obtaining source code : About the Source Code OffScreenImageSource class : A Brief Tour of sun.awt.image OrientableFlowLayout layout : OrientableFlowLayout orientHorizontally( ) : OrientableFlowLayout orientVertically( ) : OrientableFlowLayout origin coordinate space : Graphics Methods GridBagLayout layout : GridBagLayout Methods ovals : Graphics Methods overriding (see action( )) action( ) (see action( )) handleEvent( ) : Overriding handleEvent() imageUpdate( ) : Overriding imageUpdate owner, clipboard ClipboardOwner Interface ClipboardOwner owner, contents : Clipboard Methods
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_o.htm [20/12/2001 11:17:00]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
P pack( ) : Window Methods padding around components : GridBagConstraints Methods paging increment, scrollbars : Scrollbar Methods paint( ) Canvas class : Canvas Methods Component class Graphics Component Methods Container class : Container Methods paint mode : Graphics Methods PAINT, PAINT_ constants : PaintEvent paintAll( ) : Component Methods paintComponents( ) : Container Methods PaintEvent class PaintEvent PaintEvent painting (see graphics) Panel( ) : Panel Methods PanelPeer interface : PanelPeer panels CardLayout layout for CardLayout CardLayout CardLayout FlowLayout layout for FlowLayout
http://localhost/java/javaref/awt/index/idx_p.htm (1 of 7) [20/12/2001 11:17:03]
Index
FlowLayout FlowLayout OrientableFlowLayout layout for : OrientableFlowLayout Panel class Panel Panel tag (HTML) The Applet Tag Applet Methods paramString( ) ActionEvent class : ActionEvent AdjustmentEvent class : AdjustmentEvent AWTEvent class : AWTEvent Button component : Button Methods Checkbox component : Checkbox Methods CheckboxMenuItem class : CheckboxMenuItem Methods Choice component : Component Methods Component class : Component Methods ComponentEvent class : ComponentEvent Container class : Container Methods ContainerEvent class : ContainerEvent Dialog class : Dialog Constructors and Methods Event class : Event Methods FileDialog class : FileDialog Methods FocusEvent class : FocusEvent Frame class : Frame Methods ItemEvent class : ItemEvent KeyEvent class : KeyEvent Label component : Label Methods List component : List Methods Menu class : Menu Methods MenuComponent class : MenuComponent Methods MenuItem class : MenuItem Methods
http://localhost/java/javaref/awt/index/idx_p.htm (2 of 7) [20/12/2001 11:17:03]
Index
MenuShortcut class : MenuShortcut Methods MouseEvent class : MouseEvent PaintEvent class : PaintEvent Scrollbar class : Scrollbar Methods ScrollPane container : ScrollPane Methods TextArea class : TextArea Methods TextComponent class : TextComponent Methods TextEvent class : TextEvent TextField class : TextField Methods WindowEvent class : WindowEvent peekEvent( ) : Using an event multicaster peers Peers The Peer Interfaces ButtonPeer Container class and : Component Methods Font class and : The Font Class performance colors and : ColorModel deleting applets and : Applet Methods Graphics objects and : Graphics Methods MediaTracker and : MediaTracker Methods PixelGrabber class PixelGrabber PixelGrabber pixels (see images) PLAIN constant : The Font Class platforms colors and Color ColorModel event handling and : Comprehensive Event List events and : Platform-Specific Event Handling font ascent and : The FontMetrics Class http://localhost/java/javaref/awt/index/idx_p.htm (3 of 7) [20/12/2001 11:17:03]
Index
layouts and : Layouts modifier keys and : Constants peer architecture : Peers scrolling events and : Scrollbar Events Toolkit class Toolkit Toolkit play( ) Applet class : Applet Methods AudioClip interface : AudioClip Interface points (see also coordinates) adding to polygons : Polygon Methods contained in rectangles : Rectangle Methods Point class Point Point polygons Graphics Methods Polygon Polygon class Polygon Methods Polygon pop-up lists : Choice pop-up menus The PopupMenu class PopupMenu PopupMenu class New Features of AWT in Java 1.1 PopupMenu Methods PopupMenu PopupMenuPeer interface : PopupMenuPeer portability : Abstract Window Toolkit Overview events and : Comprehensive Event List
http://localhost/java/javaref/awt/index/idx_p.htm (4 of 7) [20/12/2001 11:17:03]
Index
positioning objects : Component Methods postEvent( ) Passing the Buck Using an event multicaster Component class : Component Events MenuComponent class : MenuComponent Methods MenuContainer interface : MenuContainer Methods Window class : Window Events PPMImageDecoder class (example) : ImageConsumer Interface predefined colors Color Methods SystemColor Using Desktop Colors preferredLayoutSize( ) : Methods of the LayoutManager Interface BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout GridLayout Methods GridBagLayout Methods HorizBagLayout layout : HorizBagLayout LayoutManager interface : LayoutManager Methods OrientableFlowLayout layout : OrientableFlowLayout VerticalBagLayout layout : VerticalBagLayout preferredSize( ) Component class : Component Methods Container class : Container Methods List component : List Methods TextArea class : TextArea Methods TextField class : TextField Methods prepareImage( ) Component class : Component Methods Toolkit class : Toolkit Methods previous( ) : CardLayout Methods http://localhost/java/javaref/awt/index/idx_p.htm (5 of 7) [20/12/2001 11:17:03]
Index
print( ) Component class Component Methods Component Methods Container class : Container Methods printAll( ) Component class Component Methods Component Methods printComponents( ) Component class : Component Methods Container class : Container Methods ScrollPane container : ScrollPane Methods printing Printing Printing PrintGraphics interface PrintGraphics Interface PrintGraphics PrintJob class PrintJob Class PrintJob Toolkit class and : Toolkit Methods priority, loading multimedia objects : MediaTracker Methods processActionEvent( ) : Button Events List component : List Events MenuItem class : MenuItem Events TextField class : TextField Events processAdjustmentEvent( ) Scrollbar class : Scrollbar Events processComponentEvent( ) : Component Events processContainerEvent( ) : Container Methods processEvent( ) button component : Button Events http://localhost/java/javaref/awt/index/idx_p.htm (6 of 7) [20/12/2001 11:17:03]
Index
Checkbox component : Checkbox Events Choice component : Choice Events Component class : Component Events Container class : Container Methods List component : List Events Menu class : CheckboxMenuItem Events MenuComponent class : MenuComponent Methods MenuItem class : MenuItem Events Scrollbar class : Scrollbar Events TextComponent class : TextComponent Events TextField class : TextField Events Window class : Window Events processFocusEvent( ) : Component Events processItemEvent( ) Checkbox component : Checkbox Events Choice component : Choice Events List component : List Events Menu class : CheckboxMenuItem Events processKeyEvent( ) : Component Events processMouseEvent( ) : Component Events processMouseMotionEvent( ) : Component Events processTextEvent( ) : TextComponent Events processWindowEvent( ) : Window Events properties color : Color Methods font : The Font Class image : Image Methods printing : Toolkit Methods pull-down lists (see pop-up lists; pop-up menus)
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved. http://localhost/java/javaref/awt/index/idx_p.htm (7 of 7) [20/12/2001 11:17:03]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Q queue (see events, event queue) event (see events, event queue) listener (see AWTEventMulticaster class)
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_q.htm [20/12/2001 11:17:04]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
R radio buttons : The Checkbox and CheckboxGroup classes raised rectangles : Graphics Methods RANDOMPIXELORDER constant : ImageConsumer Interface read( ) AudioStream class : AudioStream AudioStreamSequence class : AudioStreamSequence ContinuousAudioDataStream class : ContinuousAudioDataStream read-only text : TextComponent Methods rectangles bounding an object : Component Methods copying : Graphics Methods determining size of : Shape Method as drawing area Graphics Methods filling Graphics Methods intersections with : Rectangle Methods raised (with shadow effect) : Graphics Methods Rectangle class Rectangle Rectangle for repainting : PaintEvent with rounded corners : Graphics Methods size of Rectangle Methods red (color)
http://localhost/java/javaref/awt/index/idx_r.htm (1 of 5) [20/12/2001 11:17:07]
Index
Color Methods ColorModel Methods DirectColorModel IndexColorModel redrawrate parameter : Component Methods RELATIVE constant : GridBagConstraints Methods REMAINDER constant : GridBagConstraints Methods remove( ) AWTEventMulticaster class : AWTEventMulticaster Choice component : Component Methods Component class : Component Methods Container class : Container Methods Frame class : Frame Methods List component : List Methods Menu class : Menu Methods MenuBar class : MenuBar Methods MenuContainer interface : MenuContainer Methods remove listener interfaces : AWTEventMulticaster removeActionListener( ) Button class : Button Events List component : List Events MenuItem class : MenuItem Events TextField class : TextField Events removeAdjustmentListener( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Events removeAll( ) Choice component : Component Methods Container class : Container Methods List component : List Methods Menu class : Menu Methods removeComponentListener( ) : Component Events removeConsumer( ) FilteredImageSource class : FilteredImageSource http://localhost/java/javaref/awt/index/idx_r.htm (2 of 5) [20/12/2001 11:17:07]
Index
ImageProducer interface : ImageProducer Interface MemoryImageSource class : MemoryImageSource removeContainerListener( ) : Container Methods removeFocusListener( ) : Component Events removeImage( ) : MediaTracker Methods removeInternal( ) : AWTEventMulticaster removeItemListener( ) Checkbox component : Checkbox Events Choice component : Choice Events List component : List Events Menu class : CheckboxMenuItem Events removeKeyListener( ) : Component Events removeLayoutComponent( ) BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout GridLayout Methods GridBagLayout Methods HorizBagLayout layout : HorizBagLayout LayoutManager interface Methods of the LayoutManager Interface LayoutManager Methods VerticalBagLayout layout : VerticalBagLayout removeMouseListener( ) : Component Events removeMouseMotionListener( ) : Component Events removeNotify( ) Container class Component Methods Container Methods List component : List Methods Menu class : Menu Methods MenuBar class : MenuBar Methods MenuComponent class : MenuComponent Methods http://localhost/java/javaref/awt/index/idx_r.htm (3 of 5) [20/12/2001 11:17:07]
Index
TextComponent class : TextComponent Methods removeTextListener( ) : TextComponent Events removeWindowListener( ) : Window Events repaint( ) : Component Methods replaceItem( ) : List Methods replaceRange( ) : TextArea Methods replaceText( ) : TextArea Methods ReplicateScaleFilter( ) : ReplicateScaleFilter ReplicateScaleFilter class Graphics Methods ReplicateScaleFilter ReplicateScaleFilter requestFocus( ) : Component Methods requestTopDownLeftRightResend( ) FilteredImageSource class : FilteredImageSource ImageProducer interface : ImageProducer Interface MemoryImageSource class : MemoryImageSource resendTopDownLeftRight( ) : ImageFilter Methods resetting images : Image Methods reshape( ) : Component Methods resize( ) Applet class : Applet Methods Component class : Component Methods resolution, monitor : Toolkit Methods resources for further reading : Other Java Books and Resources resources, system (see performance) RGB colors Color Methods SystemColor Methods ColorModel Methods DirectColorModel RGBImageFilter class RGBImageFilter
http://localhost/java/javaref/awt/index/idx_r.htm (4 of 5) [20/12/2001 11:17:07]
Index
RGBImageFilter RGBtoGSB( ) : Color Methods RIGHT_ALIGNMENT constant : Component Methods rounded corners : Graphics Methods rowHeights[ ] variable : GridBagLayout Methods rows (see alignment) rowWeights[ ] variable : GridBagLayout Methods
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_r.htm (5 of 5) [20/12/2001 11:17:07]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
S sample programs, obtaining : Obtaining the Example Programs SCALE_ hints : Image Methods screen resolution : Toolkit Methods screen size : Toolkit Methods SCROLL_ events : Scrollbar Events Scrollbar( ) : Scrollbar Methods SCROLLBARS_ constants : ScrollPane Methods scrolling : Scrolling Adjustable interface The Adjustable Interface Adjustable images (example) : Scrolling An Image with multiline text input : TextArea Scrollbar class The Scrollbar class Scrollbar Scrollbar scrollbar color : SystemColor Methods ScrollbarPeer interface : ScrollbarPeer scrolling events Constants Scrollbar Events Using a ScrollPane ScrollPane class : ScrollPane ScrollPane container : ScrollPane
http://localhost/java/javaref/awt/index/idx_s.htm (1 of 10) [20/12/2001 11:17:11]
Index
ScrollPanePeer interface : ScrollPanePeer ScrollPane container New Features of AWT in Java 1.1 The Scrollbar class ScrollPane select( ) Choice component : Component Methods List component : List Methods TextComponent class : TextComponent Methods selectAll( ) : TextComponent Methods SELECTED constant : ItemEvent separator menu items : Menu Methods setActionCommand( ) Button component : Button Methods MenuItem class : MenuItem Events setAlignment( ) FlowLayout layout : FlowLayout Methods Label component : Label Methods setAnimated( ) : MemoryImageSource setBackground( ) : Component Methods setBlockIncrement( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods setBounds( ) Component class : Component Methods Rectangle class : Rectangle Methods setCaretPosition( ) TextComponent Methods IllegalComponentStateException setCheckboxGroup( ) : Checkbox Methods setClip( ) : Graphics Methods setColFraction( ) : VariableGridLayout setColor( ) : Graphics Methods setColorModel( ) http://localhost/java/javaref/awt/index/idx_s.htm (2 of 10) [20/12/2001 11:17:11]
Index
ImageConsumer interface : ImageConsumer Interface ImageFilter class : ImageFilter Methods PixelGrabber class : PixelGrabber RGBImageFilter class : RGBImageFilter setColumns( ) GridLayout layout : GridLayout Methods TextArea class : TextArea Methods TextField class : TextField Methods setConstraints( ) : GridBagLayout Methods setContents( ) : Clipboard Methods setCurrent( ) : CheckboxGroup Methods setCursor( ) Component class : Component Methods Frame class : Frame Methods setDimensions( ) CropImageFilter class : CropImageFilter ImageConsumer interface : ImageConsumer Interface ImageFilter class : ImageFilter Methods PixelGrabber class : PixelGrabber ReplicateScaleFilter class : ReplicateScaleFilter setDirectory( ) : FileDialog Methods setEchoChar( ) : TextField Methods setEchoCharacter( ) : TextField Methods setEditable( ) : TextComponent Methods setEnabled( ) Container class : Component Methods MenuItem class : MenuItem Methods setFile( ) : FileDialog Methods setFilenameFilter( ) : FileDialog Methods setFont( ) Component class : Component Methods Graphics class : Graphics Methods MenuComponent class : MenuComponent Methods
http://localhost/java/javaref/awt/index/idx_s.htm (3 of 10) [20/12/2001 11:17:11]
Index
setForeground( ) : Component Methods setFullBufferUpdates( ) : MemoryImageSource setHelpMenu( ) : MenuBar Methods setHgap( ) BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout : GridLayout Methods setHints( ) AreaAveragingScaleFilter class : AreaAveragingScaleFilter ImageConsumer interface : ImageConsumer Interface ImageFilter class : ImageFilter Methods PixelGrabber class : PixelGrabber setHumanPresentableName( ) : DataFlavor Methods setIconImage( ) : Frame Methods setKeyCode( ) : KeyEvent setLabel( ) Button class : Button Methods Checkbox component : Checkbox Methods MenuItem class : MenuItem Methods setLayout( ) Container class : Container Methods ScrollPane container : ScrollPane Methods setLineIncrement( ) : Scrollbar Methods setLocale( ) : Component Methods setLocation( ) Component class : Component Methods Point class : Point Methods Rectangle class : Rectangle Methods setMaximum( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods setMenuBar( ) : Frame Methods setMinimum( ) http://localhost/java/javaref/awt/index/idx_s.htm (4 of 10) [20/12/2001 11:17:11]
Index
Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods setModal( ) : Dialog Constructors and Methods setMode( ) : FileDialog Methods setModifiers( ) : KeyEvent setMultipleMode( ) : List Methods setMultipleSelections( ) : List Methods setName( ) : Component Methods setOrientation( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods setPageIncrement( ) : Scrollbar Methods setPaintMode( ) : Graphics Methods setPixels( ) AreaAveragingScaleFilter class : AreaAveragingScaleFilter CropImageFilter class : CropImageFilter ImageConsumer interface : ImageConsumer Interface ImageFilter class : ImageFilter Methods PixelGrabber class : PixelGrabber ReplicateScaleFilter class : ReplicateScaleFilter RGBImageFilter class : RGBImageFilter setProperties( ) CropImageFilter class : CropImageFilter ImageConsumer interface : ImageConsumer Interface ImageFilter class : ImageFilter Methods PixelGrabber class : PixelGrabber ReplicateScaleFilter class : ReplicateScaleFilter setResizable( ) Dialog class : Dialog Constructors and Methods Frame classM : Frame Methods setRowFraction( ) : VariableGridLayout setRows( ) GridLayout layout : GridLayout Methods TextArea class : TextArea Methods http://localhost/java/javaref/awt/index/idx_s.htm (5 of 10) [20/12/2001 11:17:11]
Index
setScrollPosition( ) : ScrollPane Methods setSelectedCheckbox( ) : CheckboxGroup Methods setSelectionEnd( ) : TextComponent Methods setSelectionStart( ) : TextComponent Methods setShortcut( ) : MenuItem Methods setSize( ) Component class : Component Methods Dimension class : Dimension Methods Rectangle class : Rectangle Methods setState( ) Checkbox component : Checkbox Methods CheckboxMenuItem class : CheckboxMenuItem Methods setStub( ) : Applet Methods setText( ) : Label Methods TextComponent class : TextComponent Methods setTitle( ) : Frame Methods Dialog class : Dialog Constructors and Methods setUnitIncrement( ) : Scrollbar Methods Adjustable interface : Methods of the Adjustable Interface setValue( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods setValues( ) : Scrollbar Methods setVgap( ) BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods FlowLayout layout : FlowLayout Methods GridLayout layout : GridLayout Methods setVisible( ) : Component Methods setVisibleAmount( ) Adjustable interface : Methods of the Adjustable Interface Scrollbar class : Scrollbar Methods setXORMode( ) : Graphics Methods shadow colors http://localhost/java/javaref/awt/index/idx_s.htm (6 of 10) [20/12/2001 11:17:11]
Index
Color Methods SystemColor Methods Displaying Colors shapes : Graphics Methods checkboxes : Checkbox Methods of cursors Cursor Constants Frame Constants polygons Graphics Methods Polygon Polygon rectangles (see rectangles) Shape interface Shape Shape Shift key (see modifiers) shiftDown( ) : Event Methods shortcuts( ) : MenuBar Methods shortcuts, menu MenuShortcut MenuBar Methods MenuShortcut show( ) CardLayout layout : CardLayout Methods Component class : Component Methods Dialog class : Dialog Constructors and Methods PopupMenu class : PopupMenu Methods Window class : Window Methods showDocument( ) : AppletContext Interface showing, component : Component Methods showStatus( ) Applet class : Applet Methods
http://localhost/java/javaref/awt/index/idx_s.htm (7 of 10) [20/12/2001 11:17:11]
Index
AppletContext interface : AppletContext Interface single-line input (see text, TextField class) SINGLEFRAME constant : ImageConsumer Interface SINGLEFRAMEDONE constant : ImageConsumer Interface SINGLEPASS constant : ImageConsumer Interface size applets Applet Methods AppletStub Interface audio data length : AudioStream color map : IndexColorModel components Container Methods Methods of the LayoutManager Interface cropping images : CropImageFilter Dimension class for : Dimension Methods font Fonts The Font Class character width : The FontMetrics Class font height : The FontMetrics Class HEIGHT, WIDTH parameters (<APPLET> tag) : The Applet Tag image Image Methods ImageObserver Interface ImageConsumer Interface image data : PixelGrabber line width : Graphics Methods monitor (screen) : Toolkit Methods objects, components for : Component Methods pixel : ColorModel Methods rectangle Rectangle Methods scrollbars : ScrollPane Methods http://localhost/java/javaref/awt/index/idx_s.htm (8 of 10) [20/12/2001 11:17:11]
Index
string length in pixels : The FontMetrics Class text input objects : TextField Methods SizedTextField class (example) : Extending TextField SOMEBITS constant : ImageObserver Interface sources, image : A Brief Tour of sun.awt.image start( ) Applet class : Applet Methods AudioPlayer class : AudioPlayer startGrabbing( ) : PixelGrabber startProduction( ) FilteredImageSource class : FilteredImageSource ImageProducer interface : ImageProducer Interface MemoryImageSource class : MemoryImageSource state checkbox : Checkbox Methods checkbox menu items : CheckboxMenuItem Methods component : Component Methods STATICIMAGEDONE constant : ImageConsumer Interface status applet Applet Methods AppletStub Interface browser status line Applet Methods AppletContext Interface image grabbing : PixelGrabber loading MediaTracker Methods ImageObserver Interface Toolkit Methods status( ) : PixelGrabber statusAll( ) : MediaTracker Methods statusID( ) : MediaTracker Methods stop( ) http://localhost/java/javaref/awt/index/idx_s.htm (9 of 10) [20/12/2001 11:17:11]
Index
Applet class : Applet Methods AudioClip interface : AudioClip Interface AudioPlayer class : AudioPlayer strings Graphics Methods pixel length of : The FontMetrics Class StringSelection class StringSelection StringSelection toString( ) (see toString( )) stringWidth( ) : The FontMetrics Class style, font (see fonts) substituteColorModel( ) : RGBImageFilter sun.awt package, layouts from : The sun.awt Layout Collection sync( ) : Toolkit Methods synchronization containers and : Container Methods image grabbing and : PixelGrabber SystemColor class SystemColor SystemColor
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_s.htm (10 of 10) [20/12/2001 11:17:11]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
T target, event Identifying the Target Variables text color of SystemColor Methods inserting with carets : TextComponent Methods read-only : TextComponent Methods selecting with mouse : TextComponent Methods style of (see fonts) text strings : Graphics Methods TextArea class The TextField and TextArea classes TextArea TextArea TextAreaPeer interface : TextAreaPeer TextComponent class Text Component TextComponent TextComponentPeer interface : TextComponentPeer TextEvent class TextEvent TextEvent TextField class The TextField and TextArea classes TextField
http://localhost/java/javaref/awt/index/idx_t.htm (1 of 4) [20/12/2001 11:17:12]
Index
Extending TextField TextField TextFieldPeer interface : TextFieldPeer TextListener interface TextListener TextListener TEXT_ constants : TextEvent textHighlight color : SystemColor Methods textHighlightText color : SystemColor Methods textInactiveText color : SystemColor Methods textText color : SystemColor Methods textValueChanged( ) : TextListener themes, color : SystemColor threads, animation and : Simple Animation throwing errors/exceptions (see errors; exceptions) time and date of events Variables InputEvent pause between image repaints : Component Methods toBack( ) : Window Methods toFront( ) : Window Methods Toolkit( ) : Toolkit Methods Toolkit class Toolkit Toolkit TOPDOWNLEFTRIGHT constant : ImageConsumer Interface TOP_ALIGNMENT constant : Component Methods toString( ) AWTEvent class : AWTEvent BorderLayout layout : BorderLayout Methods CardLayout layout : CardLayout Methods CheckboxGroup class : CheckboxGroup Methods
http://localhost/java/javaref/awt/index/idx_t.htm (2 of 4) [20/12/2001 11:17:12]
Index
Color class : Color Methods Component class : Component Methods Dimension class : Dimension Methods Event method : Event Methods FlowLayout layout : FlowLayout Methods Font class : The Font Class FontMetrics class : The FontMetrics Class Graphics class : Graphics Methods GridBagLayout layout : GridBagLayout Methods GridLayout layout : GridLayout Methods HorizBagLayout layout : HorizBagLayout Insets class : Insets Methods MenuComponent class : MenuComponent Methods MenuShortcut class : MenuShortcut Methods OrientableFlowLayout layout : OrientableFlowLayout Point class : Point Methods Rectangle class : Rectangle Methods SystemColor class : SystemColor Methods VariableGridLayout layout : VariableGridLayout VerticalBagLayout layout : VerticalBagLayout TRACK constant : AdjustmentEvent Transferable interface Transferable Interface Transferable transferFocus( ) : Component Methods translate( ) Event method : Event Methods Graphics class : Graphics Methods Point class : Point Methods Rectangle class Rectangle Methods Polygon Methods translatePoint( ) : MouseEvent
http://localhost/java/javaref/awt/index/idx_t.htm (3 of 4) [20/12/2001 11:17:12]
Index
transparency : Graphics Methods
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_t.htm (4 of 4) [20/12/2001 11:17:12]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
U UndefinedProperty constant : Image Methods underlining : The Font Class union( ) : Rectangle Methods UNIT_ constants : AdjustmentEvent UnsupportedFlavorException exception UnsupportedFlavorException UnsupportedFlavorException update( ) : Simple Animation Component class Graphics Component Methods UPDATE constant : PaintEvent URLImageSource class : A Brief Tour of sun.awt.image URLs, special : AppletContext Interface user groups, Java : Other Java Books and Resources useShiftModifier( ) : MenuShortcut Methods UUCP, obtaining examples by : UUCP
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_u.htm [20/12/2001 11:17:14]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
V validate( ) Component class : Component Methods Container class : Container Methods validateTree( ) : Container Methods validity, component : Component Methods VALUE parameter ( tag) : The Applet Tag VariableGridLayout layout : VariableGridLayout versions AWT Preface Abstract Window Toolkit Overview Java : Preface vertical alignment (see alignment) font height : The FontMetrics Class gaps (see gap settings) scrollbars (see scrolling) size (see size) VerticalBagLayout layout : VerticalBagLayout visibility component : Component Methods list items : List Methods scrollbar TextArea Methods Scrollbar Methods Methods of the Adjustable Interface
http://localhost/java/javaref/awt/index/idx_v.htm (1 of 2) [20/12/2001 11:17:18]
Index
VK_ constants : KeyEvent VSPACE parameter (<APPLET> tag) : The Applet Tag
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_v.htm (2 of 2) [20/12/2001 11:17:18]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
W waitForAll( ) : MediaTracker Methods waitForID( ) : MediaTracker Methods Web browsers (see browsers) when variable : Variables width (see size) WIDTH parameter (<APPLET> tag) : The Applet Tag Window( ) : Window Methods WINDOW_ constants : WindowEvent Window container : Windows windowActivated( ) : WindowListener and WindowAdapter windowBorder color : SystemColor Methods windowClosed( ) : WindowListener and WindowAdapter windowClosing( ) Constants WindowListener and WindowAdapter windowDeactivated( ) : WindowListener and WindowAdapter windowDeiconified( ) Constants WindowListener and WindowAdapter WindowEvent( ) : WindowEvent windowIconified( ) Constants WindowListener and WindowAdapter windowOpened( ) : WindowListener and WindowAdapter windowOpening( ) : Constants windows
http://localhost/java/javaref/awt/index/idx_w.htm (1 of 2) [20/12/2001 11:17:19]
Index
Windows Window Building a New Component from a Window BorderLayout layout for BorderLayout BorderLayout BorderLayout colors for : SystemColor Methods Window class Window Methods Window window events : Constants WindowAdapter class : WindowAdapter WindowEvent class WindowEvent WindowEvent WindowListener interface WindowListener and WindowAdapter WindowListener WindowPeer interface : WindowPeer
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_w.htm (2 of 2) [20/12/2001 11:17:19]
Index
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
X XOR mode : Graphics Methods
A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/awt/index/idx_x.htm [20/12/2001 11:17:21]
Examples for Examples for Java AWT
Examples for Java AWT ●
labels.java
●
labels.htm
●
labels.class
●
texts.java
●
texts.htm
●
texts.class
●
checkboxes.htm
●
checkboxes.class
●
checkboxes.java
●
choicebox.java
●
choicebox.class
●
choicebox.htm
●
listex.class
●
listex.java
●
listex.htm
●
simpleMenu.java
●
simpleMenu.class
●
PopupTest.htm
●
PopupTest.java
●
PopupTest.class
●
scroll.htm
●
scroll.java
●
scroll.class
●
ImageCanvas.class
●
buttonex.htm
●
buttonex.java
●
buttonex.class
http://localhost/java/javaref/awt/examples/chap1/index.htm (1 of 2) [20/12/2001 11:17:24]
Examples for Examples for Java AWT
●
CardLayoutTest.java
●
CardLayoutTest.htm
●
CardLayoutTest.class
●
CardPanel.class
●
GRIDBAG.GIF
●
gridbag.java
●
gridbag.class
●
gridbag.htm
●
panelex.class
●
panelex.java
●
panelex.htm
●
frameex.class
●
frameex.java
●
dialogex.class
●
star.class
●
windowex.java
●
windowex.class
●
star.java
●
star.htm
http://localhost/java/javaref/awt/examples/chap1/index.htm (2 of 2) [20/12/2001 11:17:24]
Examples for Examples for Java AWT
Examples for Java AWT ●
clipping.java
●
clipping.htm
●
clipping.class
●
xor.htm
●
xor.java
●
xor.class
●
drawingLines.java
●
drawingLines.class
●
arcZoom.class
●
arcZoom.java
●
arcZoom.htm
●
drawingRects.java
●
drawingRects.class
●
drawing3dRects.java
●
drawing3dRects.class
●
drawingOvals.java
●
drawingOvals.class
●
drawingArcs.class
●
drawingArcs.java
●
drawingPoly.java
●
drawingPoly.class
●
drawingImages.java
●
drawingImages.class
●
drawingImages.htm
●
drawingImages11.java
●
drawingImages11.htm
●
drawingImages11.class
http://localhost/java/javaref/awt/examples/chap2/index.htm (1 of 3) [20/12/2001 11:17:26]
Examples for Examples for Java AWT
●
rosey.jpg
●
rosey.gif
●
rect.java
●
rect.class
●
intersection.java
●
intersection.class
●
union.java
●
union.class
●
flushMe.java
●
flushMe.class
●
flush.gif
●
foo.gif
●
Animate.java
●
Animate.class
●
clock1.jpg
●
clock2.jpg
●
clock3.jpg
●
clock4.jpg
●
clock5.jpg
●
clock6.jpg
●
clock7.jpg
●
clock8.jpg
●
clock9.jpg
●
clock10.jpg
●
clock11.jpg
●
clock0.jpg
●
AnimateApplet.java
●
AnimateApplet.class
●
AnimateApplet.htm
●
buffering.java
●
buffering.class
●
buffering.htm
http://localhost/java/javaref/awt/examples/chap2/index.htm (2 of 3) [20/12/2001 11:17:26]
Examples for Examples for Java AWT
http://localhost/java/javaref/awt/examples/chap2/index.htm (3 of 3) [20/12/2001 11:17:26]
Examples for Examples for Java AWT
Examples for Java AWT ●
metrics.class
●
metrics.java
●
Center.java
●
Center.class
●
Display.java
●
Display.class
●
ColorDisplay.java
●
ColorDisplay.class
●
TextBox3D.java
●
TextBox3D.class
●
Text3DTest.java
●
Text3DTest.class
●
Text3DTest.htm
http://localhost/java/javaref/awt/examples/chap3/index.htm [20/12/2001 11:17:27]
Examples for Examples for Java AWT
Examples for Java AWT ●
mouseEvent.java
●
mouseEvent.class
●
mouseEvent.htm
●
mouseEvent11.java
●
mouseEvent11.htm
●
mouseEvent11.class
●
GetSetString.class
●
UpDownCatcher.class
●
ItemFrame.java
●
ItemFrame.class
●
ItemEventComponent.class
http://localhost/java/javaref/awt/examples/chap4/index.htm [20/12/2001 11:17:28]
Examples for Examples for Java AWT
Examples for Java AWT ●
labels.java
●
labels.htm
●
labels.class
●
TheButton.class
●
ButtonTest.java
●
ButtonTest.htm
●
ButtonTest.class
●
ButtonTest11.java
●
ButtonTest11.class
●
ButtonTest11.htm
●
MyMouseAdapter.class
●
JavaCalc.java
●
JavaCalc.htm
●
JavaCalc.class
●
VerticalLabel.java
●
VerticalLabel.class
●
vlabels.class
●
vlabels.java
●
vlabels.htm
http://localhost/java/javaref/awt/examples/chap5/index.htm [20/12/2001 11:17:31]
Examples for Examples for Java AWT
Examples for Java AWT ●
LightweightPanel.java
●
LightweightPanel.class
●
NewButtonTest11.java
●
NewButtonTest11.class
●
NewButtonTest11.htm
●
myInsets.java
●
myInsets.class
●
myInsets.htm
●
ComponentUtilities.java
●
ComponentUtilities.class
●
PopupButtonFrame.java
●
PopupButtonFrame.class
●
PopupWindow.class
●
rosey.jpg
●
modeTest.class
●
modeTest11.class
●
modeFrame.java
●
modeFrame.class
●
modeFrame11.java
●
modeFrame11.class
●
DialogHandler.class
●
FdTest.java
●
FdTest.class
http://localhost/java/javaref/awt/examples/chap6/index.htm [20/12/2001 11:17:32]
Examples for Examples for Java AWT
Examples for Java AWT ●
buttons.class
●
buttons.htm
●
buttons.java
●
CardExample.java
●
CardExample.class
●
CardExample.htm
●
multi.class
●
multi.java
●
multi.htm
●
noLayout.htm
●
noLayout.java
●
noLayout.class
●
CornerLayout2.java
●
CornerLayout.java
●
cornertexts.java
●
cornertexts.htm
●
CornerLayout.class
●
cornertexts.class
●
CornerLayout2.class
●
horizbag.java
●
horizbag.htm
●
horizbag.class
●
vertbag.java
●
vertbag.class
●
vertbag.htm
●
vargrid.class
●
vargrid.htm
http://localhost/java/javaref/awt/examples/chap7/index.htm (1 of 2) [20/12/2001 11:17:33]
Examples for Examples for Java AWT
●
vargrid.java
●
buttonorient.java
●
buttonorient.htm
●
buttonorient.class
http://localhost/java/javaref/awt/examples/chap7/index.htm (2 of 2) [20/12/2001 11:17:33]
Examples for Examples for Java AWT
Examples for Java AWT ●
readonly.java
●
readonly.class
●
readonly.htm
●
text13.java
●
text13.class
●
text13.htm
●
TextFieldSetter.class
●
texts.java
●
texts.class
●
texts.htm
●
text11.java
●
text11.class
●
text11.htm
●
MyAL.class
●
text12.java
●
text12.class
●
text12.htm
●
MyTextField.class
●
textas.java
●
textas.htm
●
textas.class
●
Rot13.class
●
textas11.java
●
textas11.class
●
textas11.htm
●
Rot13.java
●
SizedTextField.java
http://localhost/java/javaref/awt/examples/chap8/index.htm (1 of 2) [20/12/2001 11:17:34]
Examples for Examples for Java AWT
●
SizedTextField.class
●
sizetext.java
●
sizetext.class
●
sizetext.htm
http://localhost/java/javaref/awt/examples/chap8/index.htm (2 of 2) [20/12/2001 11:17:34]
Examples for Examples for Java AWT
Examples for Java AWT ●
choice11.java
●
choice11.class
●
choice11.htm
●
MyChoice11.class
●
list3.java
●
list3.htm
●
list3.class
http://localhost/java/javaref/awt/examples/chap9/index.htm [20/12/2001 11:17:36]
Examples for Examples for Java AWT
Examples for Java AWT ●
imageUpdateOver.java
●
imageUpdateOver.htm
●
imageUpdateOver.class
●
rosey.jpg
●
MemoryImage.java
●
MemoryImage.htm
●
MemoryImage.class
●
Mandelbrot.java
●
Mandelbrot.htm
●
Mandelbrot.class
●
PPMImageDecoder.java
●
PPMImageDecoder.class
●
ppmViewer.class
●
ppmViewer.htm
●
ppmViewer.java
●
rosey.ppm
●
flip.java
●
flip.class
●
flip.htm
●
ora-icon.gif
●
grab.java
●
grab.class
●
grab.htm
●
BlurFilter.class
●
BlurFilter.java
●
DynamicFilter.java
●
DynamicFilter.class
http://localhost/java/javaref/awt/examples/chap12/index.htm (1 of 2) [20/12/2001 11:17:39]
Examples for Examples for Java AWT
●
DynamicImages.java
●
dynamicImages.class
●
dynamicImages.htm
●
TransparentImageFilter.class
●
TransparentImageFilter.java
●
Crop.java
●
Crop.htm
●
Crop.class
●
GrayImageFilter.class
●
GrayImageFilter.java
●
DrawingImages.java
●
DrawingImages.htm
●
DrawingImages.class
●
AvgFilt.java
●
AvgFilt.class
●
AvgFilt.htm
http://localhost/java/javaref/awt/examples/chap12/index.htm (2 of 2) [20/12/2001 11:17:39]
Examples for Examples for Java AWT
Examples for Java AWT ●
ChangeMenu.java
●
ChangeMenu.class
●
ChangeMenu.htm
●
ComponentUtilities.class
●
MenuTest.class
●
MenuTest.java
●
MenuTest12.java
●
MenuTest12.class
●
MenuTest12$MyMenuItem.class
●
PopupTest.htm
●
PopupTest.java
●
PopupTest.class
http://localhost/java/javaref/awt/examples/chap10/index.htm [20/12/2001 11:17:41]
Examples for Examples for Java AWT
Examples for Java AWT ●
ScrollingImage.class
●
ScrollingImage.java
●
ImageCanvas.class
●
ImageFileFilter.class
●
ImageListDialog.class
●
scroll.java
●
scroll.class
●
scroll.htm
http://localhost/java/javaref/awt/examples/chap11/index.htm [20/12/2001 11:17:42]
Examples for Examples for Java AWT
Examples for Java AWT ●
TestPrint.java
●
TestPrint.class
●
TestPrint$CloseCommand.class
●
TestPrint$PrintCommand.class
●
TestPrint$LoadFileCommand.class
http://localhost/java/javaref/awt/examples/chap17/index.htm [20/12/2001 11:17:43]
Examples for Examples for Java AWT
Examples for Java AWT ●
illegal.java
●
illegal.class
●
throwme.class
●
throwme.java
http://localhost/java/javaref/awt/examples/chap13/index.htm [20/12/2001 11:17:45]
Examples for Examples for Java AWT
Examples for Java AWT ●
ParamApplet.htm
●
ParamApplet.java
●
ParamApplet.class
●
audioTest.java
●
audioTest.class
●
audioTest.htm
●
audio
●
AudioTestExample.java
●
AudioTestExample.class
●
AudioTestExample.htm
●
SunAudioClip.java
●
SunAudioClip.class
●
1.au
http://localhost/java/javaref/awt/examples/chap14/index.htm [20/12/2001 11:17:46]
Examples for Examples for Java AWT
Examples for Java AWT ●
checkingImages.java
●
checkingImages.class
●
checkingImages.htm
●
ora-icon.gif
●
TransparentImageFilter.java
●
TransparentImageFilter.class
●
drawingImages.java
●
drawingImages.class
●
drawingImages.htm
http://localhost/java/javaref/awt/examples/chap15/index.htm [20/12/2001 11:17:47]
Examples for Examples for Java AWT
Examples for Java AWT ●
ClipMe.java
●
ClipMe.class
http://localhost/java/javaref/awt/examples/chap16/index.htm [20/12/2001 11:17:48]
Examples for Examples for Java AWT
Examples for Java AWT ●
Prop.class
●
Prop.java
●
prop.list
●
Prop.htm
●
Prop11.java
●
prop11.list
●
Prop11.class
●
Prop11.htm
●
ora-icon.gif
http://localhost/java/javaref/awt/examples/chapA/index.htm [20/12/2001 11:17:49]
Examples for Examples for Java AWT
Examples for Java AWT ●
compList.htm
●
compList.java
●
compList.class
http://localhost/java/javaref/awt/examples/chapC/index.htm [20/12/2001 11:17:50]
[Preface] Using This Book
Preface
Using This Book This book is not meant to be read from cover to cover. Instead, it is meant to be used as a reference manual for the syntax and lexical structure of the Java language. The language is presented in a bottom-up order. The text starts with lexical analysis and works up through data types, expressions, declarations, statements, and overall program structure. The book also covers threads and exception handling in detail. The final chapter presents reference information on the classes in the java.lang package, since these classes are essential to the Java language. When you need to know the details about a particular Java construct, you can find the appropriate section and read everything you need to know about that aspect of the language. For every construct, there is a railroad diagram that presents its syntax in an easy-to-understand, visual fashion. The text also provides many examples to illustrate subtle features of the language. The book includes numerous cross-references to help you move quickly between related topics. A cross-reference shown in italic type specifies the location of a railroad diagram related to the current diagram, while cross-references in plain text specify other sections of the book. The Java Language Reference is broken down into ten chapters and an appendix as follows: Chapter 1 Introduction provides a quick introduction to the Java programming language by way of a "Hello World" example. The chapter also describes the notational conventions of the railroad diagrams that are used to define the syntax and lexical structure of the Java language. Chapter 2 Lexical Analysis describes the process by which the Java compiler reads the characters in a Java source file and looks for sequences that form identifiers, keywords, literals, and operators. Chapter 3 Data Types discusses all of the different data types provided by the Java language. Chapter 4 Expressions presents the syntax of Java expressions and describes the function of each operator in the language. Chapter 5
http://localhost/java/javaref/langref/ch00_02.htm (1 of 2) [20/12/2001 11:17:51]
[Preface] Using This Book
Declarations covers the syntax of class, interface, method, and variable declarations. The chapter also provides a detailed look at the object-oriented aspects of the Java language. Chapter 6 Statements and Control Structures describes each of the available statements in Java. Chapter 7 Program Structure presents the syntax of Java compilation units and also covers the two common types of Java programs: stand-alone applications and applets. Chapter 8 Threads discusses how to create and control threads in a Java program, as well as how to synchronize multiple threads. Chapter 9 Exception Handling describes how to generate, declare, and handle exceptions in Java. The chapter also covers the hierarchy of exception classes provided in the java.lang package. Chapter 10 The java.lang Package provides reference information on each of the classes in java.lang. Appendix The Unicode 2.0 Character Set lists the character sets that comprise the Unicode standard.
Audience
http://localhost/java/javaref/langref/ch00_02.htm (2 of 2) [20/12/2001 11:17:51]
Related Books
[Preface] Related Books
Preface
Related Books O'Reilly & Associates is developing an entire series of books on Java. This series consists of introductory books, reference manuals, and advanced programming guides. The following books on Java are currently available or due to be released soon from O'Reilly & Associates: Exploring Java, by Patrick Niemeyer and Joshua Peck A comprehensive tutorial that provides a practical, hands-on approach to learning Java. Java AWT Reference, by John Zukowski A comprehensive reference manual for the AWT-related packages in the core Java API. Java Fundamental Classes Reference, by Mark Grand and Jonathan Knudsen A complete reference manual for the java.lang, java.io, java.util, and java.net packages, among others, in the core Java API. Java Virtual Machine, by Jon Meyer and Troy Downing A programming guide and reference manual for the Java virtual machine. Java in a Nutshell, by David Flanagan A quick-reference guide to Java that lists all of the classes, methods, and variables in the core Java API. Java Threads, by Scott Oaks and Henry Wong An advanced programming guide to working with threads in Java. Java Network Programming, by Elliotte Rusty Harold A complete guide to writing sophisticated network applications. Database Programming with JDBC and Java, by George Reese An advanced tutorial on JDBC that presents a robust model for developing Java database programs. Developing Java Beans, by Robert Englander
http://localhost/java/javaref/langref/ch00_03.htm (1 of 2) [20/12/2001 11:17:52]
[Preface] Related Books
A complete guide to writing components that work with the JavaBeans API. Look for additional advanced programming guides on such topics as distributed computing and electronic commerce from O'Reilly in the near future.
Using This Book
http://localhost/java/javaref/langref/ch00_03.htm (2 of 2) [20/12/2001 11:17:52]
Online Resources
[Preface] Online Resources
Preface
Online Resources There are many sources for information about Java. Sun Microsystems's official Web site for Java topics is http://www.javasoft.com/. You should look here for the latest news, updates, and Java releases. This site is where you'll find the Java Development Kit ( JDK), which includes the compiler, the interpreter, and other tools. The various comp.lang.java.* newsgroups can be a good source of information about Java. The comp.lang.java.announce newsgroup is for announcements that may be of interest to Java developers. The comp.lang.java.programmer newsgroup is for discussion of the Java language; it's also a good place to ask intelligent questions. There are a number of other Java newsgroups for various kinds of specialized discussions. You should read the FAQ to find out more. The FAQ is maintained on the Web at http://sunsite.unc.edu/javafaq/javafaq.html. You should also visit O'Reilly & Associates' Java site on the Web at http://www.ora.com/publishing/java . There you'll find information about other books in O'Reilly's Java series.
Related Books
http://localhost/java/javaref/langref/ch00_04.htm [20/12/2001 11:17:53]
Conventions Used in This Book
[Preface] Conventions Used in This Book
Preface
Conventions Used in This Book Italic is used for: ● The names of syntactic constructs and lexical structures in the Java language ● New terms where they are defined ● Pathnames, filenames, and program names ● Internet addresses, such as domain names and URLs Typewriter Font is used for: ● Anything that might appear in a Java program, including keywords, operators, data types, constants, method names, variable names, class names, and interface names ● Command lines and options that should be typed verbatim on the screen ● Tags that might appear in an HTML document
Online Resources
http://localhost/java/javaref/langref/ch00_05.htm [20/12/2001 11:17:53]
Request for Comments
[Preface] Request for Comments
Preface
Request for Comments We invite you to help us improve our books. If you have an idea that could make this a more useful language reference, or if you find a bug in an example or an error in the text, let us know by sending mail to [email protected].
Conventions Used in This Book
http://localhost/java/javaref/langref/ch00_06.htm [20/12/2001 11:17:54]
Acknowledgments
[Preface] Acknowledgments
Preface
Acknowledgments I wish to acknowledge the patience of my wife, Ginni, and my daughters, Rachel, Shana, and Sossa, during the long hours I spent writing this book. I also want to thank Mike Loukides and Andy Cohen for their valuable suggestions on the content of this book. I particularly want to thank Paula Ferguson, who spent many long hours above and beyond the call of duty poring over the details of this book to edit it into its final form. Thanks also to the staff at O'Reilly & Associates. Nicole Gipson Arigo was the production editor and project manager. Kismet McDonough-Chan proofread the book. Ellie Fountain Maden and Sheryl Avruch performed quality control checks. Seth Maislin wrote the index. Erik Ray, Ellen Siever, and Lenny Muellner worked with the tools to create the book. Robert Romano fine-tuned the figures. Nancy Priest designed the interior book layout, and Edie Freedman designed the front cover.
Request for Comments
http://localhost/java/javaref/langref/ch00_07.htm [20/12/2001 11:17:57]
Introduction
[Chapter 1] 1.2 New Language Features in Java 1.1
Chapter 1 Introduction
1.2 New Language Features in Java 1.1 Although Java 1.1 is a massive new release, there are relatively few changes to the Java language in this version. The new features of the language are quite significant, however, as they add useful functionality and make the Java language even more elegant. Here is a brief summary of the new features of the Java language in Java 1.1: ● The addition of inner classes is the largest change to the Java language in Java 1.1. With this new feature, classes can be defined as members of other classes, just like variables and methods. Classes can also be defined within blocks of Java code, just like local variables. A class that is declared inside of another class may have access to the instance variables of the enclosing class; a class declared within a block may have access to the local variables and/or formal parameters of that block. Inner classes include: nested top-level classes and interfaces, member classes, local classes, and anonymous classes. The various types of inner clases are described in Inner Classes. The syntax for nested top-level and member classes is covered in Nested Top-Level and Member Classes, while the syntax for nested top-level interfaces is covered in Nested Top-Level Interfaces. The syntax for local classes is described in Local Classes. The syntax for an anonymous class is part of an allocation expression, as covered in Allocation Expressions. ●
Java 1.1 provides the ability to declare final local variables, method parameters, and catch clause parameters. final local variables, method parameters, and catch parameters are needed to allow local classes to access these entities within the scope of their blocks. The syntax for final local variables is described in Local Variables, while final method parameters are covered in Method formal parameters. The new syntax for the catch clause is described in The try Statement.
●
Instance initializers are blocks of code that execute when an instance of a class is created. Instance initializers have been added in Java 1.1 to allow anonymous classes to perform any necessary initialization, since anonymous classes can not define any constructors. The syntax for instance initializers is covered in Instance Initializers.
●
As of Java 1.1, final variable declarations do not have to include initializers. A final variable declaration that does not include an initializer is called a blank final. The functionality of blank finals is described in Variable modifiers and Final local variables.
http://localhost/java/javaref/langref/ch01_02.htm (1 of 2) [20/12/2001 11:17:59]
[Chapter 1] 1.2 New Language Features in Java 1.1
●
A class literal is a new kind of primary expression that can be used to obtain a Class object for a particular data type. Class literals have been added to support the new Reflection API in Java 1.1. The syntax for class literals is covered in Class Literals.
●
An anonymous array is an array created and initialized without using a variable initializer. The syntax for an anonymous array is part of an allocation expression, as described in Allocation Expressions.
A "Hello World" Program
http://localhost/java/javaref/langref/ch01_02.htm (2 of 2) [20/12/2001 11:17:59]
Compiling a Java Source File
[Chapter 1] 1.3 Compiling a Java Source File
Chapter 1 Introduction
1.3 Compiling a Java Source File The interface for the Java compiler in Sun's Java Development Kit (JDK) is the command line. To compile a Java program, run the program javac with the name of the source file specified as a command-line argument. For example, to compile the "Hello World" program, issue the following command: C:\> javac HelloWorld.java The Java compiler, javac, requires that the name of a Java source file end with a .java extension. If the source file contains a class or interface that is declared with the keyword public, the filename must be the name of that class or interface. There can be at most one such class or interface in a source file. In an environment such as Windows 95 that does not distinguish between uppercase and lowercase letters in a filename, you still need to be sure that the case of the filename exactly matches the case used in the public class or interface declaration. If you use a filename with the incorrect case, the compiler will be able to compile the file but it will complain about an incorrect filename. The compiler produces a compiled class file with the same name as the public class or interface declaration; the file extension used for a compiled Java file is .class. If the javac compiler complains that it is unable to find some classes, it may mean that an environment variable named CLASSPATH has not been set properly. The exact setting needed for CLASSPATH varies depending on the operating system and its directory structure. However, the value of CLASSPATH always specifies a list of directories in which the compiler should search for Java classes.
New Language Features in Java 1.1
http://localhost/java/javaref/langref/ch01_03.htm [20/12/2001 11:18:03]
Running a Java Application
[Chapter 1] 1.4 Running a Java Application
Chapter 1 Introduction
1.4 Running a Java Application To run a Java application, you invoke the Java interpreter, java, with one or more arguments. The first argument is always the name of a Java class. Here is how to run the "Hello World" application: C:\> java HelloWorld The capitalization of the class name must match the name used in the class declaration in the source file. The interpreter loads the specified class and then calls its main() method. A class can belong to a particular package. This allows the class to prevent classes in other packages from accessing its declared variables and methods. If a class is not specified as part of a package, it automatically becomes part of the default package. Because the HelloWorld class is part of the default package, you do not need to include the package name as part of the class name on the command line. If the HelloWorld class were part of a package called student.language, however, you would have to include the package name on the command line. For example, you would run the application as follows: C:\> java student.language.HelloWorld Any additional arguments specified on the command line are passed to the main() method in its String[] parameter. For the "Hello World" application, the String[] parameter is an empty array. If, however, there were command-line arguments, the first array element, String[0], would correspond to the first command-line argument specified after the class name, String[1] would correspond to the next command-line element, and so on. The name of the class does not appear as an element in the array of parameters passed to the main() method. This is different than in C/C++, where the first element in the array of command-line arguments identifies the program name and the second element is the first command-line argument.
Compiling a Java Source File
http://localhost/java/javaref/langref/ch01_04.htm [20/12/2001 11:18:04]
Notational Conventions
[Chapter 1] 1.5 Notational Conventions
Chapter 1 Introduction
1.5 Notational Conventions One of the topics of this manual is the syntax of Java: the way that identifiers such as foobar, operators such as +, and punctuation such as ; can be put together to form a valid Java program. This book also talks about lexical structure : the sequences of characters that can be put together to form valid numbers, identifiers, operators, and the like. To describe syntax and lexical structure, many language reference manuals use a notation called BNF. BNF notation is very helpful to language implementors because it defines language constructs in a way that can easily be turned into a working language parser. Unfortunately, however, BNF can be difficult for human beings to understand. This reference manual uses a different notation, called a railroad diagram, to describe syntax and lexical structure. Railroad diagrams are much easier for people to understand. A railroad diagram provides a visual means of specifying the sequence of words, symbols, and punctuation that can be used to write a syntactic construct or a lexical structure. Here is a simple example:
The idea is to follow the lines from left to right. The sequence of words or symbols that you pass along the way is the sequence of words or symbols that the railroad diagram specifies. The primary rule when navigating railroad diagrams is that you can follow lines from left to right only, unless there is an arrow pointing to the left. In the above example, there are no arrows, so there is only one way to navigate through the diagram. Therefore, the above railroad diagram specifies exactly one sequence of words: ROW YOUR BOAT. The next example provides you with a choice of sequences:
You can navigate the above diagram with one of three sequences: ● ROW YOUR BOAT ● ROW YOUR CANOE ● ROW YOUR KAYAK http://localhost/java/javaref/langref/ch01_05.htm (1 of 3) [20/12/2001 11:18:11]
[Chapter 1] 1.5 Notational Conventions
The following example contains an arrow:
In the above diagram, there is a left-pointing arrow on the line under the word ROW. That arrow means that the line can only be traversed from right to left. The line with the arrow provides a loop that allows the word ROW to be repeated one or more times, separated by commas. This allows a sequence like: ROW,ROW,ROW YOUR BOAT. The railroad diagrams shown so far lack a feature that is typically needed to make them useful: a name. A name allows one railroad diagram to refer to another diagram. The following railroad diagram defines a construct named color :
To further illustrate this point, let's look at two more railroad diagrams. The first diagram defines a construct named size :
The second railroad diagram is similar to previous ones except that now it allows an optional color or size to precede BOAT, CANOE, or KAYAK. The diagram does this by referring to the names of the railroad diagrams that define these things:
In the diagrams in this book, the font for words such as ROW that are directly contained in railroad diagrams is different from the font used for words like color that are names of railroad diagrams. The preceding railroad diagram allows size and color to occur more than once. The next diagram limits size and color to at most one occurrence:
http://localhost/java/javaref/langref/ch01_05.htm (2 of 3) [20/12/2001 11:18:11]
[Chapter 1] 1.5 Notational Conventions
The lines that refer to the size and color diagrams both have semi-circles with the number one under them. The semi-circles represent bridges that collapse if crossed more than a certain number of times. The number under the semi-circle is the number of times a bridge can be crossed. Adding bridges that can be crossed only once creates a railroad diagram that permits no more than one occurrence of color and size. The other new feature introduced in the above railroad diagram is a circle enclosing a number. These circles are connectors used when a diagram does not fit across a page. The numbered connector at the right end of one part of a railroad diagram attaches to a connector with a matching number at the left end of another part of the railroad diagram.
Running a Java Application
http://localhost/java/javaref/langref/ch01_05.htm (3 of 3) [20/12/2001 11:18:11]
Lexical Analysis
[Chapter 2] 2.2 Tokenization
Chapter 2 Lexical Analysis
2.2 Tokenization The tokenization phase of lexical analysis in Java handles breaking down the lines of Unicode source code into comments, white space, and tokens. The rule that defines the overall lexical organization of Java programs is TokenStream:
References Comments; Identifiers; Keywords; Literals; Operators; Separators; White Space
Identifiers An identifier is generally used as the name for a thing in a program. A few identifiers are reserved by Java for special uses; these are called keywords. From the viewpoint of lexical analysis, an identifier is a sequence of one or more Unicode characters. The first character must be a letter, underscore, or dollar sign. The other characters must be letters, numbers, underscores, or dollar signs. An identifier can't have the same Unicode character sequence as a keyword:
http://localhost/java/javaref/langref/ch02_02.htm (1 of 12) [20/12/2001 11:18:22]
[Chapter 2] 2.2 Tokenization
For example, foo21, _foo, and $foo are all valid identifiers; 3foo is not a valid identifier. There is no limit to the length of an identifier in Java. Although $ is a legal character in an identifier, you should avoid using it to eliminate confusion with compiler-generated identifiers. A UnicodeDigit is a Unicode character that is classified as a digit by Character.isDigit(). A UnicodeLetter is a Unicode character code that is classified as a letter by Character.isLetter(). Two identifiers are the same if they have the same length and if corresponding characters in each identifier have the same Unicode character code. It is possible, however, to have identifiers that are distinct to a Java compiler, but not to the human eye. For example, the Java compiler recognizes lowercase Latin `a' (\u0061) and lowercase Cyrillic `a' (\u0430) as different characters, although they may well be visually indistinguishable. References Character; Keywords
Keywords Keywords are identifiers that have a special meaning to Java. Because of their special meanings, keywords are not available for use as names of things defined in programs. A Keyword is one of the following: abstract default goto null synchronized boolean do if package this break double implements private throw byte else import protected throws case extends instanceof public transient catch false int return true char final interface short try class finally long static void const float native super volatile continue for new switch while The keywords const and goto are not currently used for any purpose in Java, although they may be assigned meaning in future versions of the Java language.
http://localhost/java/javaref/langref/ch02_02.htm (2 of 12) [20/12/2001 11:18:22]
[Chapter 2] 2.2 Tokenization
References Identifiers
Literals A literal is a token that represents a constant value of a primitive data type or a String object:
References Boolean literals; Character literals; Floating-point literals; Integer literals; String literals Integer literals An integer literal represents an integer constant:
NonZeroDigit is defined as one of the following characters: 1, 2, 3, 4, 5, 6, 7, 8, or 9. OctalDigit is defined as one of the following characters: 0, 1, 2, 3, 4, 5, 6, or 7. Integer literals that begin with a non-zero digit are in base 10 and are called decimal literals. Integer literals that begin with 0x are in base 16 and are called hexadecimal literals. Integer literals that begin with 0 followed by 0-7 are in base 8 and are called octal literals. If an integer literal ends with L or l, its type is long; otherwise its type is int. Integer literals cannot begin with a + or a -. If either of these characters precedes an integer literal, it is treated as a unary operator, a separate token in its own right. Here are some examples of int literals:
http://localhost/java/javaref/langref/ch02_02.htm (3 of 12) [20/12/2001 11:18:22]
[Chapter 2] 2.2 Tokenization
0 92 0642 0xDeadBeef Here are some examples of long literals: 0L 1414213562373l 0x2000000000L 075204l Note that the preceding examples end with either an uppercase or lowercase "L". They do not end with the digit 1 (one). Decimal literals of type int may not be greater than 2147483647, which represents 2^31-1. Decimal literals of type long may not be greater than 9223372036854775807L, which represents 2^63-1. Decimal literals cannot be used directly to represent negative values. To represent negative values using a decimal literal, you must use the decimal literal in conjunction with the unary minus operator. For example, representing -321 requires the use of a unary minus and a decimal literal. To represent the int -2147483648, use 0x80000000. To represent the long -9223372036854775808L, use 0x8000000000000000L. Hexadecimal and octal literals may be positive or negative because they represent either a 32-bit (int) or 64-bit (long) two's-complement quantity. Two's complement is a binary encoding technique that represents both positive and negative values. The range of values that can be represented by int hexadecimal and octal literals is shown in Table 2-1. Table 2.1: Minimum and Maximum int Literals Representation Minimum Value Maximum Value Hexadecimal 0x80000000 0x7fffffff Octal 020000000000 017777777777 Base 10 equivalent -2147483648 2147483647 The range of values that can be represented by long hexadecimal and octal literals is shown in Table 2-2. Table 2.2: Minimum and Maximum long Literals Representation Hexadecimal Octal Base 10 equivalent
Minimum Value
Maximum Value
0x8000000000000000L 0x7fffffffffffffffL 01000000000000000000000L 0777777777777777777777L -9223372036854775808 9223372036854775807
References **UNKNOWN XREF**; **UNKNOWN XREF**; Integer types; Conversion to Unicode; http://localhost/java/javaref/langref/ch02_02.htm (4 of 12) [20/12/2001 11:18:22]
[Chapter 2] 2.2 Tokenization
Unary Operators Floating-point literals A floating-point literal represents a constant value of type float or double :
A floating-point literal must minimally contain at least one digit and either a decimal point or an exponent. The data type of a floating-point literal is float if and only if the suffix f or F appears at the end of the literal. If there is no suffix or the suffix is d or D, the data type is double. Floating-point literals cannot begin with a + or a -. If either of these precedes a floating-point literal, it is treated as a separate token, a unary operator. Here are some examples of float literals: 23e4f 1.E2f .31416e1F 2.717f 7.63e+9f Here are some examples of double literals: 23e4 1.E2 .31415e1D http://localhost/java/javaref/langref/ch02_02.htm (5 of 12) [20/12/2001 11:18:23]
[Chapter 2] 2.2 Tokenization
2.717 7.53e+9d The ranges of values that can be represented by float and double literals are shown in Table 2-3. Table 2.3: Minimum and Maximum Floating-Point Literals Representation Minimum Value Maximum Value float 1.40239846e-45f 3.40282347e38f double 4.94065645841246544e-324 1.79769313486231570e308 Floating-point literals that exceed these limits are treated as errors by the Java compiler. The special floating-point values positive infinity, negative infinity, and not-a-number are available as predefined constants in Java, as part of the Float and Double classes. References **UNKNOWN XREF**; Floating-point types; Unary Operators; Double; Float Boolean literals There are two boolean literal values, represented by the keywords true and false:
References Boolean Type Character literals A character literal represents a constant value of type char (an unsigned 16-bit quantity). A character literal consists of either the character being represented, or an equivalent escape sequence, enclosed in single quotes:
http://localhost/java/javaref/langref/ch02_02.htm (6 of 12) [20/12/2001 11:18:23]
[Chapter 2] 2.2 Tokenization
Here are some examples of character literals: 'c' 'n' '\\' '\u0138' The character sequence \uxxxx is not defined above as a valid Escape, even though it can be used as a legal character literal. This sequence of characters is defined as an EscapedSourceCharacter, which is handled during the pre-processing phase, before tokenization takes place. As a result, the tokenization phase never sees an EscapedSourceCharacter. Tokenization sees only the single Unicode character that replaces the EscapedSourceCharacter during pre-processing. The translations of the different types of escape sequences supported in Java are shown in Table 2-4. Table 2.4: Java Escape Sequences Escape Sequence Unicode Equivalent Meaning Backspace \b \u0008 Horizontal tab \t \u0009 Linefeed \n \u000a Form feed \f \u000c Carriage return \r \u000d Double quote \" \u0022 Single quote \' \u0027 Backslash \\ \u005c \xxx
\u0000 to \u00ff The character corresponding to the octal value xxx
A character literal representing a carriage return character can be written only as '\r'; a character literal
http://localhost/java/javaref/langref/ch02_02.htm (7 of 12) [20/12/2001 11:18:23]
[Chapter 2] 2.2 Tokenization
representing a linefeed character can be written only as '\n'. During the pre-processing that precedes token recognition, these characters are classified as line terminators, so neither carriage return (\u000d) nor linefeed (\u000a) characters in Java source code can ever be seen by the Java compiler as being part of a character literal. If a backslash that is not part of a legal Escape appears in a character literal, it is flagged as an error. This is different from languages like C++ that ignore backslashes in character literals that are not part of an escape. References Conversion to Unicode; Integer types; **UNKNOWN XREF** String literals A string literal represents a constant string value and consists of the characters in the string or the equivalent escapes:
Here are some examples of string literals: "" "Hello World" "This has \"escapes\"\n"
// the empty string // a string literal with escapes
There is no primitive type for representing strings in Java. Instead, each string literal becomes a reference to a String object. If two or more string literals consist of the same sequence of characters, they refer to the same String object. Using one String object to represent multiple string literals works because, once created, the contents of a String object cannot be changed. For a string literal to contain a carriage return or linefeed character, the carriage return or linefeed must be written as \r or \n. Neither carriage return (\u000d) nor linefeed (\u000a) characters in Java source code can ever be seen by the Java compiler as part of a string literal. These characters are classified as line terminators during the pre-processing phase that precedes token recognition. For the same reason, \u Unicode escapes for carriage return and linefeed characters cannot be directly used in string literals. If a backslash that is not part of a legal Escape appears in a string literal it is flagged as an error. This is different from languages like C++ that ignore backslashes in string literals that are not part of an escape. Because operations on strings are generally based on the length of the string, Java does not automatically supply a NUL character (\u0000) at the end of a string literal. For the same reason, it is not customary for Java programs to put a NUL character at the end of a string. References Escape 2.2.3.4; Specially supported classes; String; StringBuffer; String Concatenation Operator + http://localhost/java/javaref/langref/ch02_02.htm (8 of 12) [20/12/2001 11:18:23]
[Chapter 2] 2.2 Tokenization
Separators A separator is any one of the punctuation tokens in the following railroad diagram:
Separator tokens are used to separate other types of tokens. Thus, separators are a part of a higher-level syntactic construct. Although separators have syntactic significance, they do not imply any operation on data.
Operators An operator is a token that implies an operation on data. Java has both assignment and non-assignment operators:
A NonAssignmentOperator is one of the following: + - = % -/ != ? >> ! & == : >> ~ | && >>> An AssignmentOperator is one of the following: = -= *= /= |= &= ^= += %= = >>>=
http://localhost/java/javaref/langref/ch02_02.htm (9 of 12) [20/12/2001 11:18:23]
[Chapter 2] 2.2 Tokenization
Unlike C/C++, Java does not have a comma operator. Java does allow a comma to be used as a separator in the header portion of for statements, however. Java also omits a number of other operators found in C and C++. Most notably, Java does not include operators for accessing physical memory as an array of bytes, such as sizeof, unary & (address of), unary * (contents of), or -> (contents of field).
Comments Java supports three styles of comments: ● A standard C-style comment, where all of the characters between /* and */ are ignored. ● A single-line comment, where all of the characters from // to the end of the line are ignored. ● A documentation comment that begins with /** and ends with */. These comments are similar to standard C-style comments, but the contents of a documentation comment can be extracted to produce automatically generated documentation. The formal definition of a comment is:
C-style comments and documentation comments do not nest. For example, consider the following arrangement of comments: /*
...
/*
...
*/
...
*/
The Java compiler interprets the first */ to be the end of the comment, so that what follows is a syntax error. However, in a single-line comment (i.e., one that starts with // ), the sequences /*, /**, and */ have no special meaning. Similarly, in a C-style comment or a documentation comment (i.e., comments that begin with /* or /**), the sequence // has no special meaning. In order to comment out large chunks of code, you need to adopt a commenting style. The C/C++ practice of using #if to comment out multiple lines of code is not available for Java programs because Java does not have a conditional compilation mechanism. If you use C-style comments in your code, you'll need to use the // style of comment to comment out multiple lines of code: ///* // * Prevent instantiation of RomanNumeral objects without http://localhost/java/javaref/langref/ch02_02.htm (10 of 12) [20/12/2001 11:18:23]
[Chapter 2] 2.2 Tokenization
// * parameters. // */ // private RomanNumeral() { // super(); // } The /* */ style of comment cannot be used to comment out the lines in the above example because the example already contains that style of comment, and these comments do not nest. If, however, you stick to using the // style of comment in your code, you can use C-style comments to comment out large blocks of code: /* *// Prevent instantiation of RomanNumeral objects without *// parameters. * private RomanNumeral() { * super(); * } */ Which style you choose is less important than using it consistently, so that you avoid inadvertently nesting comments in illegal ways. References Documentation Comments; Division of the Input Stream into Lines
White Space White space denotes characters such as space, tab, and form feed that do not have corresponding glyphs, but alter the position of following glyphs. White space and comments are discarded. The purpose of white space is to separate tokens from each other:
SpaceCharacter is equivalent to \u0020. HorizontalTabCharacter is equivalent to \u0009 or \t. FormFeedCharacter is equivalent to \u000C or \f. EndOf FileMarker is defined as \u001A. Also known as Control-Z, this is the last character in a pre-processed compilation unit. It is treated as white space if it is the last character in a file, to enhance compatibility with older MS-DOS programs and other operating environments that recognize \u001A as http://localhost/java/javaref/langref/ch02_02.htm (11 of 12) [20/12/2001 11:18:23]
[Chapter 2] 2.2 Tokenization
an end-of-file marker. References Division of the Input Stream into Lines
Pre-Processing
http://localhost/java/javaref/langref/ch02_02.htm (12 of 12) [20/12/2001 11:18:23]
Data Types
[Chapter 3] 3.2 Reference Types
Chapter 3 Data Types
3.2 Reference Types Java is an object-oriented language. An object is a collection of variables and associated methods that is described by a class. The concepts in this section that relate to objects are discussed in detail in Object-Orientation Java Style. The name of a class can be used as a type, so you can declare an object-type variable or specify that a method returns an object. If you declare a variable using the name of a class for its type, that variable can contain a reference to an object of that class. Such a variable does not contain an actual object, but rather a reference to the class instance, or object, the variable refers to. Because using a class name as a type declares a reference to an object, such types are called reference types. Java also allows the use of an interface name to specify a reference type. In addition, array types in Java are reference types because Java treats arrays as objects. The two main characteristics of objects in Java are that: ● Objects are always dynamically allocated. The lifetime of the storage occupied by an object is determined by the program's logic, not by the lifetime of a procedure call or the boundaries of a block. The lifetime of the storage occupied by an object refers to the span of time that begins when the object is created and ends at the earliest time it can be freed by the garbage collector. ● Objects are not contained by variables. Instead, a variable contains a reference to an object. A reference is similar to what is called a pointer in other languages. If there are two variables of the same reference type and one variable is assigned to the other, both variables refer to the same object. If the information in that object is changed, the change is visible through both variables. Java references are very similar to pointers in C/C++, but they are not at all related to the C++ notion of a reference. The main difference between Java references and C++ pointers is that Java does not allow any arithmetic to be done with references. This, coupled with Java's lack of any way to explicitly deallocate the storage used by reference type values, guarantees that a reference can never point to an illegal address. The formal definition of a reference type is:
http://localhost/java/javaref/langref/ch03_02.htm (1 of 6) [20/12/2001 11:18:26]
[Chapter 3] 3.2 Reference Types
It is possible to cause a reference variable to contain a reference to nothing by assigning the special value represented by the keyword null to the variable. The value null can be assigned to any reference variable without a type cast. Java does not allow reference types to be cast to primitive data types or primitive data types to be type cast to reference types. In particular, unlike C/C++, there is no conversion between integer values and references. The only operation that Java provides for reference-type variables is the ability to fetch the referenced object. However, Java does not provide an operator to fetch the object referenced by a reference variable. Instead, the object fetch operation is performed implicitly by the following operations: ● A field expression that accesses a variable or method of a class or interface object ● A field expression that accesses an element of an array object ● A type comparison operation that uses the instanceof operator References Array Types; ClassOrInterfaceName 4.1.6; Class Types; Field Expressions; Interface Types; null; Object-Orientation Java Style; Primitive Types; The instanceof Operator
Class Types The name of a class can be used to specify the type of a reference. If a variable is declared as a class type, the variable either contains null or a reference to an object of that class or a subclass of that class. It is not allowed to contain any other kinds of values. For example: class Shape { ... } class Triangle extends Shape { ... } ... Shape s; Triangle t; ... s = t; This example declares a class called Shape and a subclass of Shape called Triangle. The code later declares a reference variable called s that can contain a reference to a Shape object and another variable called t that can contain a reference to a Triangle object. The value of s can be assigned to the value of t because an object is not only an instance of its declared class, but also an instance of every superclass of its declared class. Since instances of the Triangle class are also instances of its superclass Shape, the Java compiler has no problem with s = t. However, saying t = s generates an error message from the compiler. Java does not allow a reference variable declared as a class type to contain a reference to a superclass of the declared class. The http://localhost/java/javaref/langref/ch03_02.htm (2 of 6) [20/12/2001 11:18:26]
[Chapter 3] 3.2 Reference Types
assignment t = s is illegal because Shape is a superclass of Triangle. The assignment can be accomplished if s is first cast to a reference to Triangle: t = (Triangle)s; The cast operation ensures that the object referenced by s is a class type that is either Triangle or a descendant of Triangle. When you cast an object reference to a subclass of the reference type, you are saying that you want to treat the object being referenced as an instance of the specified subclass. If the compiler cannot determine whether the argument of a cast will be of the required type, the compiler generates runtime code that ensures that the argument really is an instance of the specified subclass. At runtime, if the class of the object being referenced is not an instance of the specified subclass, a ClassCastException is thrown. References Casts; Classes; Class Declarations; Object Allocation Expressions; Runtime exceptions Specially supported classes Java provides special support for the String and StringBuffer classes. All string literals are compiled into String objects. The result of a string concatenation operation is a String object. An intermediate StringBuffer object is used to compute the result of a concatenation operation. Because operations on strings are generally based on the length of the string, Java does not automatically supply a NUL character (\u0000) at the end of a string literal. For the same reason, it is not customary for Java programs to put a NUL character at the end of a string. Java also provides special support for the Object class. This class is the ultimate superclass of all other classes in Java. If a class is declared without its superclass being specified, the language automatically specifies Object as its superclass. The throw statement in Java is special, in that it requires the use of a Throwable object. References Object; String; StringBuffer; String Concatenation Operator +; String literals; The throw Statement; Throwable
Interface Types The name of an interface can be used to specify the type of a reference. A reference variable declared using an interface name as its type can only reference instances of classes that implement that interface. For example, Java provides an interface called Runnable. Java also provides a class called Thread that implements Runnable. This means that the following assignment is allowed: Runnable r; r = new Thread(); The Java compiler does not allow a value to be assigned to a variable declared using an interface type unless the compiler can be sure that the object referenced by the value implements the specified interface. Casting a reference variable to an interface type allows the variable to be assigned to that interface type, because the cast operation provides its own guarantee that the object implements the http://localhost/java/javaref/langref/ch03_02.htm (3 of 6) [20/12/2001 11:18:26]
[Chapter 3] 3.2 Reference Types
specified interface. Unless the compiler is able to determine the actual class of the object that will be referenced at runtime, the cast produces code that verifies at runtime that the object being cast really does implement the specified interface. At runtime, if the object being cast does not implement the required interface, a ClassCastException is thrown. References Casts; Interfaces; Interface Declarations; Object Allocation Expressions; Runtime exceptions
Array Types An array is a special kind of object that contains values called elements. Array elements are similar to variables in that they contain values that can be used in expressions and set by assignment operations. Elements differ from variables, however, in that they do not have names. Instead, they are identified by non-negative integers. The elements in an array are identified by a contiguous range of integers from 0 to one less than the number of elements in the array. The elements of an array must all contain the same type of value; the type of the array is specified when the array is created. An array-type variable is declared as follows: int [] a; This declaration specifies that the variable a refers to an array of int values. Java actually allows two styles of array declarations: the one shown above and a style that is more like that used in C/C++. In other words, you can put the square brackets after the variable name instead of after the type: int a[]; Technically, all arrays in Java are one-dimensional. However, Java does allow you to declare an array of arrays, which is a more flexible data structure than a multi-dimensional array. The additional flexibility comes from the fact that the arrays in an array of arrays do not have to be the same length. Because arrays of arrays are typically used to represent multi-dimensional arrays, this book refers to them as multi-dimensional arrays, even though that is not precisely correct. A multi-dimensional array is declared using multiple pairs of square brackets, as in the following examples: int [][] d2; int [][][] d3;
// Refers to a 2-dimensional array // Refers to a 3-dimensional array
When you declare a variable to refer to a multi-dimensional array, the number of dimensions in the array is determined by the number of pairs of square brackets. Whether the brackets follow the type name or the variable name is not important. Thus, the above variables could have been declared like this: int [] d2[], d3[][];
// Refers to a 2-dimensional array // Refers to a 3-dimensional array
The actual length of each dimension of an array object is specified when the array object is created, not when the array variable is declared. An array object is not created at the same time that an array variable http://localhost/java/javaref/langref/ch03_02.htm (4 of 6) [20/12/2001 11:18:26]
[Chapter 3] 3.2 Reference Types
is declared. An array object is created with the new operator. Here are some examples: int j[] = new int[10]; int k[][] = new float[3][4];
// An array of 10 ints // An array of 3 arrays of 4 floats
The arrays contained in an array of arrays can also be of different lengths: int a[][] = new int [3][]; a[0] = new int [5]; a[1] = new int [6]; a[2] = new int [7]; Although the first new operator is creating a two-dimensional array, only the length of one dimension is specified. In this case, just the array of arrays is created. The subarrays are created by the subsequent new operators. The expression used to specify the length of an array does not have to be a constant. Consider the following example: int[] countArray(int n){ int[] a = new int[n]; for (int i=0; i>>= Both of the operands of a compound assignment operator must be of primitive types, or a compile-time error occurs. The one exception is if the left operand of the += operator is of type String; in this case
http://localhost/java/javaref/langref/ch04_13.htm (1 of 4) [20/12/2001 11:18:54]
[Chapter 4] 4.13 Assignment Operators
the right operand can be of any type. A compound assignment operator combines a binary operator with the simple assignment operator =. Thus, to be assignment-compatible, the right operand of a compound assignment operator must be of a type that complies with the rules for the indicated binary operation. Otherwise, a compile-time error occurs. An assignment expression of the form: e1 op = e2 is approximately equivalent to: e1 = (type) ((e1) op (e2)) where type is the type of the expression e1. The only difference is that e1 is only evaluated once in the expression that uses the compound assignment operator. For example, consider the following code fragment: j = 0; a[0] = 3; a[1]=6; a[j++] += 2; After this code is executed, j equals 1 and a[0] is 5. Contrast this with the following code: j = 0; a[0] = 3; a[1]=6; a[j++] = a[j++] + 2; After this code is executed, j equals 2 and a[0] is 8 because j++ is evaluated twice. References Array Types; **UNKNOWN XREF**; Conditional Operator; Interface Variables; Local Variables; Order of Operations; Primitive Types; Reference Types; String; Unary Operators; Variables
Assignment Compatibility Saying that one type of value is assignment-compatible with another type of value means that a value of the first type can be assigned to a variable of the second type. Here are the rules for assignment compatibility in Java: ● Every type is assignment-compatible with itself. ● The boolean type is not assignment-compatible with any other type. ● A value of any integer type can be assigned to a variable of any other integer type if the variable is of a type that allows it to contain the value without any loss of information. ● A value of any integer type can be assigned to a variable of any floating-point type, but a value of any floating-point type cannot be assigned to a variable of any integer type. http://localhost/java/javaref/langref/ch04_13.htm (2 of 4) [20/12/2001 11:18:54]
[Chapter 4] 4.13 Assignment Operators
●
●
● ●
●
●
A float value can be assigned to a double variable, but a double value cannot be assigned to a float variable. With a type cast, a value of any arithmetic type can be assigned to a variable of any other arithmetic type. Any reference can be assigned to a variable that is declared of type Object. A reference to an object can be assigned to a class-type reference variable if the class of the variable is the same class or a superclass of the class of the object. A reference to an object can be assigned to an interface-type reference variable if the class of the object implements the interface. A reference to an array can be assigned to an array variable if either of the following conditions is true: ❍ Both array types contain elements of the same type. ❍ Both array types contain object references and the type of reference contained in the elements of the array reference can be assigned to the type of reference contained in the elements of the variable.
Here's an example that illustrates the rules about assignment compatibility of arrays: class Triangle extends Shape {...} ... int[] i = new int[8]; int j[]; long l[]; short s[]; Triangle[] t; Shape[] sh; j = i; // Okay s = i; // Error l = i; // Error sh = t; // Okay t = sh; // Error Assigning i to j is fine because both variables are declared as references to arrays that contain int values. On the other hand, assigning i to s is an error because the variables are declared as references to arrays that contain different kinds of elements and these elements are not object references. Assigning i to l is an error for the same reason. Assigning t to sh is fine because the variables are declared as references to arrays that contain object references, and sh[0]=t[0] is legal. However, assigning sh to t is an error because t[0]=sh[0] is not legal. It is not always possible for the compiler to determine if an assignment to an array element is legal; in these cases the assignment compatibility is checked at runtime. This situation can occur when a variable contains a reference to an array whose type of elements is specified by a class or interface name. In this case, it may not be possible to determine the actual type of the array elements until runtime. Consider the following example:
http://localhost/java/javaref/langref/ch04_13.htm (3 of 4) [20/12/2001 11:18:54]
[Chapter 4] 4.13 Assignment Operators
void foo (InputStream a[]) { a[0] = new FileInputStream("/dev/null"); } Figure 4.1 shows the InputStream class and some of its subclasses in the java.io package. Figure 4.1: InputStream and some of its classes
Any array with elements that contain references to objects of class InputStream or any of its subclasses can be passed to the method foo() shown in the above example. For example: FileInputStream f[] = new FileInputStream[3]; foo(f); Since FileInputStream is a subclass of InputStream, the call to foo() does not cause any problems at runtime. However, the following call to foo() is problematic: DataInputStream f[] = new DataInputStream[3]; foo(f); This call causes an ArrayStoreException to be thrown at runtime. Although DataInputStream is a subclass of InputStream, it is not a superclass of FileInputStream, so the array element assignment in foo() is not assignment-compatible. References Arithmetic Types; Array Types; Boolean Type; Class Types; Interface Types
Conditional Operator
http://localhost/java/javaref/langref/ch04_13.htm (4 of 4) [20/12/2001 11:18:54]
Order of Operations
[Chapter 4] 4.10 Bitwise/Logical Operators
Chapter 4 Expressions
4.10 Bitwise/Logical Operators The bitwise/logical operators in Java are used for bitwise and logical AND (&), bitwise and logical exclusive OR (^), and bitwise and logical inclusive OR (|) operations. These operators have different precedence; the & operator has the highest precedence of the group and the | operator has the lowest. All of the operators are evaluated from left to right. The unary operator ~ provides a bitwise negation operation. References Bitwise Negation Operator ~; Order of Operations
Bitwise/Logical AND Operator & The bitwise/logical AND operator & produces a pure value that is the AND of its operands. The & operator may appear in a bitwise or logical AND expression:
The bitwise/logical AND operator is evaluated from left to right. The operator never throws an exception. Here is a code example that shows the use of the bitwise AND operator: boolean isOdd(int x) { return (x & 1) == 1; } The operands of the bitwise/logical AND operator must both be of either an integer type or the type boolean, or a compile-time error occurs. If both operands are of integer types, the operator performs a bitwise AND operation. The operator may perform type conversions on the operands: ● If either operand is of type long, the other operand is converted to long and the operation http://localhost/java/javaref/langref/ch04_10.htm (1 of 3) [20/12/2001 11:18:57]
[Chapter 4] 4.10 Bitwise/Logical Operators
●
produces a long value. Otherwise, both operands are converted to int and the operation produces an int value.
The bitwise AND operator produces a pure value that is the bitwise AND of its operands. If the corresponding bits in both of the converted operands are 1s, the corresponding bit in the result is a 1; otherwise the corresponding bit in the result is a 0. If both operands are of type boolean, the operator performs a logical AND operation. The logical AND operation produces a pure value of type boolean. If both operands are true, the operation produces true; otherwise the operation produces false. This operator differs from the conditional AND operator (&&) because it always evaluates both of its operands, even if its left operand evaluates to false. References Boolean AND Operator &&; Boolean Type; Equality Comparison Operators; Integer types; Order of Operations
Bitwise/Logical Exclusive OR Operator ^ The bitwise/logical exclusive OR operator ^ produces a pure value that is the exclusive OR of its operands. The ^ operator may appear in a bitwise or logical exclusive OR expression:
The bitwise/logical exclusive OR operator is evaluated from left to right. The operator never throws an exception. The operands of the bitwise/logical exclusive OR operator must both be of either an integer type or the type boolean, or a compile-time error occurs. If both operands are of integer types, the operator performs a bitwise exclusive OR operation. The operator may perform type conversions on the operands: ● If either operand is of type long, the other operand is converted to long and the operation produces a long value. ● Otherwise, both operands are converted to int and the operation produces an int value. The bitwise exclusive OR operator produces a pure value that is the bitwise exclusive OR of its operands. If the corresponding bits in the converted operands are both 0 or both 1, the corresponding bit in the result is a 0; otherwise the corresponding bit in the result is a 1. If both operands are of type boolean, the operator performs a logical exclusive OR operation. The logical exclusive OR operation produces a pure value of type boolean. If either, but not both, operands are true, the operation produces true; otherwise the operation produces false. References Bitwise/Logical AND Operator &; Boolean Type; Integer types; Order of Operations
http://localhost/java/javaref/langref/ch04_10.htm (2 of 3) [20/12/2001 11:18:57]
[Chapter 4] 4.10 Bitwise/Logical Operators
Bitwise/Logical Inclusive OR Operator | The bitwise/logical inclusive OR operator | produces a pure value that is the inclusive OR of its operands. The | operator may appear in a bitwise or logical inclusive OR expression:
The bitwise/logical inclusive OR operator is evaluated from left to right. The operator never throws an exception. Here is a code example that shows the use of the bitwise inclusive OR operator: setFont("Helvetica", Font.BOLD | Font.ITALIC, 18); The operands of the bitwise/logical inclusive OR operator must both be of either an integer type or the type boolean, or a compile-time error occurs. If both operands are of integer types, the operator performs a bitwise inclusive OR operation. The operator may perform type conversions on the operands: ● If either operand is of type long, the other operand is converted to long and the operation produces a long value. ● Otherwise, both operands are converted to int and the operation produces an int value. The bitwise inclusive OR operator produces a pure value that is the bitwise inclusive OR of its operands. If the corresponding bits in either or both of the converted operands are 1s, the corresponding bit in the result is a 1; otherwise the corresponding bit in the result is a 0. If both operands are of type boolean, the operator performs a logical inclusive OR operation. The logical inclusive OR operation produces a pure value of type boolean. If either or both operands are true, the operation produces true; otherwise the operation produces false. This operator differs from the conditional OR operator (||) because it always evaluates both of its operands, even if its left operand evaluates to true. References Boolean OR Operator ||; Boolean Type; Bitwise/Logical Exclusive OR Operator ^; Integer types; Order of Operations
Equality Comparison Operators
http://localhost/java/javaref/langref/ch04_10.htm (3 of 3) [20/12/2001 11:18:57]
Boolean Operators
[Chapter 10] Byte
Chapter 10 The java.lang Package
Byte Name Byte
Synopsis Class Name: java.lang.Byte Superclass: java.lang.Number Immediate Subclasses: None Interfaces Implemented: None Availability: New as of JDK 1.1
Description The Byte class provides an object wrapper for a byte value. This is useful when you need to treat a byte value as an object. For example, there are a number of utility methods that take a reference to an Object as one of their arguments. You cannot specify a byte value for one of these arguments, but you can provide a reference to a Byte object that encapsulates the byte value. Furthermore, the Byte class is necessary as of JDK 1.1 to support the Reflection API and class literals. The Byte class also provides a number of utility methods for converting byte values to other primitive types and for converting byte values to strings and vice versa.
http://localhost/java/javaref/langref/ch10_02.htm (1 of 9) [20/12/2001 11:18:59]
[Chapter 10] Byte
Class Summary public final class java.lang.Byte extends java.lang.Number { // Constants public static final byte MAX_VALUE; public static final byte MIN_VALUE; public static final Class TYPE; // Constructors public Byte(byte value); public Byte(String s); // Class Methods public static Byte decode(String nm); public static byte parseByte(String s); public static byte parseByte(String s, int radix); public static String toString(byte b); public static Byte valueOf(String s, int radix); public static Byte valueOf(String s); // Instance Methods public byte byteValue(); public double doubleValue; public boolean equals(Object obj); public float floatValue public int hashCode(); public int intValue(); public long longValue(); public short shortValue(); public String toString(); }
Constants MAX_VALUE public static final byte MAX_VALUE= 127 The largest value that can be represented by a byte.
MIN_VALUE public static final byte MIN_VALUE= -128 The smallest value that can be represented by a byte.
TYPE public static final Class TYPE The Class object that represents the primitive type byte. It is always true that Byte.TYPE == byte.class.
http://localhost/java/javaref/langref/ch10_02.htm (2 of 9) [20/12/2001 11:18:59]
[Chapter 10] Byte
Constructors Byte public Byte(byte value) Parameters value The byte value to be encapsulated by this object. Description Creates a Byte object with the specified byte value. public Byte(String s) throws NumberFormatException Parameters s The string to be made into a Byte object. Throws NumberFormatException If the sequence of characters in the given String does not form a valid byte literal. Description Constructs a Byte object with the value specified by the given string. The string should consist of one or more digit characters. The digit characters can be preceded by a single `-' character. If the string contains any other characters, the constructor throws a NumberFormatException.
Class Methods decode public static Byte decode(String nm) throws NumberFormatException Parameters nm A String representation of the value to be encapsulated by a Byte object. If the string begins with # or 0x, it is a radix 16 representation of the value. If the string begins with 0, it is a radix 8 representation of the value. Otherwise, it is assumed to be a radix 10 representation of the value. Returns A Byte object that encapsulates the given value. Throws NumberFormatException If the String contains any non-digit characters other than a leading minus sign or the value represented by the String is less than Byte.MIN_VALUE or greater than Byte.MAX_VALUE.
http://localhost/java/javaref/langref/ch10_02.htm (3 of 9) [20/12/2001 11:18:59]
[Chapter 10] Byte
Description This method returns a Byte object that encapsulates the given value.
parseByte public static byte parseByte(String s) throws NumberFormatException Parameters s The String to be converted to a byte value. Returns The numeric value of the byte represented by the String object. Throws NumberFormatException If the String does not contain a valid representation of a byte or the value represented by the String is less than Byte.MIN_VALUE or greater than Byte.MAX_VALUE. Description This method returns the numeric value of the byte represented by the contents of the given String object. The String must contain only decimal digits, except that the first character may be a minus sign. public static byte parseByte(String s, int radix) throws NumberFormatException Parameters s The String to be converted to a byte value. radix The radix used in interpreting the characters in the String as digits. This value must be in the range Character.MIN_RADIX to Character.MAX_RADIX. If radix is in the range 2 through 10, only characters for which the Character.isDigit() method returns true are considered to be valid digits. If radix is in the range 11 through 36, characters in the ranges `A' through `Z' and `a' through `z' may be considered valid digits. Returns The numeric value of the byte represented by the String object in the specified radix. Throws NumberFormatException If the String does not contain a valid representation of a byte, radix is not in the appropriate range, or the value represented by the String is less than Byte.MIN_VALUE or greater than Byte.MAX_VALUE. Description This method returns the numeric value of the byte represented by the contents of the given String object in the specified radix. The String must contain only valid digits of the specified radix, except that the first character may be a minus sign. The digits are parsed in the specified radix to produce the numeric value.
http://localhost/java/javaref/langref/ch10_02.htm (4 of 9) [20/12/2001 11:18:59]
[Chapter 10] Byte
toString public String toString(byte b) Parameters b The byte value to be converted to a string. Returns The string representation of the given value. Description This method returns a String object that contains the decimal representation of the given value. This method returns a string that begins with `-' if the given value is negative. The rest of the string is a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', `7', `8', and `9'. This method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with "0" or "-0".
valueOf public static Byte valueOf(String s) throws NumberFormatException Parameters s The string to be made into a Byte object. Returns The Byte object constructed from the string. Throws NumberFormatException If the String does not contain a valid representation of a byte or the value represented by the String is less than Byte.MIN_VALUE or greater than Byte.MAX_VALUE. Description Constructs a Byte object with the value specified by the given string. The string should consist of one or more digit characters. The digit characters can be preceded by a single `-' character. If the string contains any other characters, the method throws a NumberFormatException. public static Byte valueOf(String s, int radix) throws NumberFormatException Parameters s The string to be made into a Byte object. radix The radix used in converting the string to a value. This value must be in the range Character.MIN_RADIX to Character.MAX_RADIX. Returns The Byte object constructed from the string. http://localhost/java/javaref/langref/ch10_02.htm (5 of 9) [20/12/2001 11:18:59]
[Chapter 10] Byte
Throws NumberFormatException If the String does not contain a valid representation of a byte, radix is not in the appropriate range, or the value represented by the String is less than Byte.MIN_VALUE or greater than Byte.MAX_VALUE. Description Constructs a Byte object with the value specified by the given string in the specified radix. The string should consist of one or more digit characters or characters in the range `A' to `Z' or `a' to `z' that are considered digits in the given radix. The digit characters can be preceded by a single `-' character. If the string contains any other characters, the method throws a NumberFormatException.
Instance Methods byteValue public byte byteValue() Returns The value of this object as a byte. Overrides Number.byteValue() Description This method returns the value of this object as a byte.
doubleValue public double doubleValue() Returns The value of this object as a double. Overrides Number.doubleValue() Description This method returns the value of this object as a double.
equals public boolean equals(Object obj) Parameters obj The object to be compared with this object. Returns http://localhost/java/javaref/langref/ch10_02.htm (6 of 9) [20/12/2001 11:18:59]
[Chapter 10] Byte
true if the objects are equal; false if they are not. Overrides Object.equals() Description This method returns true if obj is an instance of Byte and it contains the same value as the object this method is associated with.
floatValue public float floatValue() Returns The value of this object as a float. Overrides Number.floatValue() Description This method returns the value of this object as a float.
hashCode public int hashCode() Returns A hashcode based on the byte value of the object. Overrides Object.hashCode() Description This method returns a hashcode computed from the value of this object.
intValue public int intValue() Returns The value of this object as an int. Overrides Number.intValue() Description This method returns the value of this object as an int.
http://localhost/java/javaref/langref/ch10_02.htm (7 of 9) [20/12/2001 11:18:59]
[Chapter 10] Byte
longValue public long longValue() Returns The value of this object as a long. Overrides Number.longValue() Description This method returns the value of this object as a long.
shortValue public short shortValue() Returns The value of this object as a short. Overrides Number.shortValue() Description This method returns the value of this object as a short.
toString public String toString() Returns The string representation of the value of this object. Overrides Object.toString() Description This method returns a String object that contains the decimal representation of the value of this object. This method returns a string that begins with `-` if the given value is negative. The rest of the string is a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', `7', `8', and `9'. This method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with "0" or "-0".
Inherited Methods Method Inherited From Method clone() Object finalize() getClass() Object notify() notifyAll() Object wait()
Inherited From Object Object Object
http://localhost/java/javaref/langref/ch10_02.htm (8 of 9) [20/12/2001 11:18:59]
[Chapter 10] Byte
wait(long) Object
wait(long, int) Object
See Also Character; Class; Double; Exceptions; Float; Integer literals; Integer types; Integer; Long; Number; Short; String
Boolean
http://localhost/java/javaref/langref/ch10_02.htm (9 of 9) [20/12/2001 11:18:59]
Character
[Chapter 10] Character
Chapter 10 The java.lang Package
Character Name Character
Synopsis Class Name: java.lang.Character Superclass: java.lang.Object Immediate Subclasses: None Interfaces Implemented: java.io.Serializable Availability: JDK 1.0 or later
Description The Character class provides an object wrapper for a char value. This is useful when you need to treat a char value as an object. For example, there are a number of utility methods that take a reference to an Object as one of their arguments. You cannot specify a char value for one of these arguments, but you can provide a reference to a Character object that encapsulates the char value. Furthermore, as of JDK 1.1, the Character class is necessary to support the Reflection API and class literals. In Java, Character objects represent values defined by the Unicode standard. Unicode is defined by an organization called the Unicode Consortium. The defining document for Unicode is The Unicode Standard, Version 2.0 (ISBN 0-201-48345-9). More recent information about Unicode is available at http://unicode.org. Appendix a, The Unicode 2.0 Character Set, contains a table that lists the characters defined by the Unicode 2.0 standard. http://localhost/java/javaref/langref/ch10_03.htm (1 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
The Character class provides some utility methods, such as methods for determining the type (e.g., uppercase or lowercase, digit or letter) of a character and for converting from uppercase to lowercase. The logic for these utility methods is based on a Unicode attribute table that is part of the Unicode standard. That table is available at ftp://unicode.org/pub/2.0-Update/UnicodeData-2.0.14.txt. Some of the methods in the Character class are concerned with characters that are digits; these characters are used by a number of other classes to convert strings that contain numbers into actual numeric values. The digit-related methods all use a radix value to interpret characters. The radix is the numeric base used to represent numbers as characters or strings. Octal is a radix 8 representation, while hexadecimal is a radix 16 representation. The methods that require a radix parameter use it to determine which characters should be treated as valid digits. In radix 2, only the characters `0' and `1' are valid digits. In radix 16, the characters `0' through `9', `a' through `z', and `A' through `Z' are considerd valid digits.
Class Summary public final class java.lang.Character extends java.lang.Object implements java.io.Serializable { // Constants public final static byte COMBINING_SPACING_MARK; // New in 1.1 public final static byte CONNECTOR_PUNCTUATION; // New in 1.1 public final static byte CONTROL; // New in 1.1 public final static byte CURRENCY_SYMBOL; // New in 1.1 public final static byte DASH_PUNCTUATION; // New in 1.1 public final static byte DECIMAL_DIGIT_NUMBER; // New in 1.1 public final static byte ENCLOSING_MARK; // New in 1.1 public final static byte END_PUNCTUATION; // New in 1.1 public final static byte FORMAT; // New in 1.1 public final static byte LETTER_NUMBER; // New in 1.1 public final static byte LINE_SEPARATOR; // New in 1.1 public final static byte LOWERCASE_LETTER; // New in 1.1 public final static byte MATH_SYMBOL; // New in 1.1 public final static int MAX_RADIX; public final static char MAX_VALUE; public final static int MIN_RADIX; public final static char MIN_VALUE; public final static byte MODIFIER_LETTER; // New in 1.1 public final static byte MODIFIER_SYMBOL; // New in 1.1 public final static byte NON_SPACING_MARK; // New in 1.1 public final static byte OTHER_LETTER; // New in 1.1 public final static byte OTHER_NUMBER; // New in 1.1 public final static byte OTHER_PUNCTUATION; // New in 1.1 public final static byte OTHER_SYMBOL; // New in 1.1 public final static byte PARAGRAPH_SEPARATOR; // New in 1.1 public final static byte PRIVATE_USE; // New in 1.1 public final static byte SPACE_SEPARATOR; // New in 1.1 public final static byte START_PUNCTUATION; // New in 1.1 public final static byte SURROGATE; // New in 1.1
http://localhost/java/javaref/langref/ch10_03.htm (2 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
public final static byte TITLECASE_LETTER; // New in public final static Class TYPE; // New in public final static byte UNASSIGNED; // New in public final static byte UPPERCASE_LETTER; // New in // Constructors public Character(char value); // Class Methods public static int digit(char ch, int radix); public static char forDigit(int digit, int radix); public static int getNumericValue(char ch); // New in public static int getType(char ch); // New in public static boolean isDefined(char ch); public static boolean isDigit(char ch); public static boolean isIdentifierIgnorable(char ch); // New in public static boolean isISOControl(char ch); // New in public static boolean isJavaIdentifierPart(char ch); // New in public static boolean isJavaIdentifierStart(char ch); // New in public static boolean isJavaLetter(char ch); // Deprecated public static boolean isJavaLetterOrDigit(char ch); // Deprecated public static boolean isLetter(char ch); public static boolean isLetterOrDigit(char ch); public static boolean isLowerCase(char ch); public static boolean isSpace(char ch); // Deprecated public static boolean isSpaceChar(char ch); // New in public static boolean isTitleCase(char ch); public static boolean isUnicodeIdentifierPart(char ch); // New in public static boolean isUnicodeIdentifierStart(char ch);// New in public static boolean isUpperCase(char ch); public static boolean isWhitespace(char ch); // New in public static char toLowerCase(char ch); public static char toTitleCase(char ch); public static char toUpperCase(char ch); // Instance Methods public char charValue(); public boolean equals(Object obj); public int hashCode(); public String toString(); }
Constants COMBINING_SPACING_MARK public final static byte COMBINING_SPACING_MARK Availability New as of JDK 1.1 Description http://localhost/java/javaref/langref/ch10_03.htm (3 of 23) [20/12/2001 11:19:04]
1.1 1.1 1.1 1.1
1.1 1.1
1.1 1.1 1.1 1.1 in 1.1 in 1.1
in 1.1 1.1 1.1 1.1 1.1
[Chapter 10] Character
This constant can be returned by the getType() method as the general category of a Unicode character.
CONNECTOR_PUNCTUATION public final static byte CONNECTOR_PUNCTUATION Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
CONTROL public final static byte CONTROL Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
CURRENCY_SYMBOL public final static byte CURRENCY_SYMBOL Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
DASH_PUNCTUATION public final static byte DASH_PUNCTUATION Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
DECIMAL_DIGIT_NUMBER public final static byte DECIMAL_DIGIT_NUMBER Availability http://localhost/java/javaref/langref/ch10_03.htm (4 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
ENCLOSING_MARK public final static byte ENCLOSING_MARK Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
END_PUNCTUATION public final static byte END_PUNCTUATION Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
FORMAT public final static byte FORMAT Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
LETTER_NUMBER public final static byte LETTER_NUMBER Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
http://localhost/java/javaref/langref/ch10_03.htm (5 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
LINE_SEPARATOR public final static byte LINE_SEPARATOR Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
LOWERCASE_LETTER public final static byte LOWERCASE_LETTER Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
MATH_SYMBOL public final static byte MATH_SYMBOL Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
MAX_RADIX public static final int MAX_RADIX = 36 Description The maximum value that can be specified for a radix.
MAX_VALUE public final static char MAX_VALUE = '\ufff'f Description The largest value that can be represented by a char.
http://localhost/java/javaref/langref/ch10_03.htm (6 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
MIN_RADIX public static final int MIN_RADIX = 2 Description The minimum value that can be specified for a radix.
MIN_VALUE public final static char MIN_VALUE = '\u0000' Description The smallest value that can be represented by a char.
MODIFIER_LETTER public final static byte MODIFIER_LETTER Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
MODIFIER_SYMBOL public final static byte MODIFIER_SYMBOL Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
NON_SPACING_MARK public final static byte NON_SPACING_MARK Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
http://localhost/java/javaref/langref/ch10_03.htm (7 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
OTHER_LETTER public final static byte OTHER_LETTER Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
OTHER_NUMBER public final static byte OTHER_NUMBER Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
OTHER_PUNCTUATION public final static byte OTHER_PUNCTUATION Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
OTHER_SYMBOL public final static byte OTHER_SYMBOL Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
PARAGRAPH_SEPARATOR public final static byte PARAGRAPH_SEPARATOR Availability New as of JDK 1.1 Description http://localhost/java/javaref/langref/ch10_03.htm (8 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
This constant can be returned by the getType() method as the general category of a Unicode character.
PRIVATE_USE public final static byte PRIVATE_USE Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
SPACE_SEPARATOR public final static byte SPACE_SEPARATOR Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
START_PUNCTUATION public final static byte START_PUNCTUATION Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
SURROGATE public final static byte SURROGATE Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
TITLECASE_LETTER public final static byte TITLECASE_LETTER Availability
http://localhost/java/javaref/langref/ch10_03.htm (9 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
TYPE public static final Class TYPE Availability New as of JDK 1.1 Description The Class object that represents the type char. It is always true that Character.TYPE == char.class.
UNASSIGNED public final static byte UNASSIGNED Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
UPPERCASE_LETTER public final static byte UPPERCASE_LETTER Availability New as of JDK 1.1 Description This constant can be returned by the getType() method as the general category of a Unicode character.
Constructors Character public Character(char value) Parameters value The char value to be encapsulated by this object. Description
http://localhost/java/javaref/langref/ch10_03.htm (10 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
Creates a Character object with the given char value.
Class Methods digit public static int digit(char ch, int radix) Parameters ch A char value that is a legal digit in the given radix. radix The radix used in interpreting the specified character as a digit. If radix is in the range 2 through 10, only characters for which the isDigit() method returns true are considered to be valid digits. If radix is in the range 11 through 36, characters in the ranges `A' through `Z' and `a' through `z' may be considered valid digits. Returns The numeric value of the digit. This method returns -1 if the value of ch is not considered a valid digit, if radix is less than MIN_RADIX, or if radix is greater than MAX_RADIX. Description Returns the numeric value represented by a digit character. For example, digit('7',10) returns 7. If the value of ch is not a valid digit, the method returns -1. For example, digit('7',2) returns -1 because '7' is not a valid digit in radix 2. A number of methods in other classes use this method to convert strings that contain numbers to actual numeric values. The forDigit() method is an approximate inverse of this method. If radix is greater than 10, characters in the range `A' to `A'+radix-11 are treated as valid digits. Such a character has the numeric value ch-`A'+10. By the same token, if radix is greater than 10, characters in the range `a' to `a'+radix-11 are treated as valid digits. Such a character has the numeric value ch-`a'+10.
forDigit public static char forDigit(int digit, int radix) Parameters digit The numeric value represented as a digit character. radix The radix used to represent the specified value. Returns The character that represents the digit corresponding to the specified numeric value. The method returns `\ 0' if digit is less than 0, if digit is equal to or greater than radix, if radix is less than MIN_RADIX, or if radix is greater than MAX_RADIX. http://localhost/java/javaref/langref/ch10_03.htm (11 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
Description This method returns the character that represents the digit corresponding to the specified numeric value. If digit is in the range 0 through 9, the method returns `0'+digit. If digit is in the range 10 through MAX_RADIX-1, the method returns `a'+digit-10. The method returns `\ 0' if digit is less than 0, if digit is equal to or greater than radix, if radix is less than MIN_RADIX, or if radix is greater than MAX_RADIX.
getNumericValue public static int getNumericValue(char ch) Availability New as of JDK 1.1 Parameters ch A char value. Returns The Unicode numeric value of the character as a nonnegative integer. This method returns -1 if the character has no numeric value; it returns -2 if the character has a numeric value that is not a nonnegative integer, such as 1/2. Description This method returns the Unicode numeric value of the specified character as a nonnegative integer.
getType public static int getType(char ch) Availability New as of JDK 1.1 Parameters ch A char value. Returns An int value that represents the Unicode general category type of the character. Description This method returns the Unicode general category type of the specified character. The value corresponds to one of the general category constants defined by Character.
http://localhost/java/javaref/langref/ch10_03.htm (12 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
isDefined public static boolean isDefined(char ch) Parameters ch A char value to be tested. Returns true if the specified character has an assigned meaning in the Unicode character set; otherwise false. Description This method returns true if the specified character value has an assigned meaning in the Unicode character set.
isDigit public static boolean isDigit(char ch) Parameters ch A char value to be tested. Returns true if the specified character is defined as a digit in the Unicode character set; otherwise false. Description This method determines whether or not the specified character is a digit, based on the definition of the character in Unicode.
isIdentifierIgnorable public static boolean isIdentifierIgnorable(char ch) Availability New as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character is ignorable in a Java or Unicode identifier; otherwise false. Description This method determines whether or not the specified character is ignorable in a Java or Unicode identifier. The following characters are ignorable in a Java or Unicode identifier:
http://localhost/java/javaref/langref/ch10_03.htm (13 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
\u0000 \u009F \u200C \u200A \u206A \uFEFF
- \u0008 \u000E - \u001B \u007F - \u200F - \u200E - \u206F
ISO control characters that aren't whitespace Join controls Bidirectional controls Format controls Zero-width no-break space
isISOControl public static boolean isISOControl(char ch) Availability New as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character is an ISO control character; otherwise false. Description This method determines whether or not the specified character is an ISO control character. A character is an ISO control character if it falls in the range \u0000 through \u001F or \u007F through \u009F.
isJavaIdentifierPart public static boolean isJavaIdentifierPart(char ch) Availability New as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character can appear after the first character in a Java identifier; otherwise false. Description This method returns true if the specified character can appear in a Java identifier after the first character. A character is considered part of a Java identifier if and only if it is a letter, a digit, a currency symbol (e.g., $), a connecting punctuation character (e.g., _), a numeric letter (e.g., a Roman numeral), a combining mark, a nonspacing mark, or an ignorable control character.
http://localhost/java/javaref/langref/ch10_03.htm (14 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
isJavaIdentifierStart public static boolean isJavaIdentifierStart(char ch) Availability New as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character can appear as the first character in a Java identifier; otherwise false. Description This method returns true if the specified character can appear in a Java identifier as the first character. A character is considered a start of a Java identifier if and only if it is a letter, a currency symbol (e.g., $), or a connecting punctuation character (e.g., _).
isJavaLetter public static boolean isJavaLetter(char ch) Availability Deprecated as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character can appear as the first character in a Java identifier; otherwise false. Description This method returns true if the specified character can appear as the first character in a Java identifier. A character is considered a Java letter if and only if it is a letter, the character $, or the character _ . This method returns false for digits because digits are not allowed as the first character of an identifier. This method is deprecated as of JDK 1.1. You should use isJavaIdentifierStart() instead.
isJavaLetterOrDigit public static boolean isJavaLetterOrDigit(char ch) Availability Deprecated as of JDK 1.1 Parameters ch http://localhost/java/javaref/langref/ch10_03.htm (15 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
A char value to be tested. Returns true if the specified character can appear after the first character in a Java identifier; otherwise false. Description This method returns true if the specified character can appear in a Java identifier after the first character. A character is considered a Java letter or digit if and only if it is a letter, a digit, the character $, or the character _. This method is deprecated as of JDK 1.1. You should use isJavaIdentifierPart() instead.
isLetter public static boolean isLetter(char ch) Parameters ch A char value to be tested. Returns true if the specified character is defined as a letter in the Unicode character set; otherwise false. Description This method determines whether or not the specified character is a letter, based on the definition of the character in Unicode. This method does not consider character values in ranges that have not been assigned meanings by Unicode to be letters.
isLetterOrDigit public static boolean isLetterOrDigit(char ch) Parameters ch A char value to be tested. Returns true if the specified character is defined as a letter in the Unicode character set; otherwise false. Description This method determines whether or not the specified character is a letter or a digit, based on the definition of the character in Unicode. There are some ranges that have not been assigned meanings by Unicode. If a character value is in one of these ranges, this method does not consider the character to be a letter.
http://localhost/java/javaref/langref/ch10_03.htm (16 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
isLowerCase public static boolean isLowerCase (char ch) Parameters ch A char value to be tested. Returns true if the specified character is defined as lowercase in the Unicode character set; otherwise false. Description This method determines whether or not the specified character is lowercase. Unicode defines a number of characters that do not have case mappings; if the specified character is one of these characters, the method returns false.
isSpace public static boolean isSpace(char ch) Availability Deprecated as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character is defined as whitespace in the ISO-Latin-1 character set; otherwise false. Description This method determines whether or not the specified character is whitespace. This method recognizes the whitespace characters shown in the following table. Horizontal tab \u0009 Newline \u000A Formfeed \u000C Carriage return \u000D \u0020 ` ` Space This method is deprecated as of JDK 1.1. You should use isWhitespace() instead.
isSpaceChar public static boolean isSpaceChar(char ch) Availability
http://localhost/java/javaref/langref/ch10_03.htm (17 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
New as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character is a Unicode 2.0 space characters; otherwise false. Description This method determines if the specified character is a space character according to the Unicode 2.0 specification. A character is considered to be a Unicode space character if and only if it has the general category "Zs", "Zl", or "Zp" in the Unicode specification.
isTitleCase public static boolean isTitleCase(char ch) Parameters ch A char value to be tested. Returns true if the specified character is defined as titlecase in the Unicode character set; otherwise false. Description This method determines whether or not the specified character is a titlecase character. Unicode defines a number of characters that do not have case mappings; if the specified character is one of these characters, the method returns false. Many characters are defined by the Unicode standard as having upper- and lowercase forms. There are some characters defined by the Unicode standard that also have a titlecase form. The glyphs for these characters look like a combination of two Latin letters. The titlecase form of these characters has a glyph that looks like a combination of an uppercase Latin character and a lowercase Latin character; this case should be used when the character appears as the first character of a word in a title. For example, one of the Unicode characters that has a titlecase form looks like the letter `D' followed by the letter `Z'. Here is what the three forms of this letter look like: Uppercase `DZ' Titlecase `Dz' Lowercase `dz'
isUnicodeIdentifierPart public static boolean isUnicodeIdentifierPart(char ch) Availability New as of JDK 1.1
http://localhost/java/javaref/langref/ch10_03.htm (18 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
Parameters ch A char value to be tested. Returns true if the specified character can appear after the first character in a Unicode identifier; otherwise false. Description This method returns true if the specified character can appear in a Unicode identifier after the first character. A character is considered part of a Unicode identifier if and only if it is a letter, a digit, a connecting punctuation character (e.g., _), a numeric letter (e.g., a Roman numeral), a combining mark, a nonspacing mark, or an ignorable control character.
isUnicodeIdentifierStart public static boolean isUnicodeIdentifierStart(char ch) Availability New as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character can appear as the first character in a Unicode identifier; otherwise false. Description This method returns true if the specified character can appear in a Unicode identifier as the first character. A character is considered a start of a Unicode identifier if and only if it is a letter.
isUpperCase public static boolean isUpperCase(char ch) Parameters ch A char value to be tested. Returns true if the specified character is defined as uppercase in the Unicode character set; otherwise false. Description This method determines whether or not the specified character is uppercase. Unicode defines a number of characters that do not have case mappings; if the specified character is one of these characters, the method returns false.
http://localhost/java/javaref/langref/ch10_03.htm (19 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
isWhitespace public static boolean isWhitespace(char ch) Availability New as of JDK 1.1 Parameters ch A char value to be tested. Returns true if the specified character is defined as whitespace according to Java; otherwise false. Description This method determines whether or not the specified character is whitespace. This method recognizes the following as whitespace: Unicode category "Zs" except \u00A0 and \uFEFF Unicode space separators except no-break spaces Unicode category "Zl" Unicode line separators Unicode category "Zp" Unicode paragraph separators Horizontal tab \u0009 Linefeed \u000A Vertical tab \u000B Formfeed \u000C Carriage return \u000D File separator \u001C Group separator \u001D Record separator \u001E Unit separator \u001F
toLowerCase public static char toLowerCase(char ch) Parameters ch A char value to be converted to lowercase. Returns The lowercase equivalent of the specified character, or the character itself if it cannot be converted to lowercase. Description This method returns the lowercase equivalent of the specified character value. If the specified character is not uppercase or if it has no lowercase equivalent, the character is returned unmodified. The Unicode
http://localhost/java/javaref/langref/ch10_03.htm (20 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
attribute table determines if a character has a mapping to a lowercase equivalent. Some Unicode characters in the range \u2000 through \u2FFF have lowercase mappings. For example, \u2160 (Roman numeral one) has a lowercase mapping to \u2170 (small Roman numeral one). The toLowerCase() method maps such characters to their lowercase equivalents even though the method isUpperCase() does not return true for such characters.
toTitleCase public static char toTitleCase(char ch) Parameters ch A char value to be converted to titlecase. Returns The titlecase equivalent of the specified character, or the character itself if it cannot be converted to titlecase. Description This method returns the titlecase equivalent of the specified character value. If the specified character has no titlecase equivalent, the character is returned unmodified. The Unicode attribute table is used to determine the character's titlecase equivalent. Many characters are defined by the Unicode standard as having upper- and lowercase forms. There are some characters defined by the Unicode standard that also have a titlecase form. The glyphs for these characters look like a combination of two Latin letters. The titlecase form of these characters has a glyph that looks like a combination of an uppercase Latin character and a lowercase Latin character; this case should be used when the character appears as the first character of a word in a title. For example, one of the Unicode characters that has a titlecase form looks like the letter `D' followed by the letter `Z'. Here is what the three forms of this letter look like: Uppercase `DZ' Titlecase `Dz' Lowercase `dz'
toUpperCase public static char toUpperCase(char ch) Parameters ch A char value to be converted to lowercase. Returns The uppercase equivalent of the specified character, or the character itself if it cannot be converted to uppercase. Description
http://localhost/java/javaref/langref/ch10_03.htm (21 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
This method returns the uppercase equivalent of the specified character value. If the specified character is not lowercase or if it has no uppercase equivalent, the character is returned unmodified. The Unicode attribute table determines if a character has a mapping to an uppercase equivalent. Some Unicode characters in the range \u2000 through \u2FFF have uppercase mappings. For example, \u2170 (small Roman numeral one) has a lowercase mapping to \u2160 (Roman numeral one). The toUpperCase() method maps such characters to their uppercase equivalents even though the method isLowerCase() does not return true for such characters.
Instance Methods charValue public char charValue() Returns The char value contained by the object.
equals public boolean equals(Object obj) Parameters The object to be compared with this object. Returns true if the objects are equal; false if they are not. Overrides Object.equals() Description This method returns true if obj is an instance of Character, and it contains the same value as the object this method is associated with.
hashCode public int hashCode() Returns A hashcode based on the char value of the object. Overrides Object.hashCode()
http://localhost/java/javaref/langref/ch10_03.htm (22 of 23) [20/12/2001 11:19:04]
[Chapter 10] Character
toString public String toString() Returns A String of length one that contains the character value of the object. Overrides Object.toString() Description This method returns a string representation of the Character object.
Inherited Methods Method Inherited From Method Inherited From clone() Object finalize() Object getClass() Object notify() Object notifyAll() Object wait() Object wait(long) Object wait(long, int) Object
See Also Character literals; Class; Integer types; Object
Byte
http://localhost/java/javaref/langref/ch10_03.htm (23 of 23) [20/12/2001 11:19:04]
Class
[Chapter 4] 4.12 Conditional Operator
Chapter 4 Expressions
4.12 Conditional Operator The conditional operator (? :) is a ternary operator. The operator selects one of two expressions for evaluation, based on the value of its first operand. In this way, the conditional operator is similar to an if statement. A conditional operator may appear in a conditional expression:
The conditional operator produces a pure value. Conditional expressions group from right to left. Consider the following expression: g?f:e?d:c?b:a It is equivalent to g?f:(e?d:(c?b:a)) The first operand of the conditional operator must be of type boolean, or a compile-time error occurs. If the first operand evaluates to true, the operator evaluates the second operand (i.e., the one following the ?) and produces the pure value of that expression. Otherwise, if the first operand evaluates to false, the operator evaluates the third operand (i.e., the one following the :) and produces the pure value of that expression. Note that the conditional operator evaluates either its second operand or its third operand, but not both. The second and third operands of the conditional operator may be of any type, but they must both be of the same kind of type or a compile-time error occurs. If one operand is of an arithmetic type, the other must also be of an arithmetic type. If one operand is of type boolean, the other must also be of type boolean. If one operand is a reference type, the other must also be a reference type. Note that neither the second nor the third operand can be an expression that invokes a void method. The types of the second and third operands determine the type of pure value that the conditional operator produces. If the second and third operands are of different types, the operator may perform a type conversion on the operand that it evaluates. The operator does this to ensure that it always produces the
http://localhost/java/javaref/langref/ch04_12.htm (1 of 2) [20/12/2001 11:19:06]
[Chapter 4] 4.12 Conditional Operator
same type of result for a given expression, regardless of the value of its first operand. If the second and third operands are both of arithmetic types, the conditional operator determines the type of value it produces as follows:[6] ● If both operands are of the same type, the conditional operator produces a pure value of that type.
●
●
● ● ● ●
[6] Some of these rules are different from the way it is done in C/C++. In those languages, integer data of types smaller than int are always converted to int when they appear in any expression. If one operand is of type short and the other operand is of type byte, the conditional operator produces a short value. If one operand is of type short, char, or byte and the other operand is a constant expression that can be represented as a value of that type, the conditional operator produces a pure value of that type. Otherwise, if either operand is of type double, the operator produces a double value. Otherwise, if either operand is of type float, the operator produces a float value. Otherwise, if either operand is of type long, the operator produces a long value. Otherwise, if either operand is of type int, the operator produces an int value.
If the second and third operands are both of type boolean, the conditional operator produces a pure boolean value. If the second and third operands are both reference types, the conditional operator determines the type of value it produces as follows: ● If both operands are null, the conditional operator produces the pure value null. ● Otherwise, if exactly one of the operands is null, the conditional operator produces a value of the type of the other operand. ● Otherwise, it must be possible to cast the value of one of the operands to the type of the other operand, or a compile-time error occurs. The conditional operator produces a value of the type that would be the target of the cast. References Arithmetic Types; Boolean Type; Boolean OR Operator ||; Expression 4; Order of Operations; Reference Types
Boolean Operators
http://localhost/java/javaref/langref/ch04_12.htm (2 of 2) [20/12/2001 11:19:06]
Assignment Operators
[Chapter 4] 4.9 Equality Comparison Operators
Chapter 4 Expressions
4.9 Equality Comparison Operators The equality comparison operators in Java are used for equal-to (==) and not-equal-to (!=) comparison operations. The equality comparison operators may appear in an equality expression:
The equality comparison operators are equal in precedence and are evaluated from left to right. The == and != comparison operators can perform numerical comparisons, boolean comparisons, and reference type comparisons. Both of these operators produce boolean values. References Relational Comparison Operators; Order of Operations
Equal-To Operator == The equal-to operator == performs a comparison between its operands and returns a boolean value. It returns the pure value true if the operands are equal to each other; otherwise it returns the pure value false. The == operator may appear as part of an equality expression. The equal-to operator never throws an exception. The operands of == may be of any type, but they must both be of the same kind of type or a compile-time error occurs. If one operand is of an arithmetic type, the other must also be of an arithmetic type. If one operand is of type boolean, the other must also be of type boolean. If one operand is a reference type, the other must also be a reference type. Note that neither operand can be an expression that invokes a void method. If both operands are of arithmetic types, then the operator performs an arithmetic equality comparison. The operator may perform type conversions on the operands: ● If either operand is of type double, then the other operand is converted to double. ● Otherwise, if either operand is of type float, the other operand is converted to float. ● Otherwise, if either operand is of type long, the other operand is converted to long.
http://localhost/java/javaref/langref/ch04_09.htm (1 of 3) [20/12/2001 11:19:12]
[Chapter 4] 4.9 Equality Comparison Operators
●
Otherwise, both operands are converted to int.
The equality comparison of any two arithmetic values produces true if and only if both operands are the same value; otherwise the comparison produces false. The comparison of floating-point data is governed by the following additional rules: ● If either operand is not-a-number (NaN), the comparison produces false. ● Positive infinity is a distinct value that is equal to itself, and not equal to any other value. ● Negative infinity is a distinct value that is equal to itself, and not equal to any other value. ● Positive and negative zero are treated as equal, so -0.0==0.0 produces true. If both operands are boolean values, the operator performs a Boolean equality comparison. The comparison produces true if both operands are true or both operands are false. Otherwise, the comparison produces false. If both operands are reference types, the operator performs an object equality comparison. In order to perform this type of comparison, it must be possible to cast the value of one of the operands to the type of the other operand, or a compile-time error occurs. The comparison produces true if both of its operands refer to the same object or if both of its operands are null; otherwise the comparison produces false. Because the == operator determines if two objects are the same object, it is not appropriate for comparisons that need to determine if two objects have the same contents. For example, if you need to know whether two String objects contain the same sequences of characters, the == operator is inappropriate. You should use the equals() method instead:[4] [4] This is similar to the difference in C between writing string1==string2 and strcmp(string1, string2)==0. string1.equals (string2) string1 == string2
// Compares contents of strings // Compares actual string objects
References Arithmetic Types; Boolean Type; Reference Types
Not-Equal-To-Operator != The not-equal-to operator != performs a comparison between its operands and returns a boolean value. It returns the pure value true if the operands are not equal to each other; otherwise it returns the pure value false. The != operator may appear as part of an equality expression. The not-equal-to operator never throws an exception. The operands of != may be of any type, but they must both be of the same kind of type or a compile-time error occurs. If one operand is of an arithmetic type, the other must also be of an arithmetic type. If one operand is of type boolean, the other must also be of type boolean. If one operand is a reference type, the other must also be a reference type. Note that neither operand can be an expression that invokes a void method. If both operands are of arithmetic types, the operator performs an arithmetic inequality comparison. The http://localhost/java/javaref/langref/ch04_09.htm (2 of 3) [20/12/2001 11:19:12]
[Chapter 4] 4.9 Equality Comparison Operators
operator may perform type conversions on the operands: ● If either operand is of type double, then the other operand is converted to double. ● Otherwise, if either operand is of type float, the other operand is converted to float. ● Otherwise, if either operand is of type long, the other operand is converted to long. ● Otherwise, both operands are converted to int. The inequality comparison of any two arithmetic values produces true if and only if both operands are not the same value; otherwise the comparison produces false. The comparison of floating-point data is governed by the following additional rules: ● If either operand is not-a-number (NaN), the comparison produces true. NaN is the only value that compares as not equal to itself. ● Positive infinity is a distinct value that is equal to itself, and not equal to any other value. ● Negative infinity is a distinct value that is equal to itself, and not equal to any other value. ● Positive and negative zero are treated as equal, so -0.0!=0.0 produces false. If both operands are boolean values, the operator performs a Boolean inequality comparison. The comparison produces false if both operands are true or both operands are false. Otherwise, the comparison produces true. If both operands are reference types, the operator performs an object equality comparison. In order to perform this type of comparison, it must be possible to cast the value of one of the operands to the type of the other operand, or a compile-time error occurs. The comparison produces true if both of its operands refer to different objects and if both of its operands are not null; otherwise the comparison produces false. Because the != operator determines if two objects are different objects, it is not appropriate for comparisons that need to determine if two objects have different contents. For example, if you need to know whether two String objects contain different sequences of characters, the != operator is inappropriate. You should use the equals() method instead:[5] [5] This is similar to the difference in C between writing string1!=string2 and strcmp(string1, string2)!=0. !string1.equals (string2) // Compares contents of strings string1 != string2 // Compares actual string objects References Arithmetic Types; Boolean Type; Reference Types
Relational Comparison Operators
http://localhost/java/javaref/langref/ch04_09.htm (3 of 3) [20/12/2001 11:19:12]
Bitwise/Logical Operators
[Chapter 4] 4.3 Increment/Decrement Operators
Chapter 4 Expressions
4.3 Increment/Decrement Operators The ++ operator is used to increment the contents of a variable or an array element by one, while the - operator is used to decrement such a value by one. The operand of ++ or - - must evaluate to a variable or an array element; it cannot be an expression that produces a pure value. For example, the following operations succeed because the operand of the ++ operator produces a variable: int g = 0; g++; However, the following uses of ++ generate error messages: final int h = 23; h++; 5++; The expression h++ produces an error because h is declared final, which means that its value cannot be changed. The expression 5++ generates an error message because 5 is a literal value, not a variable. The increment and decrement operators can be used in both postfix expressions (e.g., i++ or i- -) and in prefix expressions (e.g., ++i or - -i). Although both types of expression have the same side effect of incrementing or decrementing a variable, they differ in the values that they produce. A postfix expression produces a pure value that is the value of the variable before it is incremented or decremented, while a prefix expression produces a pure value that is the value of the variable after it has been incremented or decremented. For example, consider the following code fragment: int i = 3, j = 3; System.out.println( "i++ produces " + i++); System.out.println( "++j produces " + ++j); The above code fragment produces the following output: i++ produces 3 ++j produces 4
http://localhost/java/javaref/langref/ch04_03.htm (1 of 3) [20/12/2001 11:19:16]
[Chapter 4] 4.3 Increment/Decrement Operators
After the code fragment has been evaluated, both i and j have the value 4. In essence, what you need to remember is that a prefix expression performs its increment or decrement before producing a value, while a postfix expression performs its increment or decrement after producing a value.
Postfix Increment/Decrement Operators A postfix increment/decrement expression is a primary expression that may be followed by either a ++ or a - -:
The postfix increment and decrement operators are equal in precedence and are effectively non-associative. If a postfix expression includes a ++ or - -, the primary expression must produce a variable or an array element of an arithmetic type. The postfix increment operator (++) has the side effect of incrementing the contents of the variable or array element by one. The postfix decrement operator (- -) has the side effect of decrementing the contents of the variable or array element by one. The data type of the value produced by a postfix increment/decrement operator is the same as the data type of the variable or array element produced by the primary expression. A postfix increment/decrement operator produces the original pure value stored in the variable or array element before it is incremented or decremented. The following is an example of using a postfix decrement operator: char j = '\u0100'; while (j-- > 0) doit(j);
// call doit for char values // '\u00ff' through '\u0000'
This example works because Java treats char as an arithmetic data type. References Arithmetic Types; Order of Operations; Primary Expressions
http://localhost/java/javaref/langref/ch04_03.htm (2 of 3) [20/12/2001 11:19:16]
[Chapter 4] 4.3 Increment/Decrement Operators
Prefix Increment/Decrement Operators A prefix increment/decrement expression is a primary expression that may be preceded by either a ++ or a - -:
The prefix increment and decrement operators are equal in precedence and are effectively non-associative. If a prefix expression includes a ++ or - -, the primary expression must produce a variable or an array element of an arithmetic type. The prefix increment operator (++) has the side effect of incrementing the contents of the variable or array element by one. The prefix decrement operator (- -) has the side effect of decrementing the contents of the variable or array element by one. The data type of the value produced by a prefix increment/decrement operator is the same as the data type of the variable or array element produced by the primary expression. A prefix increment/decrement operator produces the pure value stored in the variable or array element after it has been incremented or decremented. Here's an example of using a prefix increment operator: void foo(int a[]) { int j = -1; while (++j < a.length) doit(a[j]); }
// call doit for each element // of a
References Arithmetic Types; Order of Operations; Primary Expressions
Allocation Expressions
http://localhost/java/javaref/langref/ch04_03.htm (3 of 3) [20/12/2001 11:19:16]
Unary Operators
[Chapter 10] Integer
Chapter 10 The java.lang Package
Integer Name Integer
Synopsis Class Name: java.lang.Integer Superclass: java.lang.Number Immediate Subclasses: None Interfaces Implemented: None Availability: JDK 1.0 or later
Description The Integer class provides an object wrapper for an int value. This is useful when you need to treat an int value as an object. For example, there are a number of utility methods that take a reference to an Object as one of their arguments. You cannot specify an int value for one of these arguments, but you can provide a reference to an Integer object that encapsulates the int value. Also, as of JDK 1.1, the Integer class is necessary to support the Reflection API and class literals. The Integer class also provides a number of utility methods for converting int values to other primitive types and for converting int values to strings and vice versa.
http://localhost/java/javaref/langref/ch10_10.htm (1 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
Class Summary public final class java.lang.Integer extends java.lang.Number // Constants public static final int MAX_VALUE; public static final int MIN_VALUE; public final static Class TYPE; // New // Constructors public Integer(int value); public Integer(String s); // Class Methods public static Integer decode(String nm) // New public static Integer getInteger(String nm); public static Integer getInteger(String nm, int val); public static Integer getInteger(String nm, Integer val); public static int parseInt(String s); public static int parseInt(String s, int radix; public static String toBinaryString(long i); public static String toHexString(long i); public static String toOctalString(long i); public static String toString(int i); public static String toString(int i, int radix); public static Integer valueOf(String s); public static Integer valueOf(String s, int radix); // Instance Methods public byte byteValue(); // New public double doubleValue(); public boolean equals(Object obj); public float floatValue(); public int hashCode(); public int intValue(); public long longValue(); public short shortValue(); // New public String toString(); }
Constants MAX_VALUE public static final int MAX_VALUE = 0x7fffffff // 2147483647 Description The largest value that can be represented by an int.
http://localhost/java/javaref/langref/ch10_10.htm (2 of 12) [20/12/2001 11:19:22]
{
in 1.1
in 1.1
in 1.1
in 1.1
[Chapter 10] Integer
MIN_VALUE public static final int MIN_VALUE = 0x80000000 // -2147483648 Description The smallest value that can be represented by an int.
TYPE public static final Class TYPE Availability New as of JDK 1.1 Description The Class object that represents the type int. It is always true that Integer.TYPE == int.class.
Constructors Integer public Integer(int value) Parameters value The int value to be encapsulated by this object. Description Creates an Integer object with the specified int value. public Integer(String s) throws NumberFormatException Parameters s The string to be made into an Integer object. Throws NumberFormatException If the sequence of characters in the given String does not form a valid int literal. Description Constructs an Integer object with the value specified by the given string. The string should consist of one or more digit characters. The digit characters can be preceded by a single `-' character. If the string contains any other characters, the constructor throws a NumberFormatException.
http://localhost/java/javaref/langref/ch10_10.htm (3 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
Class Methods decode public static Integer decode(String nm) Availability New as of JDK 1.1 Parameters nm A String representation of the value to be encapsulated by an Integer object. If the string begins with # or 0x, it is a radix 16 representation of the value. If the string begins with 0, it is a radix 8 representation of the value. Otherwise, it is assumed to be a radix 10 representation of the value. Returns An Integer object that encapsulates the given value. Throws NumberFormatException If the String contains any nondigit characters other than a leading minus sign or the value represented by the String is less than Integer.MIN_VALUE or greater than Integer.MAX_VALUE. Description This method returns an Integer object that encapsulates the given value.
getInteger public static Integer getInteger(String nm) Parameters nm The name of a system property. Returns The value of the system property as an Integer object, or an Integer object with the value 0 if the named property does not exist or cannot be parsed. Description This method retrieves the value of the named system property and returns it as an Integer object. The method obtains the value of the system property as a String using System.getProperty(). If the value of the property begins with 0x or # and is not followed by a minus sign, the rest of the value is parsed as a hexadecimal integer. If the value begins with 0, it's parsed as an octal integer; otherwise it's parsed as a decimal integer. public static Integer getInteger(String nm, int val) Parameters nm
http://localhost/java/javaref/langref/ch10_10.htm (4 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
The name of a system property. val A default int value for the property. Returns The value of the system property as an Integer object, or an Integer object with the value val if the named property does not exist or cannot be parsed. Description This method retrieves the value of the named system property and returns it as an Integer object. The method obtains the value of the system property as a String using System.getProperty(). If the value of the property begins with 0x or # and is not followed by a minus sign, the rest of the value is parsed as a hexadecimal integer. If the value begins with 0, it's parsed as an octal integer; otherwise it's parsed as a decimal integer. public static Integer getInteger(String nm, Integer val) Parameters nm The name of a system property. val A default Integer value for the property. Returns The value of the system property as an Integer object, or the Integer object val if the named property does not exist or cannot be parsed. Description This method retrieves the value of the named system property and returns it as an Integer object. The method obtains the value of the system property as a String using System.getProperty(). If the value of the property begins with 0x or # and is not followed by a minus sign, the rest of the value is parsed as a hexadecimal integer. If the value begins with 0, it's parsed as an octal integer; otherwise it's as a decimal integer.
parseInt public static int parseInt(String s) throws NumberFormatException Parameters s The String to be converted to an int value. Returns The numeric value of the integer represented by the String object. Throws NumberFormatException If the String does not contain a valid representation of an integer.
http://localhost/java/javaref/langref/ch10_10.htm (5 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
Description This method returns the numeric value of the integer represented by the contents of the given String object. The String must contain only decimal digits, except that the first character may be a minus sign. public static int parseInt(String s, int radix) throws NumberFormatException Parameters s The String to be converted to an int value. radix The radix used in interpreting the characters in the String as digits. This value must be in the range Character.MIN_RADIX to Character.MAX_RADIX. If radix is in the range 2 through 10, only characters for which the Character.isDigit() method returns true are considered to be valid digits. If radix is in the range 11 through 36, characters in the ranges `A' through `Z' and `a' through `z' may be considered valid digits. Returns The numeric value of the integer represented by the String object in the specified radix. Throws NumberFormatException If the String does not contain a valid representation of an integer, or radix is not in the appropriate range. Description This method returns the numeric value of the integer represented by the contents of the given String object in the specified radix. The String must contain only valid digits of the specified radix, except that the first character may be a minus sign. The digits are parsed in the specified radix to produce the numeric value.
toBinaryString public static String toBinaryString(int value) Parameters value The int value to be converted to a string. Returns A string that contains the binary representation of the given value. Description This method returns a String object that contains the representation of the given value as an unsigned binary number. To convert the given value to an unsigned quantity, the method simply uses the value as if it were not negative. In other words, if the given value is negative, the method adds 2^32 to it. Otherwise the value is used as it is. The string returned by this method contains a sequence of one or more `0' and `1' characters. The method returns "0" if its argument is 0. Otherwise, the string returned by this method begins with `1'.
http://localhost/java/javaref/langref/ch10_10.htm (6 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
toHexString public static String toHexString(int value) Parameters value The int value to be converted to a string. Returns A string that contains the hexadecimal representation of the given value. Description This method returns a String object that contains the representation of the given value as an unsigned hexadecimal number. To convert the given value to an unsigned quantity, the method simply uses the value as if it were not negative. In other words, if the given value is negative, the method adds 2^32 to it. Otherwise the value is used as it is. The string returned by this method contains a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', `7', `8', `9', `a', `b', `c', `d', `e', and `f'. The method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with `0'. To produce a string that contains upper- instead of lowercase letters, use the String.toUpperCase() method.
toOctalString public static String toOctalString(int value) Parameters value The int value to be converted to a string. Returns A string that contains the octal representation of the given value. Description This method returns a String object that contains a representation of the given value as an unsigned octal number. To convert the given value to an unsigned quantity, the method simply uses the value as if it were not negative. In other words, if the given value is negative, the method adds 2^32 to it. Otherwise the value is used as it is. The string returned by this method contains a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', and `7'. The method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with `0'.
toString public static String toString(int i) Parameters i
http://localhost/java/javaref/langref/ch10_10.htm (7 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
The int value to be converted to a string. Returns The string representation of the given value. Description This method returns a String object that contains the decimal representation of the given value. This method returns a string that begins with `-' if the given value is negative. The rest of the string is a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', `7', `8', and `9'. This method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with "0" or "-0". public static String toString(int i, int radix) Parameters i The int value to be converted to a string. radix The radix used in converting the value to a string. This value must be in the range Character.MIN_RADIX to Character.MAX_RADIX. Returns The string representation of the given value in the specified radix. Description This method returns a String object that contains the representation of the given value in the specified radix. This method returns a string that begins with `-' if the given value is negative. The rest of the string is a sequence of one or more characters that represent the magnitude of the given value. The characters that can appear in the sequence are determined by the value of radix. If N is the value of radix, the first N characters on the following line can appear in the sequence: 0123456789abcdefghijklmnopqrstuvwxyz The method does not verify that radix is in the proper range. If radix is less than Character.MIN_RADIX or greater than Character.MAX_RADIX, the value 10 is used instead of the given value. This method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with "0" or "-0".
valueOf public static Integer valueOf(String s) throws NumberFormatException Parameters s The string to be made into an Integer object. Returns The Integer object constructed from the string. Throws http://localhost/java/javaref/langref/ch10_10.htm (8 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
NumberFormatException If the String does not contain a valid representation of an integer. Description Constructs an Integer object with the value specified by the given string. The string should consist of one or more digit characters. The digit characters can be preceded by a single `-' character. If the string contains any other characters, the method throws a NumberFormatException. public static Integer valueOf(String s, int radix) throws NumberFormatException Parameters s The string to be made into an Integer object. radix The radix used in converting the string to a value. This value must be in the range Character.MIN_RADIX to Character.MAX_RADIX. Returns The Integer object constructed from the string. Throws NumberFormatException If the String does not contain a valid representation of an integer or radix is not in the appropriate range. Description Constructs an Integer object with the value specified by the given string in the specified radix. The string should consist of one or more digit characters or characters in the range `A' to `Z' or `a' to `z' that are considered digits in the given radix. The digit characters can be preceded by a single `-' character. If the string contains any other characters, the method throws a NumberFormatException.
Instance Methods byteValue public byte byteValue() Availability New as of JDK 1.1 Returns The value of this object as a byte. Overrides Number.byteValue() Description This method returns the value of this object as a byte. The high order bits of the value are discarded.
http://localhost/java/javaref/langref/ch10_10.htm (9 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
doubleValue public double doubleValue() Returns The value of this object as a double. Overrides Number.doubleValue() Description This method returns the value of this object as a double.
equals public boolean equals(Object obj) Parameters obj The object to be compared with this object. Returns true if the objects are equal; false if they are not. Overrides Object.equals() Description This method returns true if obj is an instance of Integer and it contains the same value as the object this method is associated with.
floatValue public float floatValue() Returns The value of this object as a float. Overrides Number.floatValue() Description This method returns the value of this object as a float. Rounding may occur.
hashCode public int hashCode() Returns A hashcode based on the int value of the object.
http://localhost/java/javaref/langref/ch10_10.htm (10 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
Overrides Object.hashCode() Description This method returns a hashcode computed from the value of this object.
intValue public int intValue() Returns The value of this object as an int. Overrides Number.intValue() Description This method returns the value of this object as an int.
longValue public long longValue() Returns The value of this object as a long. Overrides Number.longValue() Description This method returns the value of this object as a long.
shortValue public short shortValue() Availability New as of JDK 1.1 Returns The value of this object as a short. Overrides Number.shortValue() Description This method returns the value of this object as a short. The high order bits of the value are discarded.
http://localhost/java/javaref/langref/ch10_10.htm (11 of 12) [20/12/2001 11:19:22]
[Chapter 10] Integer
toString public String toString() Returns The string representation of the value of this object. Overrides Object.toString() Description This method returns a String object that contains the decimal representation of the value of this object. This method returns a string that begins with `-' if the value is negative. The rest of the string is a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', `7', `8', and `9'. This method returns "0" if the value of the object is 0. Otherwise, the string returned by this method does not begin with "0" or "-0".
Inherited Methods Method Inherited From Method Inherited From clone() Object finalize() Object getClass() Object notify() Object notifyAll() Object wait() Object wait(long) Object wait(long, int) Object
See Also Character; Class; Exceptions; Integer literals; Integer types; Long; Number; String; System
Float
http://localhost/java/javaref/langref/ch10_10.htm (12 of 12) [20/12/2001 11:19:22]
Long
[Chapter 10] Long
Chapter 10 The java.lang Package
Long Name Long
Synopsis Class Name: java.lang.Long Superclass: java.lang.Number Immediate Subclasses: None Interfaces Implemented: None Availability: JDK 1.0 or later
Description The Long class provides an object wrapper for a long value. This is useful when you need to treat a long value as an object. For example, there are a number of utility methods that take a reference to an Object as one of their arguments. You cannot specify a long value for one of these arguments, but you can provide a reference to a Long object that encapsulates the long value. Furthermore, as of JDK 1.1, the Long class is necessary to support the Reflection API and class literals. The Long class also provides a number of utility methods for converting long values to other primitive types and for converting long values to strings and vice versa.
http://localhost/java/javaref/langref/ch10_11.htm (1 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
Class Summary public final class java.lang.Long extends java.lang.Number { // Constants public static final long MIN_VALUE; public static final long MAX_VALUE; public final static Class TYPE; // New in 1.1 // Constructors public Long(long value); public Long(String s); // Class Methods public static Long getLong(String nm); public static Long getLong(String nm, long val); public static Long getLong(String nm, Long val); public static long parseLong(String s); public static long parseLong(String s, int radix); public static String toBinaryString(long i); public static String toHexString(long i); public static String toOctalString(long i); public static String toString(long i); public static String toString(long i, int radix); public static Long valueOf(String s); public static Long valueOf(String s, int radix); // Instance Methods public byte byteValue(); // New in 1.1 public double doubleValue(); public boolean equals(Object obj); public float floatValue(); public int hashCode(); public int intValue(); public long longValue(); public short shortValue(); // New in 1.1 public String toString(); }
Constants MAX_VALUE public static final long MAX_VALUE = 0x7fffffffffffffffL Description The largest value that can be represented by a long.
http://localhost/java/javaref/langref/ch10_11.htm (2 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
MIN_VALUE public static final long MIN_VALUE = 0x8000000000000000L Description The smallest value that can be represented by a long.
TYPE public static final Class TYPE Availability New as of JDK 1.1 Description The Class object that represents the type long. It is always true that Long.TYPE == long.class.
Constructors Long public Long(long value) Parameters value The long value to be encapsulated by this object. Description Creates a Long object with the specified long value. public Long(String s) throws NumberFormatException Parameters s The string to be made into a Long object. Throws NumberFormatException If the sequence of characters in the given String does not form a valid long literal. Description Constructs a Long object with the value specified by the given string. The string should consist of one or more digit characters. The digit characters can be preceded by a single `-' character. If the string contains any other characters, the constructor throws a NumberFormatException.
http://localhost/java/javaref/langref/ch10_11.htm (3 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
Class Methods getLong public static Integer getLong(String nm) Parameters nm The name of a system property. Returns The value of the system property as a Long object or a Long object with the value 0 if the named property does not exist or cannot be parsed. Description This method retrieves the value of the named system property and returns it as a Long object. The method obtains the value of the system property as a String using System.getProperty(). If the value of the property begins with 0x or # and is not followed by a minus sign, the rest of the value is parsed as a hexadecimal integer. If the value begins with 0, it's parsed as an octal integer; otherwise it's parsed as a decimal integer. public static Long getLong(String nm, long val) Parameters nm The name of a system property. val A default value for the property. Returns The value of the system property as a Long object or a Long object with the value val if the named property does not exist or cannot be parsed. Description This method retrieves the value of the named system property and returns it as a Long object. The method obtains the value of the system property as a String using System.getProperty(). If the value of the property begins with 0x or # and is not followed by a minus sign, the rest of the value is parsed as a hexadecimal integer. If the value begins with 0, it's parsed as an octal integer; otherwise it's parsed as a decimal integer. public static Long getLong(String nm, Long val) Parameters nm The name of a system property. val
http://localhost/java/javaref/langref/ch10_11.htm (4 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
A default value for the property. Returns The value of the system property as a Long object, or the Long object val if the named property does not exist or cannot be parsed. Description This method retrieves the value of the named system property and returns it as a Long object. The method obtains the value of the system property as a String using System.getProperty(). If the value of the property begins with 0x or # and is not followed by a minus sign, the rest of the value is parsed as a hexadecimal integer. If the value begins with 0, it's parsed as an octal integer; otherwise it's parsed as a decimal integer.
parseLong public static long parseLong(String s) throws NumberFormatException Parameters s The String to be converted to a long value. Returns The numeric value of the long represented by the String object. Throws NumberFormatException If the String does not contain a valid representation of a long value. Description This method returns the numeric value of the long represented by the contents of the given String object. The String must contain only decimal digits, except that the first character may be a minus sign. public static long parseLong(String s, int radix) throws NumberFormatException Parameters s The String to be converted to a long value. radix The radix used in interpreting the characters in the String as digits. It must be in the range Character.MIN_RADIX to Character.MAX_RADIX. If radix is in the range 2 through 10, only characters for which the Character.isDigit() method returns true are considered valid digits. If radix is in the range 11 through 36, characters in the ranges `A' through `Z' and `a' through `z' may be considered valid digits. Returns The numeric value of the long represented by the String object in the specified radix. Throws NumberFormatException If the String does not contain a valid representation of a long or radix is not in the appropriate
http://localhost/java/javaref/langref/ch10_11.htm (5 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
range. Description This method returns the numeric value of the long represented by the contents of the given String object in the specified radix. The String must contain only valid digits of the specified radix, except that the first character may be a minus sign. The digits are parsed in the specified radix to produce the numeric value.
toBinaryString public static String toBinaryString(long value) Parameters value The long value to be converted to a string. Returns A string that contains the binary representation of the given value. Description This method returns a String object that contains the representation of the given value as an unsigned binary number. To convert the given value to an unsigned quantity, the method simply uses the value as if it were not negative. In other words, if the given value is negative, the method adds 2^64 to it. Otherwise the value is used as it is. The string returned by this method contains a sequence of one or more `0' and `1' characters. The method returns "0" if its argument is 0. Otherwise, the string returned by this method begins with `1'.
toHexString public static String toHexString(long value) Parameters value The long value to be converted to a string. Returns A string that contains the hexadecimal representation of the given value. Description This method returns a String object that contains the representation of the given value as an unsigned hexadecimal number. To convert the given value to an unsigned quantity, the method simply uses the value as if it were not negative. In other words, if the given value is negative, the method adds 2^64 to it. Otherwise the value is used as it is. The string returned by this method contains a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', `7', `8', `9', `a', `b', `c', `d', `e', and `f'. The method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with `0'. To produce a string that contains upper- instead of lowercase letters, use the String.toUpperCase() method.
http://localhost/java/javaref/langref/ch10_11.htm (6 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
toOctalString public static String toOctalString(long value) Parameters value The long value to be converted to a string. Returns A string that contains the octal representation of the given value. Description This method returns a String object that contains a representation of the given value as an unsigned octal number. To convert the given value to an unsigned quantity, the method simply uses the value as if it were not negative. In other words, if the given value is negative, the method adds 2^64 to it. Otherwise the value is used as it is. The string returned by this method contains a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', and `7'. The method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with `0'.
toString public static String toString(long i) Parameters i The long value to be converted to a string. Returns The string representation of the given value. Description This method returns a String object that contains the decimal representation of the given value. This method returns a string that begins with `-' if the given value is negative. The rest of the string is a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', `7', `8', and `9'. This method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with "0" or "-0". public static String toString(long i, int radix) Parameters i The long value to be converted to a string. radix The radix used in converting the value to a string. This value must be in the range Character.MIN_RADIX to Character.MAX_RADIX. Returns
http://localhost/java/javaref/langref/ch10_11.htm (7 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
The string representation of the given value in the specified radix. Description This method returns a String object that contains the representation of the given value in the specified radix. This method returns a string that begins with`-' if the given value is negative. The rest of the string is a sequence of one or more characters that represent the magnitude of the given value. The characters that can appear in the sequence are determined by the value of radix. If N is the value of radix, the first N characters on the following line can appear in the sequence: 0123456789abcdefghijklmnopqrstuvwxyz The method does not verify that radix is in the proper range. If radix is less than Character.MIN_RADIX or greater than Character.MAX_RADIX, the value 10 is used instead of the given value. This method returns "0" if its argument is 0. Otherwise, the string returned by this method does not begin with "0" or "-0".
valueOf public static Long valueOf(String s) throws NumberFormatException Parameters s The string to be made into a Long object. Returns The Long object constructed from the string. Throws NumberFormatException If the String does not contain a valid representation of a long. Description Constructs a Long object with the value specified by the given string. The string should consist of one or more digit characters. The digit characters can be preceded by a single - character. If the string contains any other characters, the method throws a NumberFormatException. public static Long valueOf(String s, int radix) throws NumberFormatException Parameters s The string to be made into a Long object. radix The radix used in converting the string to a value. This value must be in the range Character.MIN_RADIX to Character.MAX_RADIX. Returns The Long object constructed from the string. Throws
http://localhost/java/javaref/langref/ch10_11.htm (8 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
NumberFormatException If the String does not contain a valid representation of a long. Description Constructs a Long object with the value specified by the given string in the specified radix. The string should consist of one or more digit characters or characters in the range `A' to `Z' or `a' to `z' that are considered digits in the given radix. The digit characters can be preceded by a single `-' character. If the string contains any other characters, the method throws a NumberFormatException. The method does not verify that radix is in the proper range. If radix is less than Character.MIN_RADIX or greater than Character.MAX_RADIX, the value 10 is used instead of the given value.
Instance Methods byteValue public byte byteValue() Availability New as of JDK 1.1 Returns The value of this object as a byte. Overrides Number.byteValue() Description This method returns the value of this object as a byte. The high order bits of the value are discarded.
doubleValue public double doubleValue() Returns The value of this object as a double. Overrides Number.doubleValue() Description This method returns the value of this object as a double. Rounding may occur.
equals public boolean equals(Object obj) Parameters obj http://localhost/java/javaref/langref/ch10_11.htm (9 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
The object to be compared with this object. Returns true if the objects are equal; false if they are not. Overrides Object.equals() Description This method returns true if obj is an instance of Long and it contains the same value as the object this method is associated with.
floatValue public float floatValue() Returns The value of this object as a float. Overrides Number.floatValue() Description This method returns the value of this object as a float. Rounding may occur.
hashCode public int hashCode() Returns A hashcode based on the long value of the object. Overrides Object.hashCode() Description This method returns a hashcode computed from the value of this object. More specifically, the result is the exclusive OR of the two halves of the long value represented by the object. If value is the value of the object, the method returns a result equivalent to the following expression: (int)(value^(value>>>32))
intValue public int intValue() Returns The value of this object as an int. Overrides
http://localhost/java/javaref/langref/ch10_11.htm (10 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
Number.intValue() Description This method returns the value of this object as an int. The high-order bits of the value are discarded.
longValue public long longValue() Returns The value of this object as a long. Overrides Number.longValue() Description This method returns the value of this object as a long.
shortValue public short shortValue() Availability New as of JDK 1.1 Returns The value of this object as a short. Overrides Number.shortValue() Description This method returns the value of this object as a short. The high-order bits of the value are discarded.
toString public String toString() Returns The string representation of the value of this object. Overrides Object.toString() Description This method returns a String object that contains the decimal representation of the value of this object. This method returns a string that begins with `-' if the value is negative. The rest of the string is a sequence of one or more of the characters `0', `1', `2', `3', `4', `5', `6', `7', `8', and `9'. This method returns "0" if the value of the object is 0. Otherwise, the string returned by this method does not begin with "0" or "-0".
http://localhost/java/javaref/langref/ch10_11.htm (11 of 12) [20/12/2001 11:19:26]
[Chapter 10] Long
Inherited Methods Method Inherited From Method Inherited From clone() Object finalize() Object getClass() Object notify() Object notifyAll() Object wait() Object wait(long) Object wait(long, int) Object
See Also Character; Class; Exceptions; Integer; Integer literals; Integer types; Number; String; System
Integer
http://localhost/java/javaref/langref/ch10_11.htm (12 of 12) [20/12/2001 11:19:26]
Math
[Chapter 4] 4.5 Multiplicative Operators
Chapter 4 Expressions
4.5 Multiplicative Operators The multiplicative operators in Java are binary operators that are used for multiplication (*), division (/), and the remainder operation (%). The multiplicative operators appear in multiplicative expressions:
The multiplicative operators are equal in precedence and are evaluated from left to right. References Unary Operators; Order of Operations
Multiplication Operator * The binary multiplication operator * produces a pure value that is the product of its operands. The * operator may appear in a multiplicative expression. The multiplication operator never throws an exception. Here is an example that uses the multiplication operator: int doubleIt(int x) { return x*2; } The types of both operands of the multiplication operator must be arithmetic types, or a compile-time error occurs. The * operator may perform type conversions on its operands: ● If either operand is of type double, the other operand is converted to double and the operation produces a double value. ● Otherwise, if either operand is of type float, the other operand is converted to float and the operation produces a float value. http://localhost/java/javaref/langref/ch04_05.htm (1 of 5) [20/12/2001 11:19:32]
[Chapter 4] 4.5 Multiplicative Operators
●
●
Otherwise, if either operand is of type long, the other operand is converted to long and the operation produces a long value. Otherwise, both operands are converted to int and the operation produces an int value.
If the multiplication of integer data overflows, the low order bits of the product are returned; no exception is thrown. The most significant bit of the low order bits is treated as a sign bit. When overflow occurs, the sign of the number produced may not be the same as the sign of the mathematically correct product, due to the limitations of the two's complement representation used for integer data. The multiplication of floating-point data is governed by the following rules: ● If either operand is not-a-number (NaN), the product is NaN. ● If neither operand is NaN and if both operands have the same sign, the product is positive. ● If neither operand is NaN and if the operands have different signs, the product is negative. ● If one of the operands is positive or negative infinity and the other operand is positive or negative zero, the product is NaN. ● If one of the operands is an infinity value and the other operand is neither zero nor NaN, the product is either positive or negative infinity, as determined by the rules governing the sign of products. ● If neither operand is a zero value, an infinity value, or NaN, the product is rounded to the nearest representable value. If the magnitude of the product is too large to be represented, the operation overflows and an infinity value of the appropriate sign is produced. If the magnitude of the product is too small to be represented, the operation underflows and a zero value of the appropriate sign is produced. References Arithmetic Types
Division Operator / The binary division operator / produces a pure value that is the quotient of its operands. The left operand is the dividend and the right operand is the divisor. The / operator may appear in a multiplicative expression. Here is an example that uses the division operator: int halfIt(int x) { return x/2; } The types of both operands of the division operator must be arithmetic types, or a compile-time error occurs. The / operator may perform type conversions on its operands: ● If either operand is of type double, the other operand is converted to double and the operation produces a double value. ● Otherwise, if either operand is of type float, the other operand is converted to float and the operation produces a float value.
http://localhost/java/javaref/langref/ch04_05.htm (2 of 5) [20/12/2001 11:19:32]
[Chapter 4] 4.5 Multiplicative Operators
●
●
Otherwise, if either operand is of type long, the other operand is converted to long and the operation produces a long value. Otherwise, both operands are converted to int and the operation produces an int value.
The division of integer data rounds toward zero. If the divisor of an integer division operator is zero, an ArithmeticException is thrown. If the dividend is Integer.MIN_VALUE or Long.MIN_VALUE and the divisor is -1, the quotient produced is Integer.MIN_VALUE or Long.MIN_VALUE, due to the limitations of the two's complement representation used for integer data. The division of floating-point data is governed by the following rules: ● If either operand is not-a-number (NaN), the quotient is NaN. ● If neither operand is NaN and if both operands have the same sign, the quotient is positive. ● If neither operand is NaN and if the operands have different signs, the quotient is negative. ● If both of the operands are positive or negative infinity, the quotient is NaN. ● If the dividend is an infinity value and the divisor is a finite number, the quotient is either positive or negative infinity, as determined by the rules governing the sign of quotients. ● If the dividend is a finite number and the divisor is an infinity value, the quotient is either positive or negative zero, as determined by the rules governing the sign of quotients. ● If the divisor is positive or negative zero and the dividend is not zero or NaN, the quotient is either positive or negative infinity, as determined by the rules governing the sign of quotients. ● If both operands are zero values, the quotient is NaN. ● If the dividend is a zero value and the divisor is a non-zero finite number, the quotient is either positive or negative zero, as determined by the rules governing the sign of quotients. ● If the dividend is a non-zero finite number and the divisor is a zero value, the quotient is either positive or negative infinity, as determined by the rules governing the sign of quotients. ● If neither operand is a zero value, an infinity value, or NaN, the quotient is rounded to the nearest representable value. If the magnitude of the quotient is too large to be represented, the operation overflows and an infinity value of the appropriate sign is produced. If the magnitude of the quotient is too small to be represented, the operation underflows and a zero value of the appropriate sign is produced. References Arithmetic Types; Integer; Long; Runtime exceptions
Remainder Operator % The binary remainder operator % produces a pure value that is the remainder from an implied division of its operands. The left operand is the dividend and the right operand is the divisor. The % operator may appear in a multiplicative expression. Here is an example that uses the remainder operator: // format seconds into hours, minutes and seconds String formatTime(int t) { int minutes, seconds; http://localhost/java/javaref/langref/ch04_05.htm (3 of 5) [20/12/2001 11:19:32]
[Chapter 4] 4.5 Multiplicative Operators
seconds = t%60; t /= 60; minutes = t%60; return t/60 + ":" + minutes + ":" + seconds; } The types of both operands of the remainder operator must be arithmetic types, or a compile-time error occurs. The % operator may perform type conversions on its operands: ● If either operand is of type double, the other operand is converted to double and the operation produces a double value. ● Otherwise, if either operand is of type float, the other operand is converted to float and the operation produces a float value. ● Otherwise, if either operand is of type long, the other operand is converted to long and the operation produces a long value. ● Otherwise, both operands are converted to int and the operation produces an int value. When the remainder operation is performed on integer data, the following expression is guaranteed to produce the same value as a%b: a-((a/b)*b) The sign of the value produced by the remainder operator is always the sign of the dividend. The magnitude of the value produced by the remainder operator is always less than the absolute value of the divisor. If the divisor is zero, an ArithmeticException is thrown. Unlike C/C++, Java provides a remainder operation for floating-point data. The remainder of floating-point data is computed in a manner similar to the remainder of integer data. The remainder operation uses a truncating division to compute its value. This is unlike the IEEE 754 remainder operation, which uses a rounding division. The IEEE remainder operation is provided by the Math.IEEEremainder() method. The computation of the remainder of double and float data is governed by the following rules: ● If either operand is not-a-number (NaN), the remainder is NaN. ● If neither operand is NaN, the sign of the remainder is the same as the sign of the dividend. ● If the dividend is positive or negative infinity or the divisor is positive or negative zero, the remainder is NaN. ● If the dividend is a finite number and the divisor is an infinity value, the remainder is equal to the dividend. ● If the dividend is a zero value and the divisor is a finite number, the remainder is equal to the dividend. ● If neither operand is a zero value, an infinity value, or NaN, the remainder is computed according to the following mathematical formula:
http://localhost/java/javaref/langref/ch04_05.htm (4 of 5) [20/12/2001 11:19:32]
[Chapter 4] 4.5 Multiplicative Operators
p is the dividend and d is the divisor. The notation to x ; this is called the floor operation.
means the greatest integer less than or equal
References Arithmetic Types; Math; Runtime exceptions
Unary Operators
http://localhost/java/javaref/langref/ch04_05.htm (5 of 5) [20/12/2001 11:19:32]
Additive Operators
[Chapter 4] 4.8 Relational Comparison Operators
Chapter 4 Expressions
4.8 Relational Comparison Operators The relational comparison operators in Java are used for less than (), and instanceof comparison operations. They may appear in a relational expression:
The relational comparison operators are equal in precedence and are evaluated from left to right. The operators are numerical comparison operators, while instanceof is a type comparison operator. All of these operators produce boolean values. References Shift Operators; Order of Operations; Type 3
Less-Than Operator < The less-than operator < performs a comparison between its operands and returns a boolean value. It returns the pure value true if its left operand is less than its right operand; otherwise the operator returns the pure value false. The < operator may appear as part of a relational expression. The less-than operator never throws an exception. The types of both operands of the less-than operator must be arithmetic types, or a compile-time error occurs. The < operator may perform type conversions on its operands: ● If either operand is of type double, then the other operand is converted to double. ● Otherwise, if either operand is of type float, the other operand is converted to float. ● Otherwise, if either operand is of type long, the other operand is converted to long. ● Otherwise, both operands are converted to int. The comparison of any two arithmetic values produces true if the value of the left operand is less than the value of the right operand; otherwise the comparison produces false. The comparison of floating-point data is governed by the following additional rules:
http://localhost/java/javaref/langref/ch04_08.htm (1 of 4) [20/12/2001 11:19:36]
[Chapter 4] 4.8 Relational Comparison Operators
● ●
●
●
If either operand is not-a-number (NaN), the comparison produces false. Negative infinity is the most negative value. If the left operand is negative infinity, the comparison produces true, unless the right operand is also negative infinity, in which case the comparison produces false. Positive infinity is the most positive value. If the right operand is positive infinity, the comparison produces true, unless the left operand is also positive infinity, in which case the comparison produces false. Positive and negative zero are treated as equal, so -0.0 < 0.0 produces false.
References Arithmetic Types
Less-Than-Or-Equal-To Operator = 0.0 produces true. References Arithmetic Types
Greater-Than Operator > The greater-than operator > performs a comparison between its operands and returns a boolean value. It returns the pure value true if its left operand is greater than its right operand; otherwise the operator returns the pure value false. The > operator may appear as part of a relational expression. The greater-than operator never throws an exception. The types of both operands of the greater-than operator must be arithmetic types, or a compile-time error occurs. The > operator may perform type conversions on its operands: ● If either operand is of type double, then the other operand is converted to double. ● Otherwise, if either operand is of type float, the other operand is converted to float. ● Otherwise, if either operand is of type long, the other operand is converted to long. ● Otherwise, both operands are converted to int. The comparison of any two arithmetic values produces true if the value of the left operand is greater than the value of the right operand; otherwise the comparison produces false. The comparison of floating-point data is governed by the following additional rules: ● If either operand is not-a-number (NaN), the comparison produces false. ● Negative infinity is the most negative value. If the right operand is negative infinity, the comparison produces true, unless the left operand is also negative infinity, in which case the comparison produces false. ● Positive infinity is the most positive value. If the left operand is positive infinity, the comparison produces true, unless the right operand is also positive infinity, in which case the comparison produces false. http://localhost/java/javaref/langref/ch04_08.htm (3 of 4) [20/12/2001 11:19:36]
[Chapter 4] 4.8 Relational Comparison Operators
●
Positive and negative zero are treated as equal, so 0.0 > -0.0 produces false.
References Arithmetic Types
The instanceof Operator The instanceof operator performs a type comparison between its operands and returns a boolean value. It returns the pure value true if the object referred to by the left operand can be cast to the type specified as the right operand; otherwise the operator returns the pure value false. If the value of the left operand is null, the instanceof operator returns the pure value false. The instanceof operator may appear as part of a relational expression. The instanceof operator never throws an exception. The type of the left operand of the instanceof operator must be a reference type, or a compile-time error occurs. All objects inherit a method called equals() from the Object class. The equals() method defined in the Object class returns true if the two objects being compared are the same object. For some classes, it is more appropriate to override the equals() method so that it compares the contents of two objects. Before such a method can do the comparison, it should verify that the objects are instances of the same class by using instanceof. For example, let's suppose that you are defining a class to represent complex numbers. Since you want the equals() method to compare the contents of complex number objects, you define an equals method for the complex number class that looks like this: boolean equals (Object o) { if (o instanceof complexNumber) return o.real == this.real && o.imaginary == this.imaginary; } The instanceof operator can also be used to find out if an object is an instance of a class that implements an interface. For example: if (o instanceof Runnable) (new Thread((Runnable)o).start; References Casts; Class Types; Interface Types
Shift Operators
http://localhost/java/javaref/langref/ch04_08.htm (4 of 4) [20/12/2001 11:19:36]
Equality Comparison Operators
[Chapter 9] 9.4 The Exception Hierarchy
Chapter 9 Exception Handling
9.4 The Exception Hierarchy The possible exceptions in a Java program are organized in a hierarchy of exception classes. The Throwable class, which is an immediate subclass of Object, is at the root of the exception hierarchy. Throwable has two immediate subclasses: Exception and Error. Figure 9.1 shows the standard exception classes defined in the java.lang package, while Figure 9.2 shows the standard error classes defined in java.lang. Figure 9.1: Standard Java exception classes
Figure 9.2: Standard Java error classes
http://localhost/java/javaref/langref/ch09_04.htm (1 of 7) [20/12/2001 11:19:42]
[Chapter 9] 9.4 The Exception Hierarchy
Exceptions All of the subclasses of Exception represent exceptional conditions that a normal Java program may want to handle. Many of the standard exceptions are also subclasses of RuntimeException. Runtime exceptions represent runtime conditions that can generally occur in any Java method, so a method is not required to declare that it throws any of the runtime exceptions. However, if a method can throw any of the other standard exceptions, it must declare them in its throws clause. A Java program should try to handle all of the standard exception classes, since they represent routine abnormal conditions that should be anticipated and caught to prevent program termination. Runtime exceptions The java.lang package defines the following standard runtime exception classes: ArithmeticException This exception is thrown to indicate an exceptional arithmetic condition, such as integer division by zero. ArrayIndexOutOfBoundsException This exception is thrown when an out-of-range index is detected by an array object. An
http://localhost/java/javaref/langref/ch09_04.htm (2 of 7) [20/12/2001 11:19:42]
[Chapter 9] 9.4 The Exception Hierarchy
out-of-range index occurs when the index is less than zero or greater than or equal to the size of the array. ArrayStoreException This exception is thrown when there is an attempt to store a value in an array element that is incompatible with the type of the array. ClassCastException This exception is thrown when there is an attempt to cast a reference to an object to an inappropriate type. IllegalArgumentException This exception is thrown to indicate that an illegal argument has been passed to a method. IllegalMonitorStateException This exception is thrown when an object's wait(), notify(), or notifyAll() method is called from a thread that does not own the object's monitor. IllegalStateException This exception is thrown to indicate that a method has been invoked when the run-time environment is in an inappropriate state for the requested operation. This exception is new in Java 1.1. IllegalThreadStateException This exception is thrown to indicate an attempt to perform an operation on a thread that is not legal for the thread's current state, such as attempting to resume a dead thread. IndexOutOfBoundsException The appropriate subclass of this exception (i.e., ArrayIndexOutOfBoundsException or StringIndexOutOfBoundsException) is thrown when an array or string index is out of bounds. NegativeArraySizeException This exception is thrown in response to an attempt to create an array with a negative size. NullPointerException This exception is thrown when there is an attempt to access an object through a null object reference. This can occur when there is an attempt to access an instance variable or call a method through a null object or when there is an attempt to subscript an array with a null object. NumberFormatException This exception is thrown to indicate that an attempt to parse numeric information in a string has failed. RuntimeException The appropriate subclass of this exception is thrown in response to a runtime error detected at the virtual machine level. Because these exceptions are so common, methods that can throw objects http://localhost/java/javaref/langref/ch09_04.htm (3 of 7) [20/12/2001 11:19:42]
[Chapter 9] 9.4 The Exception Hierarchy
that are instances of RuntimeException or one of its subclasses are not required to declare that fact in their throws clauses. SecurityException This exception is thrown in response to an attempt to perform an operation that violates the security policy implemented by the installed SecurityManager object. StringIndexOutOfBoundsException This exception is thrown when a String or StringBuffer object detects an out-of-range index. An out-of-range index occurs when the index is less than zero or greater than or equal to the length of the string. Other exceptions The java.lang package defines the following standard exception classes that are not runtime exceptions: ClassNotFoundException This exception is thrown to indicate that a class that is to be loaded cannot be found. CloneNotSupportedException This exception is thrown when the clone() method has been called for an object that does not implement the Cloneable interface and thus cannot be cloned. Exception The appropriate subclass of this exception is thrown in response to an error detected at the virtual machine level. If a program defines its own exception classes, they should be subclasses of the Exception class. IllegalAccessException This exception is thrown when a program tries to dynamically load a class (i.e., uses the forName() method of the Class class, or the findSystemClass() or the loadClass() method of the ClassLoader class) and the currently executing method does not have access to the specified class because it is in another package and not public. This exception is also thrown when a program tries to create an instance of a class (i.e., uses the newInstance() method of the Class class) that does not have a zero-argument constructor accessible to the caller. InstantiationException This exception is thrown in response to an attempt to instantiate an abstract class or an interface using the newInstance() method of the Class class. InterruptedException This exception is thrown to signal that a thread that is sleeping, waiting, or otherwise paused has been interrupted by another thread. NoSuchFieldException This exception is thrown when a specified variable cannot be found. This exception is new in Java http://localhost/java/javaref/langref/ch09_04.htm (4 of 7) [20/12/2001 11:19:42]
[Chapter 9] 9.4 The Exception Hierarchy
1.1. NoSuchMethodException This exception is thrown when a specified method cannot be found.
Errors The subclasses of Error represent errors that are normally thrown by the class loader, the virtual machine, or other support code. Application-specific code should not normally throw any of these standard error classes. If a method does throw an Error class or any of its subclasses, the method is not required to declare that fact in its throws clause. A Java program should not try to handle the standard error classes. Most of these error classes represent non-recoverable errors and as such, they cause the Java runtime system to print an error message and terminate program execution. The java.lang package defines the following standard error classes: AbstractMethodError This error is thrown in response to an attempt to invoke an abstract method. ClassCircularityError This error is thrown when a circular reference among classes is detected during class initialization. ClassFormatError This error is thrown when an error is detected in the format of a file that contains a class definition. Error The appropriate subclass of this error is thrown when an unpredictable error, such as running out of memory, occurs. Because of the unpredictable nature of these errors, methods that can throw objects that are instances of Error or one of its subclasses are not required to declare that fact in their throws clauses. ExceptionInInitializerError This error is thrown when an unexpected exception is thrown in a static initializer. This error is new in Java 1.1. IllegalAccessError This error is thrown when a class attempts to access a field or call a method it does not have access to. Usually this error is caught by the compiler; this error can occur at run-time if the definition of a class changes after the class that references it was last compiled. IncompatibleClassChangeError This error or one of its subclasses is thrown when a class refers to another class in an incompatible way. This situation occurs when the current definition of the referenced class is incompatible with the definition of the class that was found when the referring class was compiled. For example, say class A refers to a method in class B. Then, after class A is compiled, the method is removed from
http://localhost/java/javaref/langref/ch09_04.htm (5 of 7) [20/12/2001 11:19:42]
[Chapter 9] 9.4 The Exception Hierarchy
class B. When class A is loaded, the run-time system discovers that the method in class B no longer exists and throws an error. InstantiationError This error is thrown in response to an attempt to instantiate an abstract class or an interface. Usually this error is caught by the compiler; this error can occur at run-time if the definition of a class is changed after the class that references it was last compiled. InternalError This error is thrown to signal an internal error within the virtual machine. LinkageError The appropriate subclass of this error is thrown when there is a problem resolving a reference to a class. Reasons for this may include a difficulty in finding the definition of the class or an incompatibility between the current definition and the expected definition of the class. NoClassDefFoundError This error is thrown when the definition of a class cannot be found. NoSuchFieldError This error is thrown in response to an attempt to reference an instance or class variable that is not defined in the current definition of a class. Usually this error is caught by the compiler; this error can occur at run-time if the definition of a class is changed after the class that references it was last compiled. NoSuchMethodError This error is thrown in response to an attempt to reference a method that is not defined in the current definition of a class. Usually this error is caught by the compiler; this error can occur at run-time if the definition of a class is changed after the class that references it was last compiled. OutOfMemoryError This error is thrown when an attempt to allocate memory fails. StackOverflowError This error is thrown when a stack overflow error occurs within the virtual machine. ThreadDeath This error is thrown by the stop() method of a Thread object to kill the thread. Catching ThreadDeath objects is not recommended. If it is necessary to catch a ThreadDeath object, it is important to re-throw the object so that it is possible to cleanly stop the catching thread. UnknownError This error is thrown when an error of unknown origins is detected in the run-time system. UnsatisfiedLinkError This error is thrown when the implementation of a native method cannot be found. VerifyError http://localhost/java/javaref/langref/ch09_04.htm (6 of 7) [20/12/2001 11:19:42]
[Chapter 9] 9.4 The Exception Hierarchy
This error is thrown when the byte-code verifier detects that a class file, though well-formed, contains some sort of internal inconsistency or security problem. VirtualMachineError The appropriate subclass of this error is thrown to indicate that the Java virtual machine has encountered an error.
Generating Exceptions
http://localhost/java/javaref/langref/ch09_04.htm (7 of 7) [20/12/2001 11:19:42]
The java.lang Package
[Chapter 4] 4.7 Shift Operators
Chapter 4 Expressions
4.7 Shift Operators The shift operators in Java are used for left shift (), and unsigned right shift (>>>) operations. The shift operators may appear in a shift expression:
The shift operators are equal in precedence and are evaluated from left to right. References Additive Operators; Order of Operations
Left Shift Operator s is mathematically equivalent to:
The notation
means the greatest integer less than or equal to x ; this is called the floor operation.
If the type of the left operand is long, only the six least significant bits of the value of the right operand are used as the shift distance. Therefore, the shift distance is in the range 0 through 63. In this case, the value produced by r >> s is mathematically equivalent to:
http://localhost/java/javaref/langref/ch04_07.htm (2 of 3) [20/12/2001 11:19:47]
[Chapter 4] 4.7 Shift Operators
References Integer types
Unsigned Right Shift Operator >>> The unsigned right shift operator >>> produces a pure value that is its left operand right-shifted with zero extension by the number of bits specified by its right operand. Right-shifting with zero extension means that shifting a value n places to the right causes the n high order bits to contain zero. The >>> operator may appear as part of a shift expression. The unsigned right shift operator never throws an exception. Here are some examples of the unsigned right shift operator: (0x01234567>>>4) == 0x00123456 (0xF1234567>>>4) == 0x0F123456 The type of each operand of the unsigned right shift operator must be an integer data type, or a compile-time error occurs. The >>> operator may perform type conversions on its operands; unlike arithmetic binary operators, each operand is converted independently. If the type of an operand is byte, short, or char, that operand is converted to an int before the value of the operator is computed. The type of the value produced by the unsigned right shift operator is the type of its left operand. If the converted type of the left operand is int, only the five least significant bits of the value of the right operand are used as the shift distance. So, the shift distance is in the range 0 through 31. Here, the value produced by r >>> s is the same as: s==0 ? r : (r >> s) & ~(-1> s is the same as the following: s==0 ? r : (r >> s) & ~(-1>>32))
intValue public int intValue() Returns The value of this object as an int. Overrides Number.intValue() Description This method returns the truncated value of this object as an int. More specifically, if the value of the object is NaN, the method returns 0. If the value is POSITIVE_INFINITY, or any other value that is too large to be represented by an int, the method returns Integer.MAX_VALUE. If the value is NEGATIVE_INFINITY, or any other value that is too small to be represented by an int, the method returns Integer.MIN_VALUE. Otherwise, the value is rounded toward zero and returned.
isInfinite public boolean isInfinite() Returns true if the value of this object is equal to POSITIVE_INFINITY or NEGATIVE_INFINITY; otherwise false. Description This method determines whether or not the value of this object is an infinity value.
isNaN public boolean isNaN() Returns true if the value of this object is equal to NaN; otherwise false. Description This method determines whether or not the value of this object is NaN.
http://localhost/java/javaref/langref/ch10_08.htm (10 of 12) [20/12/2001 11:20:03]
[Chapter 10] Double
longValue public long longValue() Returns The value of this object as a long. Overrides Number.longValue() Description This method returns the truncated value of this object as a long. More specifically, if the value of the object is NaN, the method returns 0. If the value is POSITIVE_INFINITY, or any other value too large to be represented by a long, the method returns Long.MAX_VALUE. If the value is NEGATIVE_INFINITY, or any other value too small to be represented by a long, the method returns Long.MIN_VALUE. Otherwise, the value is rounded toward zero and returned.
shortValue public short shortValue() Availability New as of JDK 1.1 Returns The value of this object as a short. Overrides Number.shortValue() Description This method returns the truncated value of this object as a short. More specifically, if the value of the object is NaN, the method returns 0. If the value is POSITIVE_INFINITY, or any other value that is too large to be represented by an short, the method returns Short.MAX_VALUE. If the value is NEGATIVE_INFINITY, or any other value that is too small to be represented by an short, the method returns Short.MIN_VALUE. Otherwise, the value is rounded toward zero and returned.
toString public String toString() Returns A string representation of the value of this object.
http://localhost/java/javaref/langref/ch10_08.htm (11 of 12) [20/12/2001 11:20:03]
[Chapter 10] Double
Overrides Object.toString() Description This method returns a String object that contains a representation of the value of this object. The values NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY, -0.0, and +0.0 are represented by the strings "NaN", "--Infinity", "Infinity", "--0.0", and "0.0", respectively. For other values, the exact string representation depends on the value being converted. If the absolute value of this object is greater than or equal to 10^-3 or less than or equal to 10^7, it is converted to a string with an optional minus sign (if the value is negative) followed by up to eight digits before the decimal point, a decimal point, and the necessary number of digits after the decimal point (but no trailing zero if there is more than one significant digit). There is always a minimum of one digit after the decimal point. Otherwise, the value is converted to a string with an optional minus sign (if the value is negative), followed by a single digit, a decimal point, the necessary number of digits after the decimal point (but no trailing zero if there is more than one significant digit), and the letter E followed by a plus or a minus sign and a base 10 exponent of at least one digit. Again, there is always a minimum of one digit after the decimal point. Note that the definition of this method has changed as of JDK 1.1. Prior to that release, the method provided a string representation that was equivalent to the %g format of the printf function in C.
Inherited Methods Method Inherited From Method Inherited From clone() Object finalize() Object getClass() Object notify() Object notifyAll() Object wait() Object wait(long) Object wait(long, int) Object
See Also Class; Exceptions; Float; Floating-point literals; Floating-point types; Number; String
Compiler
http://localhost/java/javaref/langref/ch10_08.htm (12 of 12) [20/12/2001 11:20:03]
Float
[Chapter 10] Float
Chapter 10 The java.lang Package
Float Name Float
Synopsis Class Name: java.lang.Float Superclass: java.lang.Number Immediate Subclasses: None Interfaces Implemented: None Availability: JDK 1.0 or later
Description The Float class provides an object wrapper for a float value. This is useful when you need to treat a float value as an object. For example, there are a number of utility methods that take a reference to an Object as one of their arguments. You cannot specify a float value for one of these arguments, but you can provide a reference to a Float object that encapsulates the float value. Furthermore, as of JDK 1.1, the Float class is necessary to support the Reflection API and class literals. In Java, float values are represented using the IEEE 754 format. The Float class provides constants
http://localhost/java/javaref/langref/ch10_09.htm (1 of 12) [20/12/2001 11:20:09]
[Chapter 10] Float
for the three special values that are mandated by this format: POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN (not-a-number). The Float class also provides some utility methods, such as methods for determining whether a floatx value is an infinity value or NaN, for converting float values to other primitive types, and for converting a float to a String and vice versa.
Class Summary public final class java.lang.Float extends java.lang.Number { // Constants public static final float MIN_VALUE; public static final float MAX_VALUE; public static final float NaN; public static final float NEGATIVE_INFINITY; public static final float POSITIVE_INFINITY; public final static Class TYPE; // New in 1.1 // Constructors public Float(double value); public Float(float value); public Float(String s); // Class Methods public static native int floatToIntBits(float value); public static native float intBitsToFloat(int bits); public static boolean isInfinite(float v); public static boolean isNaN(float v); public static String toString(float f); public static Float valueOf(String s); // Instance Methods public byte byteValue(); // New in 1.1 public double doubleValue(); public boolean equals(Object obj); public float floatValue(); public int hashCode(); public int intValue(); public boolean isInfinite(); public boolean isNaN(); public long longValue(); public short shortValue(); // New in 1.1 public String toString(); }
http://localhost/java/javaref/langref/ch10_09.htm (2 of 12) [20/12/2001 11:20:09]
[Chapter 10] Float
Constants MAX_VALUE public static final float MAX_VALUE = 3.40282346638528860e+38f Description The largest value that can be represented by a float.
MIN_VALUE public static final float MIN_VALUE = 1.40129846432481707e-45f Description The smallest value that can be represented by a float.
NaN public static final float NaN = 0.0f / 0.0f Description This variable represents the value NaN, a special value produced by float operations such as division of zero by zero. When NaN is one of the operands, most arithmetic operations return NaN as the result. Most comparison operators () return false when one of their arguments is NaN. The exception is !=, which returns true when one of its arguments is NaN.
NEGATIVE_INFINITY public static final float NEGATIVE_INFINITY = -1.0f / 0.0f Description This variable represents the value negative infinity, which is produced when a float operation underflows or a negative float value is divided by zero. Negative infinity is by definition less than any other float value.
POSITIVE_INFINITY public static final float POSITIVE_INFINITY = 1.0f / 0.0f Description This variable represents the value positive infinity, which is produced when a float operation overflows or a positive float value is divided by zero. Positive infinity is by definition greater
http://localhost/java/javaref/langref/ch10_09.htm (3 of 12) [20/12/2001 11:20:09]
[Chapter 10] Float
than any other float value.
TYPE public static final Class TYPE Availability New as of JDK 1.1 Description The Class object that represents the type float. It is always true that Float.TYPE == float.class.
Constructors Float public Float(double value) Parameters value The double value to be encapsulated by this object. Description Creates a Float object with the specified double value. The value is rounded to float precision. public Float(float value) Parameters value The float value to be encapsulated by this object. Description Creates a Float object with the specified float value. public Float(String s) throws NumberFormatException Parameters s The string to be made into a Float object. Throws
http://localhost/java/javaref/langref/ch10_09.htm (4 of 12) [20/12/2001 11:20:09]
[Chapter 10] Float
NumberFormatException If the sequence of characters in the given String does not form a valid float literal. Description Constructs a Float object with the value specified by the given string. The string must contain a sequence of characters that forms a legal float literal.
Class Methods floatToIntBits public static native int floatToIntBits(float value) Parameters value The float value to be converted. Returns The int value that contains the same sequence of bits as the representation of the given float value. Description This method returns the int value that contains the same sequence of bits as the representation of the given float value. The meaning of the bits in the result is defined by the IEEE 754 floating-point format: bit 31 is the sign bit, bits 30-23 are the exponent, and bits 22-0 are the mantissa. An argument of POSITIVE_INFINITY produces the result 0x7f800000, an argument of NEGATIVE_INFINITY produces the result 0xff800000, and an argument of NaN produces the result 0x7fc00000. The value returned by this method can be converted back to the original float value by the intBitsToFloat() method.
intBitsToFloat public static native float intBitsToFloat(int bits) Parameters bits The int value to be converted. Returns The float value whose representation is the same as the bits in the given int value. Description
http://localhost/java/javaref/langref/ch10_09.htm (5 of 12) [20/12/2001 11:20:09]
[Chapter 10] Float
This method returns the float value whose representation is the same as the bits in the given int value. The meaning of the bits in the int value is defined by the IEEE 754 floating-point format: bit 31 is the sign bit, bits 30-23 are the exponent, and bits 22-0 are the mantissa. The argument 0x7f800000 produces the result POSITIVE_INFINITY, and the argument 0xff800000 produces the result NEGATIVE_INFINITY. Arguments in the ranges 0x7f800001 through 0x7f8fffff and 0xff800001 through 0xff8fffffL all produce the result NaN. Except for NaN values not normally used by Java, this method is the inverse of the floatToIntBits() method.
isInfinite public static boolean isInfinite(float v) Parameters v The float value to be tested. Returns true if the specified value is equal to POSITIVE_INFINITY or NEGATIVE_INFINITY; otherwise false. Description This method determines whether or not the specified value is an infinity value.
isNaN public static boolean isNaN(float v) Parameters v The float value to be tested. Returns true if the specified value is equal to NaN; otherwise false. Description This method determines whether or not the specified value is NaN.
toString public static String toString(float f) Parameters http://localhost/java/javaref/langref/ch10_09.htm (6 of 12) [20/12/2001 11:20:09]
[Chapter 10] Float
f The float value to be converted. Returns A string representation of the given value. Description This method returns a String object that contains a representation of the given float value. The values NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY, -0.0, and +0.0 are represented by the strings "NaN", "--Infinity", "Infinity", "--0.0", and "0.0", respectively. For other values, the exact string representation depends on the value being converted. If the absolute value of f is greater than or equal to 10^-3 or less than or equal to 10^7, it is converted to a string with an optional minus sign (if the value is negative) followed by up to eight digits before the decimal point, a decimal point, and the necessary number of digits after the decimal point (but no trailing zero if there is more than one significant digit). There is always a minimum of one digit after the decimal point. Otherwise, the value is converted to a string with an optional minus sign (if the value is negative), followed by a single digit, a decimal point, the necessary number of digits after the decimal point (but no trailing zero if there is more than one significant digit), and the letter E followed by a plus or a minus sign and a base 10 exponent of at least one digit. Again, there is always a minimum of one digit after the decimal point. Note that the definition of this method has changed as of JDK 1.1. Prior to that release, the method provided a string representation that was equivalent to the %g format of the printf function in C.
valueOf public static Float valueOf(String s) throws NumberFormatException Parameters s The string to be made into a Float object. Returns The Float object constructed from the string. Throws NumberFormatException If the sequence of characters in the given String does not form a valid float literal. Description Constructs a Float object with the value specified by the given string. The string must contain a sequence of characters that forms a legal float literal. This method ignores leading and trailing http://localhost/java/javaref/langref/ch10_09.htm (7 of 12) [20/12/2001 11:20:09]
[Chapter 10] Float
whitespace in the string.
Instance Methods byteValue public byte byteValue() Availability New as of JDK 1.1 Returns The value of this object as a byte. Overrides Number.byteValue() Description This method returns the truncated value of this object as a byte. More specifically, if the value of the object is NaN, the method returns 0. If the value is POSITIVE_INFINITY, or any other value that is too large to be represented by an byte, the method returns Byte.MAX_VALUE. If the value is NEGATIVE_INFINITY, or any other value that is too small to be represented by an byte, the method returns Byte.MIN_VALUE. Otherwise, the value is rounded toward zero and returned.
doubleValue public double doubleValue() Returns The value of this object as a double. Overrides Number.doubleValue() Description This method returns the value of this object as a double.
equals public boolean equals(Object obj) Parameters obj
http://localhost/java/javaref/langref/ch10_09.htm (8 of 12) [20/12/2001 11:20:10]
[Chapter 10] Float
The object to be compared with this object. Returns true if the objects are equal; false if they are not. Overrides Object.equals() Description This method returns true if obj is an instance of Float and it contains the same value as the object this method is associated with. More specifically, the method returns true if the floatToIntBits() method returns the same result for the values of both objects. This method produces a different result than the == operator when both values are NaN. In this case, the == operator produces false, while this method returns true. By the same token, the method also produces a different result when the two values are +0.0 and -0.0. In this case, the == operator produces true, while this method returns false.
floatValue public float floatValue() Returns The value of this object as a float. Overrides Number.floatValue() Description This method returns the value of this object as a float.
hashCode public int hashCode() Returns A hashcode based on the float value of the object. Overrides Object.hashCode() Description This method returns a hashcode computed from the value of this object. More specifically, if f is the value of the object, this method returns Float.floatToIntBits(f).
http://localhost/java/javaref/langref/ch10_09.htm (9 of 12) [20/12/2001 11:20:10]
[Chapter 10] Float
intValue public int intValue() Returns The value of this object as an int. Overrides Number.intValue() Description This method returns the truncated value of this object as an int. More specifically, if the value of the object is NaN, the method returns 0. If the value is POSITIVE_INFINITY, or any other value that is too large to be represented by an int, the method returns Integer.MAX_VALUE. If the value is NEGATIVE_INFINITY, or any other value that is too small to be represented by an int, the method returns Integer.MIN_VALUE. Otherwise, the value is rounded toward zero and returned.
isInfinite public boolean isInfinite(float v) Returns true if the value of this object is equal to POSITIVE_INFINITY or NEGATIVE_INFINITY; otherwise false. Description This method determines whether or not the value of this object is an infinity value.
isNaN public boolean isNaN() Returns true if the value of this object is equal to NaN; otherwise false. Description This method determines whether or not the value of this object is NaN.
longValue public long longValue() Returns
http://localhost/java/javaref/langref/ch10_09.htm (10 of 12) [20/12/2001 11:20:10]
[Chapter 10] Float
The value of this object as a long. Overrides Number.longValue() Description This method returns the truncated value of this object as a long. More specifically, if the value of the object is NaN, the method returns 0. If the value is POSITIVE_INFINITY, or any other value that is too large to be represented by a long, the method returns Long.MAX_VALUE. If the value is NEGATIVE_INFINITY, or any other value that is too small to be represented by a long, the method returns Long.MIN_VALUE. Otherwise, the value is rounded toward zero and returned.
shortValue public short shortValue() Availability New as of JDK 1.1 Returns The value of this object as a short. Overrides Number.shortValue() Description This method returns the truncated value of this object as a short. More specifically, if the value of the object is NaN, the method returns 0. If the value is POSITIVE_INFINITY, or any other value that is too large to be represented by an short, the method returns Short.MAX_VALUE. If the value is NEGATIVE_INFINITY, or any other value that is too small to be represented by an short, the method returns Short.MIN_VALUE. Otherwise, the value is rounded toward zero and returned.
toString public String toString() Returns A string representation of the value of this object. Overrides Object.toString() Description
http://localhost/java/javaref/langref/ch10_09.htm (11 of 12) [20/12/2001 11:20:10]
[Chapter 10] Float
This method returns a String object that contains a representation of the value of this object. The values NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY, -0.0, and +0.0 are represented by the strings "NaN", "--Infinity", "Infinity", "--0.0", and "0.0", respectively. For other values, the exact string representation depends on the value being converted. If the absolute value of this object is greater than or equal to 10^-3 or less than or equal to 10^7, it is converted to a string with an optional minus sign (if the value is negative) followed by up to eight digits before the decimal point, a decimal point, and the necessary number of digits after the decimal point (but no trailing zero if there is more than one significant digit). There is always a minimum of one digit after the decimal point. Otherwise, the value is converted to a string with an optional minus sign (if the value is negative), followed by a single digit, a decimal point, the necessary number of digits after the decimal point (but no trailing zero if there is more than one significant digit), and the letter E followed by a plus or a minus sign and a base 10 exponent of at least one digit. Again, there is always a minimum of one digit after the decimal point. Note that the definition of this method has changed as of JDK 1.1. Prior to that release, the method provided a string representation that was equivalent to the %g format of the printf function in C.
Inherited Methods Method Inherited From Method Inherited From clone() Object finalize() Object getClass() Object notify() Object notifyAll() Object wait() Object wait(long) Object wait(long, int) Object
See Also Class; Double; Exceptions; Floating-point literals; Floating-point types; Number; String
Double
http://localhost/java/javaref/langref/ch10_09.htm (12 of 12) [20/12/2001 11:20:10]
Integer
[Chapter 4] 4.11 Boolean Operators
Chapter 4 Expressions
4.11 Boolean Operators The Boolean operators in Java are used for conditional AND (&&) and conditional OR (||) operations. These operators have different precedence; the && operator has the higher precedence and || the lower precedence. Both of the operators are evaluated from left to right. The unary operator ! provides a Boolean negation operation. References Boolean Negation Operator !; Order of Operations
Boolean AND Operator && The conditional AND operator && produces a pure boolean value that is the conditional AND of its operands. The && operator may appear in a conditional AND expression:
The conditional AND operator is evaluated from left to right. The operator never throws an exception. Here is a code example that shows the use of the conditional AND operator: public final short readShort() throws IOException { int ch1, ch2; if ((ch1 = in.read()) >= 0 && (ch2 = in.read()) >= 0) return (short)((ch1 5 ? 5 : n) { case 5: doIt(); case 4: doIt(); case 3: doIt(); case 2: doIt(); case 1: doIt(); } } The above method calls the doIt() method up to 5 times. To prevent control from flowing through case labels, it is common to end each case with a flow-altering statement such as a break statement. Other statements used for this purpose include the continue statement and the return statement. References Constant Expressions; Expression 4; Identifiers; Integer types; Local Classes; Local Variables; Statement 6; The break Statement; The continue Statement; The return Statement
The if Statement
http://localhost/java/javaref/langref/ch06_06.htm (2 of 2) [20/12/2001 11:21:22]
Iteration Statements
[Chapter 6] 6.8 The break Statement
Chapter 6 Statements and Control Structures
6.8 The break Statement A break statement transfers control out of an enclosing statement:
If a break statement does not contain an identifier, the statement attempts to transfer control to the statement that follows the innermost enclosing while, for, do, or switch statement. The Java compiler issues an error message if a break statement without an identifier occurs without an enclosing while, for, do, or switch statement. Here is an example of a break statement that contains no identifier: while (true) { c = in.read(); if (Character.isSpace(c) break; s += (char)c; } In this example, the break statement is used to exit from the while loop. The innermost while, for, do, or switch statement that encloses the break statement must be in the immediately enclosing method or initializer block. In other words, a break statement cannot be used to leave a method or initializer block. The break statement in the following example is used incorrectly and generates an error: while (true) { class X { void doIt() { break; } } new X().doIt(); http://localhost/java/javaref/langref/ch06_08.htm (1 of 3) [20/12/2001 11:21:27]
[Chapter 6] 6.8 The break Statement
} If a break statement contains an identifier, the identifier must be defined as the label of an enclosing statement. A break statement that contains an identifier attempts to transfer control to the statement that immediately follows the statement labeled with that identifier. Here's an example of a break statement that contains an identifier: foo:{ doIt(); if (n > 4) break foo; doIt(); } In this example, the break statement transfers control to the statement following the block labeled foo. The label used in a break statement must be in the immediately enclosing method or initializer block. The break statement in the following example is used incorrectly and generates an error: foo: { class X { void doIt() { break foo; } } new X().doIt(); } The statement to which a break statement attempts to transfer control is called the target statement. If a break statement occurs inside a try statement, control may not immediately transfer to the target statement. If a try statement has a finally clause, the finally block is executed before control leaves the try statement for any reason. This means that if a break statement occurs inside a try statement (but not in its finally block) and the target statement is outside of the try statement, the finally block is executed first, before the control transfer can take place. If the finally block contains a break, continue, return, or throw statement, the pending control transfer for the previously executed break statement is forgotten. Instead, control is transferred to the target of the break, continue, return, or throw statement in the finally block. If the finally block does not contain a break, continue, return, or throw statement, the pending control transfer happens after the finally block is done executing, unless the target statement is enclosed by another try statement. If there is another enclosing try statement and it has a finally clause, that finally block is also executed before the control transfer can take place. Execution proceeds in this manner until the target statement of the break is executed. Here is an example that illustrates a simple scenario: ll:{
http://localhost/java/javaref/langref/ch06_08.htm (2 of 3) [20/12/2001 11:21:27]
[Chapter 6] 6.8 The break Statement
try { f = new FileInputStream(fname); i = f.read(); if (i != ' ') break ll; i = f.read(); } catch (IOException e) { System.out.println("Got an IO Exception!"); break ll; } finally { f.close(); // Always executed } // Only reached if we don't break out of the try System.out.println("No breaks"); } In this example, a break statement is executed if one of two things happens. First, if an IOException is thrown, the catch clause prints a message and then executes a break statement. Otherwise, if the first call to read() does not return a space, a break statement is executed. In either case, the finally clause is executed before control is transferred to the statement following the statement labeled with ll. References Identifiers; Labeled Statements; The continue Statement; The do Statement; The for Statement; The return Statement; The throw Statement; The try Statement; The while Statement
Iteration Statements
http://localhost/java/javaref/langref/ch06_08.htm (3 of 3) [20/12/2001 11:21:27]
The continue Statement
[Chapter 6] 6.9 The continue Statement
Chapter 6 Statements and Control Structures
6.9 The continue Statement A continue statement stops the current iteration of an iteration statement and transfers control to the start of the next iteration:
A continue statement must occur within a while, for, or do statement or the compiler issues an error message. If a continue statement does not contain an identifier, the statement stops the current iteration in the innermost enclosing while, for, or do statement and attempts to transfer control to the start of the next iteration. This means that in a while or do statement, the continue statement transfers control to just after the contained statement of the while or do statement. In a for statement, the continue statement transfers control to the increment portion of the for statement. Here is an example of a continue statement that contains no identifier: public static void main (String[] argv) { for (int i=0; i tags inside the tag. A <param> tag must specify name and value attributes. For example:
http://localhost/java/javaref/langref/ch07_06.htm (3 of 4) [20/12/2001 11:22:24]
[Chapter 7] 7.6 Applets
<param name=speed value=65> If a Web browser does not support the tag, it ignores the tag and simply displays any HTML content provided inside the tag. However, if the browser understands the tag, this HTML content is ignored. This means that you can provide HTML content inside an tag to inform users of non-Java-enabled browsers about what they are missing. Here is an example that combines all of these elements: <param name=direction value=north> <param name=speed value=65>
If you can see this message, your Web browser is not Java enabled. There is a Java applet on this Web page that you are not seeing.
If a non-Java-enabled browser is used to view this HTML file, the following text is displayed: If you can see this message, your Web browser is not Java-enabled. There is a Java applet on this Web page that you are not seeing.
Applications
http://localhost/java/javaref/langref/ch07_06.htm (4 of 4) [20/12/2001 11:22:24]
Threads
[Chapter 8] 8.2 Synchronizing Multiple Threads
Chapter 8 Threads
8.2 Synchronizing Multiple Threads The correct behavior of a multithreaded program generally depends on multiple threads cooperating with each other. This often involves threads not doing certain things at the same time or waiting for each other to perform certain tasks. This type of cooperation is called synchronization. This section discusses some common strategies for synchronization and how they can be implemented in Java. The simplest strategy for ensuring that threads are correctly synchronized is to write code that works correctly when executed concurrently by any number of threads. However, this is more easily said than done. Most useful computations involve doing some activity, such as updating an instance variable or updating a display, that must be synchronized in order to happen correctly. If a method only updates its local variables and calls other methods that only modify their local variables, the method can be invoked by multiple threads without any need for synchronization. Math.sqrt() and the length() method of the String class are examples of such methods. A method that creates objects and meets the above criterion may not require synchronization. If the constructors invoked by the method do not modify anything but their own local variables and instance variables of the object they are constructing, and they only call methods that do not need to be synchronized, the method itself does not need to be synchronized. An example of such a method is the substring() in the String class. Beyond these two simple cases, it is impossible to give an exhaustive list of rules that can tell you whether or not a method needs to be synchronized. You need to consider what the method is doing and think about any ill effects of concurrent execution in order to decide if synchronization is necessary.
Single-Threaded Execution When more than one thread is trying to update the same data at the same time, the result may be wrong or inconsistent. Consider the following example: class CountIt { int i = 0; void count() { i = i + 1; } http://localhost/java/javaref/langref/ch08_02.htm (1 of 7) [20/12/2001 11:22:29]
[Chapter 8] 8.2 Synchronizing Multiple Threads
} The method count() is supposed to increment the variable i by one. However, suppose that there are two threads, A and B, that call count() at the same time. In this case, it is possible that i could be incremented only once, instead of twice. Say the value of i is 7. Thread A calls the count() method and computes i+1 as 8. Then thread B calls the count() method and computes i+1 as 8 because thread A has not yet assigned the new value to i. Next, thread A assigns the value 8 to the variable i. Finally, thread B assigns the value 8 to the variable i. Thus, even though the count() method is called twice, the variable has only been incremented once when the sequence is finished. Clearly, this code can fail to produce its intended result when it is executed concurrently by more than one thread. A piece of code that can fail to produce its intended result when executed concurrently is called a critical section. However, a critical section does behave correctly when it is executed by only one thread at a time. The strategy of single-threaded execution is to allow only one thread to execute a critical section of code at a time. If a thread wants to execute a critical section that another thread is already executing, the thread has to wait until the first thread is done and no other thread is executing that code before it can proceed. Java provides the synchronized statement and the synchronized method modifier for implementing single-threaded execution. Before executing the block in a synchronized statement, the current thread must obtain a lock for the object referenced by the expression. If a method is declared with the synchronized modifer, the current thread must obtain a lock before it can invoke the method. If the method is not declared static, the thread must obtain a lock associated with the object used to access the method. If the method is declared static, the thread must obtain a lock associated with the class in which the method is declared. Because a thread must obtain a lock before executing a synchronized method, Java guarantees that synchronized methods are executed by only one thread at a time. Modifying the count() method to make it a synchronized method ensures that it works as intended. class CountIt { int i = 0; synchronized void count() { i = i + 1; } } The strategy of single-threaded execution can also be used when multiple methods update the same data. Consider the following example: class CountIt2 { int i = 0; void count() { i = i + 1; } void count2() { http://localhost/java/javaref/langref/ch08_02.htm (2 of 7) [20/12/2001 11:22:29]
[Chapter 8] 8.2 Synchronizing Multiple Threads
i = i + 2; } } By the same logic used above, if the count() and count2() methods are executed concurrently, the result could be to increment i by 1, 2, or 3. Both the count() and count2() methods can be declared as synchronized to ensure that they are not executed concurrently with themselves or each other: class CountIt2 { int i = 0; synchronized void count() { i = i + 1; } synchronized void count2() { i = i + 2; } } Sometimes it's necessary for a thread to make multiple method calls to manipulate an object without another thread calling that object's methods at the same time. Consider the following example: System.out.print(new Date()); System.out.print(" : "); System.out.println(foo()); If the code in the example is executed concurrently by multiple threads, the output from the two threads will be interleaved. The synchronized keyword provides a way to ensure that only one thread at a time can execute a block of code. Before executing the block in a synchronized statement, the current thread must obtain a lock for the object referenced by the expression. The above code can be modified to give a thread exclusive access to the OutputStream object referenced by System.out: synchronized (System.out) { System.out.print(new Date()); System.out.print(" : "); System.out.println(foo()); } Note that this approach only works if other code that wants to call methods in the same object also uses similar synchronized statements, or if the methods in question are all synchronized methods. In this case, the print() and println() methods are synchronized, so other pieces of code that need to use these methods do not need to use a synchronized statement. When an inner class is updating fields in its enclosing instance, simply making a method synchronized does not provide the needed single-threaded execution. Consider the following code:
http://localhost/java/javaref/langref/ch08_02.htm (3 of 7) [20/12/2001 11:22:29]
[Chapter 8] 8.2 Synchronizing Multiple Threads
public class Z extends Frame { int pressCount = 0; ... private class CountButton extends Button implements ActionListener { public void actionPerformed(ActionEvent evt) { pressCount ++; } } ... } If a Z object instantiates more than one instance of CountButton, you need to use single-threaded execution to ensure that updates to pressCount are done correctly. Unfortunately, declaring the actionPerformed() method of CountButton to be synchronized does not accomplish that goal because it only forces the method to acquire a lock on the instance of CountButton it is associated with before it executes. The object you need to acquire a lock for is the enclosing instance of Z. One way to have a CountButton object capture a lock on its enclosing instance of Z is to update pressCount inside of a synchronized statement. For example: synchronized (Z.this) { pressCount ++; } The drawback to this approach is that every piece of code that accesses pressCount in any inner class of Z must be in a similar synchronized statement. Otherwise, it is possible for pressCount to be updated incorrectly. The more pieces of code that need to be inside of synchronized statements, the more places there are to introduce bugs in your program. A more robust approach is to have the inner class update a field in its enclosing instance by calling a synchronized method in the enclosing instance. For example: public class Z extends Frame { int pressCount = 0; synchronized incrementPressCount() { pressCount++; } ... private class CountButton extends Button implements ActionListener { public void actionPerformed(ActionEvent evt) { incrementPressCount(); } }
http://localhost/java/javaref/langref/ch08_02.htm (4 of 7) [20/12/2001 11:22:29]
[Chapter 8] 8.2 Synchronizing Multiple Threads
... } References Inner Classes; Method modifiers; The synchronized Statement
Optimistic Single-Threaded Execution When multiple threads are updating a data structure, single-threaded execution is the obvious strategy to use to ensure correctness of the operations on the data structure. However, single-threaded execution can cause some problems of its own. Consider the following example: public class Queue extends java.util.Vector { synchronized public void put(Object obj) { addElement(obj); } synchronized public Object get() throws EmptyQueueException { if (size() == 0) throw new EmptyQueueException(); Object obj = elementAt(0); removeElementAt(0); return obj; } } This example implements a first-in, first-out (FIFO) queue. If the get() method of a Queue object is called when the queue is empty, the method throws an exception. Now suppose that you want to write the get() method so that when the queue is empty, the method waits for an item to be put in the queue, rather than throwing an exception. In order for an item to be put in the queue, the put() method of the queue must be invoked. But using the single-threaded execution strategy, the put() method will never be able to run while the get() method is waiting for the queue to receive an item. A good way to solve this dilemma is to use a strategy called optimistic single-threaded execution. The optimistic single-threaded execution strategy is similar to the single-threaded execution strategy. They both begin by getting a lock on an object to ensure that the currently executing thread is the only thread that can execute a piece of code, and they both end by releasing that lock. The difference is what happens in between. Using the optimistic single-threaded execution strategy, if a piece of code discovers that conditions are not right to proceed, the code releases the lock it has on the object that enforces single-threaded execution and waits. When another piece of code changes things in such a way that might allow the first piece of code to proceed, it notifies the first piece of code that it should try to regain the lock and proceed. To implement this strategy, the Object class provides methods called wait(), notify(), and notifyAll(). These methods are inherited by every other class in Java. The following example shows how to implement a queue that uses the optimistic single-threaded execution strategy, so that when the queue is empty, its get() method waits for the queue to have an item put in it:
http://localhost/java/javaref/langref/ch08_02.htm (5 of 7) [20/12/2001 11:22:29]
[Chapter 8] 8.2 Synchronizing Multiple Threads
public class Queue extends java.util.Vector { synchronized public void put(Object obj) { addElement(obj); notify(); } synchronized public Object get() throws EmptyQueueException { while (size() == 0) wait(); Object obj = elementAt(0); removeElementAt(0); return obj; } } In the above implementation of the Queue class, the get() method calls wait() when the queue is empty. The wait() method releases the lock that excludes other threads from executing methods in the Queue object, and then waits until another thread calls the put() method. When put() is called, it adds an item to the queue and calls notify(). The notify() method tells a thread that is waiting to return from a wait() method that it should attempt to regain its lock and proceed. If there is more than one thread waiting to regain the lock on the object, notify() chooses one of the threads arbitrarily. The notifyAll() method is similar to notify(), but instead of choosing one thread to notify, it notifies all of the threads that are waiting to regain the lock on the object. Notice that the get() method calls wait() inside a while loop. Between the time that wait() is notified that it should try to regain its lock and the time it actually does regain the lock, another thread may have called the get() method and emptied the queue. The while loop guards against this situation. References Method modifiers; Object; The synchronized Statement
Rendezvous Sometimes it is necessary to have a thread wait to continue until another thread has completed its work and died. This type of synchronization uses the rendezvous strategy. The Thread class provides the join() method for implementing this strategy. When the join() method is called on a Thread object, the method returns immediately if the thread is dead. Otherwise, the method waits until the thread dies and then returns. References Thread
Balking Some methods should not be executed concurrently, and have a time-sensitive nature that makes postponing calls to them a bad idea. This is a common situation when software is controlling real-world devices. Suppose you have a Java program that is embedded in an electronic control for a toilet. There is a method called flush() that is responsible for flushing a toilet, and flush() can be called from more than one thread. If a thread calls flush() while another thread is already executing flush(), http://localhost/java/javaref/langref/ch08_02.htm (6 of 7) [20/12/2001 11:22:29]
[Chapter 8] 8.2 Synchronizing Multiple Threads
the second call should do nothing. A toilet is capable of only one flush at a time, and having a concurrent call to the flush() method result in a second flush would only waste water. This scenario suggests the use of the balking strategy. The balking strategy allows no more than one thread to execute a method at a time. If another thread attempts to execute the method, the method simply returns without doing anything. Here is an example that shows what such a flush() method might look like: boolean busy; void flush() { synchronized (this) { if (busy) return; busy = true; } // code to make flush happen goes here busy = false; }
Explicit Synchronization When the synchronization needs of a thread are not known in advance, you can use a strategy called explicit synchronization. The explicit synchronization strategy allows you to explicitly tell a thread when it can and cannot run. For example, you may want an animation to start and stop in response to external events that happen at unpredictable times, so you need to be able to tell the animation when it can run. To implement this strategy, the Thread class provides methods called suspend() and resume(). You can suspend the execution of a thread by calling the suspend() method of the Thread object that controls the thread. You can later resume execution of the thread by calling the resume() method on the Thread object. References Thread
Using Thread Objects
http://localhost/java/javaref/langref/ch08_02.htm (7 of 7) [20/12/2001 11:22:29]
Exception Handling
[Chapter 10] Thread
Chapter 10 The java.lang Package
Thread Name Thread
Synopsis Class Name: java.lang.Thread Superclass: java.lang.Object Immediate Subclasses: None Interfaces Implemented: java.lang.Runnable Availability: JDK 1.0 or later
Description The Thread class encapsulates all of the information about a single thread of control running in a Java environment. Thread objects are used to control threads in a multithreaded program. The execution of Java code is always under the control of a Thread object. The Thread class provides a static method called currentThread() that can be used to get a reference to the Thread object that controls the current thread of execution. In order for a Thread object to be useful, it must be associated with a method that it is supposed to run. http://localhost/java/javaref/langref/ch10_23.htm (1 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
Java provides two ways of associating a Thread object with a method: ● Declare a subclass of Thread that defines a run() method. When such a class is instantiated and the object's start() method is called, the thread invokes this run() method. ● Pass a reference to an object that implements the Runnable interface to a Thread constructor. When the start() method of such a Thread object is called, the thread invokes the run() method of the Runnable object. After a thread is started, it dies when one of the following things happens: ● The run() method called by the Thread returns. ● An exception is thrown that causes the run() method to be exited. ● The stop() method of the Thread is called.
Class Summary public class java.lang.Thread extends java.lang.Object implements java.lang.Runnable { // Constants public final static int MAX_PRIORITY; public final static int MIN_PRIORITY; public final static int NORM_PRIORITY; // Constructors public Thread(); public Thread(Runnable target); public Thread(Runnable target, String name); public Thread(String name); public Thread(ThreadGroup group, Runnable target); public Thread(ThreadGroup group, Runnable target, String name); public Thread(ThreadGroup group, String name); // Class Methods public static int activeCount(); public static native Thread currentThread(); public static void dumpStack(); public static int enumerate(Thread tarray[]); public static boolean interrupted(); public static native void sleep(long millis); public static void sleep(long millis, int nanos); public static native void yield(); // Instance Methods public void checkAccess(); public native int countStackFrames(); public void destroy(); public final String getName(); public final int getPriority(); http://localhost/java/javaref/langref/ch10_23.htm (2 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
public public public public public public public public public public public public public public public public public public
final ThreadGroup getThreadGroup(); void interrupt(); final native boolean isAlive(); final boolean isDaemon(); boolean isInterrupted(); final void join(); final synchronized void join(long millis); final synchronized void join(long millis, int nanos); final void resume(); void run(); final void setDaemon(boolean on); final void setName(String name); final void setPriority(int newPriority); synchronized native void start(); final void stop(); final synchronized void stop(Throwable o); final void suspend(); String toString();
}
Constants MAX_PRIORITY public final static int MAX_PRIORITY = 10 Description The highest priority a thread can have.
MIN_PRIORITY public final static int MIN_PRIORITY = 1 Description The lowest priority a thread can have.
NORM_PRIORITY public final static int NORM_PRIORITY = 5 Description The default priority assigned to a thread.
http://localhost/java/javaref/langref/ch10_23.htm (3 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
Constructors Thread public Thread() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description Creates a Thread object that belongs to the same ThreadGroup object as the current thread, has the same daemon attribute as the current thread, has the same priority as the current thread, and has a default name. A Thread object created with this constructor invokes its own run() method when the Thread object's start() method is called. This is not useful unless the object belongs to a subclass of the Thread class that overrides the run() method. Calling this constructor is equivalent to: Thread(null, null, genName) genName is an automatically generated name of the form "Thread-"+n, where n is an integer incremented each time a Thread object is created. public Thread(String name) Parameters name The name of this Thread object. Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description Creates a Thread object that belongs to the same ThreadGroup object as the current thread, has the same daemon attribute as the current thread, has the same priority as the current thread, and has the specified name. A Thread object created with this constructor invokes its own run() method when the Thread object's start() method is called. This is not useful unless the object belongs to a subclass of http://localhost/java/javaref/langref/ch10_23.htm (4 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
the Thread class that overrides the run() method. Calling this constructor is equivalent to: Thread(null, null, name) The uniqueness of the specified Thread object's name is not checked, which may be a problem for programs that attempt to identify Thread objects by their name. public Thread(ThreadGroup group, Runnable target) Parameters group The ThreadGroup object that this Thread object is to be added to. target A reference to an object that implements the Runnable interface. Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description Creates a Thread object that belongs to the specified ThreadGroup object, has the same daemon attribute as the current thread, has the same priority as the current thread, and has a default name. A Thread object created with this constructor invokes the run() method of the specified Runnable object when the Thread object's start() method is called. Calling this constructor is equivalent to: Thread(group, target, genName) genName is an automatically generated name of the form "Thread-"+n, where n is an integer that is incremented each time a Thread object is created. public Thread(ThreadGroup group, Runnable target, String name) Parameters group The ThreadGroup object that this Thread object is to be added to. target A reference to an object that implements the Runnable interface. http://localhost/java/javaref/langref/ch10_23.htm (5 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
name The name of this Thread object. Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description Creates a Thread object that belongs to the specified ThreadGroup object, has the same daemon attribute as the current thread, has the same priority as the current thread, and has the specified name. A Thread object created with this constructor invokes the run() method of the specified Runnable object when the Thread object's start() method is called. The uniqueness of the specified Thread object's name is not checked, which may be a problem for programs that attempt to identify Thread objects by their names. public Thread(ThreadGroup group, String name) Parameters group The ThreadGroup object that this Thread object is to be added to. name The name of this Thread object. Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description Creates a Thread object that belongs to the specified ThreadGroup object, has the same daemon attribute as the current thread, has the same priority as the current thread, and has the specified name. A Thread object created with this constructor invokes its own run() method when the Thread object's start() method is called. This is not useful unless the object belongs to a subclass of the Thread class that overrides the run() method. Calling this constructor is equivalent to: Thread(group, null, name) The uniqueness of the specified Thread object's name is not checked, which may be a problem
http://localhost/java/javaref/langref/ch10_23.htm (6 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
for programs that attempt to identify Thread objects by their name.
Class Methods activeCount public static int activeCount() Returns The current number of threads in the ThreadGroup of the currently running thread. Description This method returns the number of threads in the ThreadGroup of the currently running thread for which the isAlive() method returns true.
currentThread public static native Thread currentThread() Returns A reference to the Thread object that controls the currently executing thread. Description This method returns a reference to the Thread object that controls the currently executing thread.
dumpStack public static void dumpStack() Description This method outputs a stack trace of the currently running thread.
enumerate public static int enumerate(Thread tarray[]) Parameters tarray A reference to an array of Thread objects. Returns The number of Thread objects stored in the array. Description http://localhost/java/javaref/langref/ch10_23.htm (7 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
This method stores a reference in the array for each of the Thread objects in the ThreadGroup of the currently running thread for which the isAlive() method returns true. Calling this method is equivalent to: currentThread().getThreadGroup().enumerate(tarray) If the array is not big enough to contain references to all the Thread objects, only as many references as will fit are put into the array. No indication is given that some Thread objects were left out, so it is a good idea to call activeCount() before calling this method, to get an idea of how large to make the array.
interrupted public static boolean interrupted() Returns true if the currently running thread has been interrupted; otherwise false. Description This method determines whether or not the currently running thread has been interrupted.
sleep public static native void sleep(long millis) Parameters millis The number of milliseconds that the currently running thread should sleep. Throws InterruptedException If another thread interrupts the currently running thread. Description This method causes the currently running thread to sleep. The method does not return until at least the specified number of milliseconds have elapsed. While a thread is sleeping, it retains ownership of all locks. The Object class defines a method called wait() that is similar to sleep() but causes the currently running thread to temporarily relinquish its locks. public static void sleep(long millis, int nanos) Parameters http://localhost/java/javaref/langref/ch10_23.htm (8 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
millis The number of milliseconds that the currently running thread should sleep. nanos An additional number of nanoseconds to sleep. Throws InterruptedException If another thread interrupts the currently running thread. Description This method causes the currently running thread to sleep. The method does not return until at least the specified number of milliseconds have elapsed. While a thread is sleeping, it retains ownership of all locks. The Object class defines a method called wait() that is similar to sleep() but causes the currently running thread to temporarily relinquish its locks. Note that Sun's reference implementation of Java does not attempt to implement the precision implied by this method. Instead, it rounds to the nearest millisecond (unless millis is 0, in which case it rounds up to 1 millisecond) and calls sleep(long).
yield public static native void yield() Description This method causes the currently running thread to yield control of the processor so that another thread can be scheduled.
Instance Methods checkAccess public void checkAccess() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method determines if the currently running thread has permission to modify this Thread object. http://localhost/java/javaref/langref/ch10_23.htm (9 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
countStackFrames public native int countStackFrames() Returns The number of pending method invocations on this thread's stack. Description This method returns the number of pending method invocations on this thread's stack.
destroy public void destroy() Description This method is meant to terminate this thread without any of the usual cleanup (i.e., any locks held by the thread are not released). This method provides a last-resort way to terminate a thread. While a thread can defeat its stop() method by catching objects thrown from it, there is nothing that a thread can do to stop itself from being destroyed. Note that Sun's reference implementation of Java does not implement the documented functionality of this method. Instead, the implementation of this method just throws a NoSuchMethodError.
getName public final String getName() Returns The name of this thread. Description This method returns the name of this Thread object.
getPriority public final int getPriority() Returns The priority of this thread. Description This method returns the priority of this Thread object.
http://localhost/java/javaref/langref/ch10_23.htm (10 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
getThreadGroup public final ThreadGroup getThreadGroup() Returns The ThreadGroup of this thread. Description This method returns a reference to the ThreadGroup that this Thread object belongs to.
interrupt public void interrupt() Description This method interrupts this Thread object. Note that prior to version 1.1, Sun's reference implementation of Java does not implement the documented functionality of this method. Instead, the method just sets a private flag that indicates that an interrupt has been requested. None of the methods that should throw an InterruptedException currently do. However, the interrupted() and isInterrupted() methods do return true after this method has been called.
isAlive public final native boolean isAlive() Returns true if this thread is alive; otherwise false. Description This method determines whether or not this Thread object is alive. A Thread object is alive if it has been started and has not yet died. In other words, it has been scheduled to run before and can still be scheduled to run again. A thread is generally alive after its start() method is called and until its stop() method is called.
isDaemon public final boolean isDaemon() Returns true if the thread is a daemon thread; otherwise false. Description
http://localhost/java/javaref/langref/ch10_23.htm (11 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
This method determines whether or not this thread is a daemon thread, based on the value of the daemon attribute of this Thread object.
isInterrupted public boolean isInterrupted() Returns true if this thread has been interrupted; otherwise false. Description This method determines whether or not this Thread object has been interrupted.
join public final void join() Throws InterruptedException If another thread interrupts this thread. Description This method allows the thread that calls it to wait for the Thread associated with this method to die. The method returns when the Thread dies. If this thread is already dead, then this method returns immediately. public final synchronized void join(long millis) Parameters millis The maximum number of milliseconds to wait for this thread to die. Throws InterruptedException If another thread interrupts this thread. Description This method causes a thread to wait to die. The method returns when this Thread object dies or after the specified number of milliseconds has elapsed, whichever comes first. However, if the specified number of milliseconds is zero, the method will wait forever for this thread to die. If this thread is already dead, the method returns immediately. public final synchronized void join(long millis, int nanos)
http://localhost/java/javaref/langref/ch10_23.htm (12 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
Parameters millis The maximum number of milliseconds to wait for this thread to die. nanos An additional number of nanoseconds to wait. Throws InterruptedException If another thread interrupts this thread. Description This method causes a thread to wait to die. The method returns when this Thread object dies or after the specified amount of time has elapsed, whichever comes first. However, if millis and nanos are zero, the method will wait forever for this thread to die. If this thread is already dead, the method returns immediately. Note that Sun's reference implementation of Java does not attempt to implement the precision implied by this method. Instead, it rounds to the nearest millisecond (unless millis is 0, in which case it rounds up to 1 millisecond) and calls join(long).
resume public final void resume() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method resumes a suspended thread. The method causes this Thread object to once again be eligible to be run. Calling this method for a thread that is not suspended has no effect.
run public void run() Implements Runnable.run() Description A Thread object's start() method causes the thread to invoke a run() method. If this Thread object was created without a specified Runnable object, the Thread object's own
http://localhost/java/javaref/langref/ch10_23.htm (13 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
run() method is executed. This behavior is only useful in a subclass of Thread that overrides this run() method, since the run() method of the Thread class does not do anything.
setDaemon public final void setDaemon(boolean on) Parameters on The new value for this thread's daemon attribute. Throws IllegalThreadStateException If this method is called after this thread has been started and while it is still alive. SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method sets the daemon attribute of this Thread object to the given value. This method must be called before the thread is started. If a thread dies and there are no other threads except daemon threads alive, the Java virtual machine stops.
setName public final void setName(String name) Parameters name The new name for this thread. Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method sets the name of this Thread object to the given value. The uniqueness of the specified Thread object's name is not checked, which may be a problem for programs that attempt to identify Thread objects by their name.
http://localhost/java/javaref/langref/ch10_23.htm (14 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
setPriority public final void setPriority(int newPriority) Parameters newPriority The new priority for this thread. Throws IllegalArgumentException If the given priority is less than MIN_PRIORITY or greater than MAX_PRIORITY. SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method sets the priority of this Thread to the given value.
start public synchronized native void start() Throws IllegalThreadStateException If this Thread object's start() method has been called before. Description This method starts this Thread object, allowing it to be scheduled for execution. The top-level code that is executed by the thread is the run() method of the Runnable object specified in the constructor that was used to create this object. If no such object was specified, the top-level code executed by the thread is this object's run() method. It is not permitted to start a thread more than once.
stop public final void stop() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException.
http://localhost/java/javaref/langref/ch10_23.htm (15 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
Description This method causes this Thread object to stop executing by throwing a ThreadDeath object. The object is thrown in this thread, even if the method is called from a different thread. This thread is forced to stop whatever it is doing and throw a newly created ThreadDeath object. If this thread was suspended, it is resumed; if it was sleeping, it is awakened. Normally, you should not catch ThreadDeath objects in a try statement. If you need to catch ThreadDeath objects to detect a Thread is about to die, the try statement that catches ThreadDeath objects should rethrow them. When an object is thrown out of the run() method associated with a Thread, the uncaughtException() method of the ThreadGroup for that Thread is called. The uncaughtException() method normally outputs a stack trace. However, uncaughtException() treats a ThreadDeath object as a special case by not outputting a stack trace. When the uncaughtException() method returns, the thread is dead. The thread is never scheduled to run again. If this Thread object's stop() method is called before this thread is started, the ThreadDeath object is thrown as soon as the thread is started. public final synchronized void stop(Throwable o) Parameters o The object to be thrown. Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method causes this Thread object to stop executing by throwing the given object. Normally, the stop() method that takes no arguments and throws a ThreadDeath object should be called instead of this method. However, if it is necessary to stop a thread by throwing some other type of object, this method can be used. The object is thrown in this thread, even if the method is called from a different thread. This thread is forced to stop whatever it is doing and throw the Throwable object o. If this thread was suspended, it is resumed; if it was sleeping, it is awakened. When an object is thrown out of the run() method associated with a Thread, the uncaughtException() method of the ThreadGroup for that Thread is called. If the thrown object is not an instance of the ThreadDeath class, uncaughtException() calls the thrown object's printStackTrace() method and then the thread dies. The thread is never scheduled to run again.
http://localhost/java/javaref/langref/ch10_23.htm (16 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
If this Thread object's stop() method is called before this thread is started, the ThreadDeath object is thrown as soon as the thread is started.
suspend public final void suspend() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method suspends a thread. The method causes this Thread object to temporarily be ineligible to be run. The thread becomes eligible to be run again after its resume() method is called. Calling this method for a thread that is already suspended has no effect.
toString public String toString() Returns A string representation of this Thread object. Overrides Object.toString() Description This method returns a string representation of this Thread object.
Inherited Methods Method Inherited From Method Inherited From clone() Object equals(Object) Object finalize() Object getClass() Object hashCode() Object notify() Object notifyAll() Object wait() Object wait(long) Object wait(long, int) Object
http://localhost/java/javaref/langref/ch10_23.htm (17 of 18) [20/12/2001 11:22:37]
[Chapter 10] Thread
See Also Exceptions; Object; Runnable; SecurityManager; ThreadGroup; Threads 8
System
http://localhost/java/javaref/langref/ch10_23.htm (18 of 18) [20/12/2001 11:22:37]
ThreadGroup
[Chapter 10] Runnable
Chapter 10 The java.lang Package
Runnable Name Runnable
Synopsis Interface Name: java.lang.Runnable Super-interface: None Immediate Sub-interfaces: None Implemented By: java.lang.Thread Availability: JDK 1.0 or later
Description The Runnable interface declares the run() method that is required for use with the Thread class. Any class that implements the Runnable interface must define a run() method. This method is the top-level code that is run by a thread.
http://localhost/java/javaref/langref/ch10_16.htm (1 of 2) [20/12/2001 11:22:41]
[Chapter 10] Runnable
Interface Declaration public interface java.lang.Runnable { // Methods public abstract void run(); }
Methods run public abstract void run() Description When a Thread object starts running a thread, it associates executable code with the thread by calling a Runnable object's run() method. The subsequent behavior of the thread is controlled by the run() method. Thus, a class that wants to perform certain operations in a separate thread should implement the Runnable interface and define an appropriate run() method. When the run() method called by a Thread object returns or throws an exception, the thread dies.
See Also Thread; ThreadGroup; Threads 8
Process
http://localhost/java/javaref/langref/ch10_16.htm (2 of 2) [20/12/2001 11:22:41]
Runtime
[Chapter 10] ThreadGroup
Chapter 10 The java.lang Package
ThreadGroup Name ThreadGroup
Synopsis Class Name: java.lang.ThreadGroup Superclass: java.lang.Object Immediate Subclasses: None Interfaces Implemented: None Availability: JDK 1.0 or later
Description The ThreadGroup class implements a grouping scheme for threads. A ThreadGroup object can own Thread objects and other ThreadGroup objects. The ThreadGroup class provides methods that allow a ThreadGroup object to control its Thread and ThreadGroup objects as a group. For example, suspend() and resume() methods of a ThreadGroup object call the suspend() and resume() methods of each of the Thread and ThreadGroup objects that belong to the particular ThreadGroup. When a Java program starts, a ThreadGroup object is created to own the first Thread. Any additional
http://localhost/java/javaref/langref/ch10_24.htm (1 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
ThreadGroup objects are explicitly created by the program.
Class Summary public class java.lang.ThreadGroup extends java.lang.Object { // Constructors public ThreadGroup(String name); public ThreadGroup(ThreadGroup parent, String name; // Instance Methods public int activeCount(); public int activeGroupCount(); public boolean allowThreadSuspension(boolean b); // New in 1.1 public final void checkAccess(); public final void destroy(); public int enumerate(Thread list[]); public int enumerate(Thread list[], boolean recurse); public int enumerate(ThreadGroup list[]); public int enumerate(ThreadGroup list[], boolean recurse); public final int getMaxPriority(); public final String getName(); public final ThreadGroup getParent(); public final boolean isDaemon(); public synchronized boolean isDestroyed(); // New in 1.1 public void list(); public final boolean parentOf(ThreadGroup g); public final void resume(); public final void setDaemon(boolean daemon); public final void setMaxPriority(int pri); public final void stop(); public final void suspend(); public String toString(); public void uncaughtException(Thread t, Throwable e); }
Constructors ThreadGroup public ThreadGroup(String name) Parameters name The name of this ThreadGroup object.
http://localhost/java/javaref/langref/ch10_24.htm (2 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description Creates a ThreadGroup object that has the specified name and the same parent ThreadGroup as the current thread. public ThreadGroup(ThreadGroup parent, String name) Parameters parent The ThreadGroup object that this ThreadGroup object is to be added to. name The name of this ThreadGroup object. Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description Creates a ThreadGroup object with the specified name and parent ThreadGroup object.
Instance Methods activeCount public int activeCount() Returns An approximation of the current number of threads in this ThreadGroup object and any child ThreadGroup objects. Description This method returns an approximation of the number of threads that belong to this ThreadGroup object and any child ThreadGroup objects. The count is approximate because a thread can die after it is counted, but before the complete count is returned. Also, after a child ThreadGroup is counted but before the total count is returned, additional Thread and ThreadGroup objects can be added to a child ThreadGroup.
http://localhost/java/javaref/langref/ch10_24.htm (3 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
activeGroupCount public int activeGroupCount() Returns An approximation of the current number of child ThreadGroup objects in this ThreadGroup object. Description This method returns an approximation of the number of child ThreadGroup objects that belong to this ThreadGroup object. The count is approximate because after a child ThreadGroup is counted but before the total count is returned, additional ThreadGroup objects can be added to a child ThreadGroup.
allowThreadSuspension public boolean allowThreadSuspension(boolean b) Availability New as of JDK 1.1 Parameters b A boolean value that specifies whether or not the run-time system is allowed to suspend threads due to low memory. Returns The boolean value true. Description This method specifies whether or not the Java virtual machine is allowed to suspend threads due to low memory.
checkAccess public final void checkAccess() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method determines if the currently running thread has permission to modify this ThreadGroup object. http://localhost/java/javaref/langref/ch10_24.htm (4 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
destroy public final void destroy() Throws IllegalThreadStateException If this ThreadGroup object is not empty, or if it has already been destroyed. SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method destroys this ThreadGroup object and any child ThreadGroup objects. The ThreadGroup must not contain any Thread objects. This method also removes the ThreadGroup object from its parent ThreadGroup object.
enumerate public int enumerate(Thread list[]) Parameters list A reference to an array of Thread objects. Returns The number of Thread objects stored in the array. Description This method stores a reference in the array for each of the Thread objects that belongs to this ThreadGroup or any of its child ThreadGroup objects. If the array is not big enough to contain references to all the Thread objects, only as many references as will fit are put into the array. No indication is given that some Thread objects were left out, so it is a good idea to call activeCount() before calling this method, to get an idea of how large to make the array. public int enumerate(Thread list[], boolean recurse) Parameters list A reference to an array of Thread objects. recurse A boolean value that specifies whether or not to include Thread objects that belong to http://localhost/java/javaref/langref/ch10_24.htm (5 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
child ThreadGroup objects of this ThreadGroup object. Returns The number of Thread objects stored in the array. Description This method stores a reference in the array for each of the Thread objects that belongs to this ThreadGroup object. If recurse is true, the method also stores a reference for each of the Thread objects that belongs to a child ThreadGroup object of this ThreadGroup. If the array is not big enough to contain references to all the Thread objects, only as many references as will fit are put into the array. No indication is given that some Thread objects were left out, so it is a good idea to call activeCount() before calling this method, to get an idea of how large to make the array. public int enumerate(ThreadGroup list[]) Parameters list A reference to an array of ThreadGroup objects. Returns The number of ThreadGroup objects stored in the array. Description This method stores a reference in the array for each ThreadGroup object that belongs to this ThreadGroup or any of its child ThreadGroup objects. If the array is not big enough to contain references to all the ThreadGroup objects, only as many references as will fit are put into the array. No indication is given that some ThreadGroup objects were left out, so it is a good idea to call activeGroupCount() before calling this method, to get an idea of how large to make the array. public int enumerate(Thread list[], boolean recurse) Parameters list A reference to an array of ThreadGroup objects. recurse A boolean value that specifies whether or not to include ThreadGroup objects that belong to child ThreadGroup objects of this ThreadGroup object. Returns The number of ThreadGroup objects stored in the array. Description
http://localhost/java/javaref/langref/ch10_24.htm (6 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
This method stores a reference in the array for each of the ThreadGroup objects that belongs to this ThreadGroup object. If recurse is true, the method also stores a reference for each of the ThreadGroup objects that belongs to a child ThreadGroup object of this ThreadGroup. If the array is not big enough to contain references to all the ThreadGroup objects, only as many references as will fit are put into the array. No indication is given that some ThreadGroup objects were left out, so it is a good idea to call activeGroupCount() before calling this method, to get an idea of how large to make the array.
getMaxPriority public final int getMaxPriority() Returns The maximum priority that can be assigned to Thread objects that belong to this ThreadGroup object. Description This method returns the maximum priority that can be assigned to Thread objects that belong to this ThreadGroup object. It is possible for a ThreadGroup to contain Thread objects that have higher priorities than this maximum, if they were given that higher priority before the maximum was set to a lower value.
getName public final String getName() Returns The name of this ThreadGroup object. Description This method returns the name of this ThreadGroup object.
getParent public final ThreadGroup getParent() Returns The parent ThreadGroup object of this ThreadGroup, or null if this ThreadGroup is the root of the thread group hierarchy. Description This method returns the parent ThreadGroup object of this ThreadGroup object. If this ThreadGroup is at the root of the thread group hierarchy and has no parent, the method returns null.
http://localhost/java/javaref/langref/ch10_24.htm (7 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
isDaemon public final boolean isDaemon() Returns true if this ThreadGroup is a daemon thread group; otherwise false. Description This method determines whether or not this ThreadGroup is a daemon thread group, based on the value of daemon attribute of this ThreadGroup object. A daemon thread group is destroyed when the last Thread in it is stopped, or the last ThreadGroup in it is destroyed.
isDestroyed public synchronized boolean isDestroyed() Availability New as of JDK 1.1 Returns true if this ThreadGroup has been destroyed; otherwise false. Description This method determines whether or not this ThreadGroup has been destroyed.
list public void list() Description This method outputs a listing of the contents of this ThreadGroup object to System.out.
parentOf public final boolean parentOf(ThreadGroup g) Parameters g A ThreadGroup object. Returns true if this ThreadGroup object is the same ThreadGroup, or a direct or indirect parent of the specified ThreadGroup; otherwise false. Description http://localhost/java/javaref/langref/ch10_24.htm (8 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
This method determines if this ThreadGroup object is the same as the specified ThreadGroup or one of its ancestors in the thread-group hierarchy.
resume public final void resume() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method resumes each Thread object that directly or indirectly belongs to this ThreadGroup object by calling its resume() method.
setDaemon public final void setDaemon(boolean daemon) Parameters daemon The new value for this ThreadGroup object's daemon attribute. Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method sets the daemon attribute of this ThreadGroup object to the given value. A daemon thread group is destroyed when the last Thread in it is stopped, or the last ThreadGroup in it is destroyed.
setMaxPriority public final void setMaxPriority(int pri) Parameters pri The new maximum priority for Thread objects that belong to this ThreadGroup object. Description This method sets the maximum priority that can be assigned to Thread objects that belong to this http://localhost/java/javaref/langref/ch10_24.htm (9 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
ThreadGroup object. It is possible for a ThreadGroup to contain Thread objects that have higher priorities than this maximum, if they were given that higher priority before the maximum was set to a lower value.
stop public final void stop() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method stops each Thread object that directly or indirectly belongs to this ThreadGroup object by calling its stop() method.
suspend public final void suspend() Throws SecurityException If the checkAccess() method of the SecurityManager throws a SecurityException. Description This method suspends each Thread object that directly or indirectly belongs to this ThreadGroup object by calling its suspend() method.
toString public String toString() Returns A string representation of this ThreadGroup object. Overrides Object.toString() Description This method returns a string representation of this ThreadGroup object.
http://localhost/java/javaref/langref/ch10_24.htm (10 of 11) [20/12/2001 11:22:47]
[Chapter 10] ThreadGroup
uncaughtException public void uncaughtException(Thread t, Throwable e) Parameters t A reference to a Thread that just died because of an uncaught exception. e The uncaught exception. Description This method is called when a Thread object that belongs to this ThreadGroup object dies because of an uncaught exception. If this ThreadGroup object has a parent ThreadGroup object, this method just calls the parent's uncaughtException() method. Otherwise, this method must determine whether the uncaught exception is an instance of ThreadDeath. If it is, nothing is done. If it is not, the method calls the printStackTrace() method of the exception object. If this method is overridden, the overriding method should end with a call to super.uncaughtException().
Inherited Methods Method Inherited From Method Inherited From clone() Object equals(Object) Object finalize() Object getClass() Object hashCode() Object notify() Object notifyAll() Object wait() Object wait(long) Object wait(long, int) Object
See Also Exceptions; Object; Runnable; SecurityManager; Thread; Threads 8; Throwable
Thread
http://localhost/java/javaref/langref/ch10_24.htm (11 of 11) [20/12/2001 11:22:47]
Throwable
[Chapter 9] 9.2 Declaring Exceptions
Chapter 9 Exception Handling
9.2 Declaring Exceptions If a method is expected to throw any exceptions, the method declaration must declare that fact in a throws clause. If a method implementation contains a throw statement, it is possible that an exception will be thrown from within the method. In addition, if a method calls another method declared with a throws clause, there is the possibility that an exception will be thrown from within the method. If the exception is not caught inside the method with a try statement, it will be thrown out of the method to its caller. Any exception that can be thrown out of a method in this way must be listed in a throws clause in the method declaration. The classes listed in a throws clause must be Throwable or any of its subclasses; the Throwable class is the superclass of all objects that can be thrown in Java. However, there are certain types of exceptions that do not have to be listed in a throws clause. Specifically, if the exception is an instance of Error, RuntimeException, or a subclass of one of those classes, it does not have to be listed in a throws clause. Subclasses of the Error class correspond to situations that are not easily predicted, such as the system running out of memory. Subclasses of RuntimeException correspond to many common run-time problems, such as illegal casts and array index problems. The reason that these types of exceptions are treated specially is that they can be thrown from such a large number of places that essentially every method would have to declare them. Consider the following example: import java.io.IOException; class throwsExample { char[] a; int position; ... // Method explicitly throws an exception int read() throws IOException { if (position >= a.length) throw new IOException(); return a[position++]; } // Method implicitly throws an exception String readUpTo(char terminator) throws IOException { http://localhost/java/javaref/langref/ch09_02.htm (1 of 3) [20/12/2001 11:22:52]
[Chapter 9] 9.2 Declaring Exceptions
StringBuffer s = new StringBuffer(); while (true) { int c = read(); // Can throw IOException if (c == -1 || c == terminator) { return s.toString(); } s.append((char)c); } return s.toString(); } // Method catches an exception internally int getLength() { String s; try { s = readUpTo(':'); } catch (IOException e) { return 0; } return s.length(); } // Method can throw a RuntimeException int getAvgLength() { int count = 0; int total = 0; int len; while (true){ len = getLength(); if (len == 0) break; count++; total += len; } return total/count; // Can throw ArithmeticException } } The method read() can throw an IOException, so it declares that fact in its throws clause. Without that throws clause, the compiler would complain that the method must either declare IOException in its throws clause or catch it. Although the readUpTo() method does not explicitly throw any exceptions, it calls the read() method that does throw an IOException, so it declares that fact in its throws clause. Whether explicitly or implicitly thrown, the requirement to catch or declare an exception is the same. The getLength() method catches the IOException thrown by readUpTo(), so it does not have to declare the exception. The final method, getAvgLength(), can throw an ArithmeticException if count is zero. Because ArithmeticException is a subclass of RuntimeException, the fact that it can be thrown out of getAvgLength() does not need to be declared in a throws clause. http://localhost/java/javaref/langref/ch09_02.htm (2 of 3) [20/12/2001 11:22:52]
[Chapter 9] 9.2 Declaring Exceptions
References Constructors; Errors; Methods; Runtime exceptions; The throw Statement; The try Statement; Throwable
Handling Exceptions
http://localhost/java/javaref/langref/ch09_02.htm (3 of 3) [20/12/2001 11:22:52]
Generating Exceptions
[Chapter 9] 9.3 Generating Exceptions
Chapter 9 Exception Handling
9.3 Generating Exceptions A Java program can use the exception-handling mechanism to deal with program-specific errors in a clean manner. A program simply uses the throw statement to signal an exception. The throw statement must be followed by an object that is of type Throwable or one of its subclasses. For program-defined exceptions, you typically want an exception object to be an instance of a subclass of the Exception class. In most cases, it makes sense to define a new subclass of Exception that is specific to your program. Consider the following example: class WrongDayException extends Exception { public WrongDayException () {} public WrongDayException(String msg) { super(msg); } } public class ThrowExample { void doIt() throws WrongDayException{ int dayOfWeek =(new java.util.Date()).getDay(); if (dayOfWeek != 2 && dayOfWeek != 4) throw new WrongDayException("Tue. or Thur."); // The rest of doIt's logic goes here System.out.println("Did it"); } public static void main (String [] argv) { try { (new ThrowExample()).doIt(); } catch (WrongDayException e) { System.out.println("Sorry, can do it only on " + e.getMessage()); } } }
http://localhost/java/javaref/langref/ch09_03.htm (1 of 3) [20/12/2001 11:22:56]
[Chapter 9] 9.3 Generating Exceptions
The code in this example defines a class called WrongDayException to represent the specific type of exception thrown by the example. The Throwable class, and most subclasses of Throwable, have at least two constructors. One constructor takes a string argument that is used as a textual message that explains the exception, while the other constructor takes no arguments. Thus, the WrongDayException class defines two constructors. In the class ThrowExample, if the current day of the week is neither Tuesday nor Thursday, the doIt() method throws a WrongDayException. Note that the WrongDayException object is created at the same time it is thrown. It is common practice to provide some information about an exception when it is thrown, so a string argument is used in the allocation statement for the WrongDayException. The method declaration for the doIt() method contains a throws clause, to indicate the fact that it can throw a WrongDayException. The main() method in ThrowExample encloses its call to the doIt() method in a try statement, so that it can catch any WrongDayException thrown by doIt(). The catch block prints an error message, using the getMessage() method of the exception object. This method retrieves the string that was passed to the constructor when the exception object was created. References Constructors; Exceptions; Methods; The throw Statement; The try Statement; Throwable
Printing Stack Traces When an exception is caught, it can be useful to print a stack trace to figure out where the exception came from. A stack trace looks like the following: java.lang.ArithmeticException: / by zero at t.cap(t.java:16) at t.doit(t.java:8) at t.main(t.java:3) You can print a stack trace by calling the printStackTrace() method that all Throwable objects inherit from the Throwable class. For example: int cap (x) {return 100/x} try { cap(0); } catch(ArithmeticException e) { e.printStackTrace(); } You can also print a stack trace anywhere in an application, without actually throwing an exception. For example: new Throwable().printStackTrace(); References Throwable
http://localhost/java/javaref/langref/ch09_03.htm (2 of 3) [20/12/2001 11:22:56]
[Chapter 9] 9.3 Generating Exceptions
Rethrowing Exceptions After an exception is caught, it can be rethrown if is appropriate. The one choice that you have to make when rethrowing an exception concerns the location from where the stack trace says the object was thrown. You can make the rethrown exception appear to have been thrown from the location of the original exception throw, or from the location of the current rethrow. To rethrow an exception and have the stack trace indicate the original location, all you have to do is rethrow the exception: try { cap(0); } catch(ArithmeticException e) { throw e; } To arrange for the stack trace to show the actual location from which the exception is being rethrown, you have to call the exception's fillInStackTrace() method. This method sets the stack trace information in the exception based on the current execution context. Here's an example using the fillIn-StackTrace() method: try { cap(0); } catch(ArithmeticException e) { throw (ArithmeticException)e.fillInStackTrace(); } It is important to call fillInStackTrace() on the same line as the throw statement, so that the line number specified in the stack trace matches the line on which the throw statement appears. The fillInStackTrace() method returns a reference to the Throwable class, so you need to cast the reference to the actual type of the exception. References Throwable
Declaring Exceptions
http://localhost/java/javaref/langref/ch09_03.htm (3 of 3) [20/12/2001 11:22:56]
The Exception Hierarchy
[Chapter 10] Throwable
Chapter 10 The java.lang Package
Throwable Name Throwable
Synopsis Class Name: java.lang.Throwable Superclass: java.lang.Object Immediate Subclasses: java.lang.Error, java.lang.Exception Interfaces Implemented: java.io.Serializable Availability: JDK 1.0 or later
Description The Throwable class is the superclass of all objects that can be thrown by the throw statement in Java. This is a requirement of the throw statement. A Throwable object can have an associated message that provides more detail about the particular error or exception that is being thrown. The Throwable class provides a method that outputs information about the state of the system when an exception object is created. This method can be useful in debugging Java programs. http://localhost/java/javaref/langref/ch10_25.htm (1 of 5) [20/12/2001 11:22:57]
[Chapter 10] Throwable
The subclasses of Throwable that are provided with Java do not add functionality to Throwable. Instead, they offer more specific classifications of errors and exceptions.
Class Summary public class java.lang.Throwable extends java.lang.Object implements java.lang.Serializable { // Constructors public Throwable(); public Throwable(String message); // Instance Methods public native Throwable fillInStackTrace(); public String getLocalizedMessage(); // New in 1.1 public String getMessage(); public void printStackTrace(); public void printStackTrace(PrintStream s); public void printStackTrace(PrintWriter s); // New in 1.1 public String toString(); }
Constructors Throwable public Throwable() Description Creates a Throwable object with no associated message. This constructor calls fillInStackTrace() so that information is available for printStackTrace(). public Throwable(String message) Parameters message A message string to be associated with the object. Description Create a Throwable object with an associated message. This constructor calls fillInStackTrace() so that information is available for printStackTrace().
http://localhost/java/javaref/langref/ch10_25.htm (2 of 5) [20/12/2001 11:22:57]
[Chapter 10] Throwable
Instance Methods fillInStackTrace public native Throwable fillInStackTrace() Returns A reference to this object. Description This method puts stack trace information in this Throwable object. It is not usually necessary to explicitly call this method, since it is called by the constructors of the class. However, this method can be useful when rethrowing an object. If the stack trace information in the object needs to reflect the location that the object is rethrows from, fillInStackTrace() should be called.
getLocalizedMessage public String getLocalizedMessage() Availability New as of JDK 1.1 Returns A localized version of the String object associated with this Throwable object, or null if there is no message associated with this object. Description This method creates a localized version of the message that was associated with this object by its constructor. The getLocalizedMessage() method in Throwable always returns the same result as getMessage(). A subclass must override this method to produce a locale-specific message.
getMessage public String getMessage() Returns The String object associated with this Throwable object, or null if there is no message associated with this object. Description This method returns any string message that was associated with this object by its constructor.
http://localhost/java/javaref/langref/ch10_25.htm (3 of 5) [20/12/2001 11:22:57]
[Chapter 10] Throwable
printStackTrace public void printStackTrace() Description This method outputs the string representation of this Throwable object and a stack trace to System.err. public void printStackTrace(PrintStream s) Parameters s A java.io.PrintStream object. Description This method outputs the string representation of this Throwable object and a stack trace to the specified PrintStream object. public void printStackTrace(PrintStream w) Availability New as of JDK 1.1 Parameters s A java.io.PrintWriter object. Description This method outputs the string representation of this Throwable object and a stack trace to the specified PrintWriter object.
toString public String toString() Returns A string representation of this object. Overrides Object.toString() Description This method returns a string representation of this Throwable object.
http://localhost/java/javaref/langref/ch10_25.htm (4 of 5) [20/12/2001 11:22:57]
[Chapter 10] Throwable
Inherited Methods Method Inherited From Method Inherited From clone() Object equals(Object) Object finalize() Object getClass() Object hashCode() Object notify() Object notifyAll() Object wait() Object wait(long) Object wait(long, int) Object
See Also Errors; Exceptions; Object
ThreadGroup
http://localhost/java/javaref/langref/ch10_25.htm (5 of 5) [20/12/2001 11:22:57]
Void
[Chapter 10] Object
Chapter 10 The java.lang Package
Object Name Object
Synopsis Class Name: java.lang.Object Superclass: None Immediate Subclasses: Too many to be listed here Interfaces Implemented: None Availability: JDK 1.0 or later
Description The Object class is the ultimate superclass of all other classes in Java. Because every other class is a subclass of Object, all of the methods accessible from Object are inherited by every other class. In other words, all objects in Java, including arrays, have access to implementations of the methods in Object. The methods of Object provide some basic object functionality. The equals() method compares two objects for equality, while the hashCode() method returns a hashcode for an object. The getClass() method returns the Class object associated with an object. The wait(), notify(), and notifyAll() methods support thread synchronization for an object. The toString() method provides a string representation of an object. Some of these methods should be overridden by subclasses of Object. For example, every class should provide its own implementation of the toString() method, so that it can provide an appropriate string representation. Although it is possible to create an instance of the Object class, this is rarely done because it is more useful to create specialized objects. However, it is often useful to declare a variable that contains a reference to an Object because such a variable can contain a reference to an object of any other class.
http://localhost/java/javaref/langref/ch10_14.htm (1 of 8) [20/12/2001 11:23:00]
[Chapter 10] Object
Class Summary public class java.lang.Object { // Constructors public Object(); // Public Instance Methods public boolean equals(Object obj); public final native Class getClass(); public native int hashCode(); public final native void notify(); public final native void notifyAll(); public String toString(); public final native void wait(); public final native void wait(long millis); public final native void wait(long millis, int nanos); // Protected Instance Methods protected native Object clone(); protected void finalize() throws Throwable; }
Constructors Object public Object() Description Creates an instance of the Object class.
Public Instance Methods equals public boolean equals(Object obj) Parameters obj The object to be compared with this object. Returns true if the objects are equal; false if they are not. Description The equals() method of Object returns true if the obj parameter refers to the same object as the object this method is associated with. This is equivalent to using the == operator to compare two objects. Some classes, such as String, override the equals() method to provide a comparison based on the contents of the two objects, rather than on the strict equality of the references. Any subclass can override the equals() method to implement an appropriate comparison, as long as the overriding method satisfies the following rules for an equivalence relation: http://localhost/java/javaref/langref/ch10_14.htm (2 of 8) [20/12/2001 11:23:00]
[Chapter 10] Object ❍ ❍
❍
❍
❍
The method is reflexive : given a reference x, x.equals(x) returns true. The method is symmetric : given references x and y, x.equals(y) returns true if and only if y.equals(x) returns true. The method is transitive : given references x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) returns true. The method is consistent : given references x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided that no information contained by the objects referenced by x or y changes. A comparison with null returns false: given a reference x that is non-null, x.equals(null) returns false.
getClass public final native Class getClass() Returns A reference to the Class object that describes the class of this object. Description The getClass() method of Object returns the Class object that describes the class of this object. This method is final, so it cannot be overridden by subclasses.
hashCode public native int hashCode() Returns A relatively unique value that should be the same for all objects that are considered equal. Description The hashCode() method of Object calculates a hashcode value for this object. The method returns an integer value that should be relatively unique to the object. If the equals() method for the object bases its result on the contents of the object, the hashcode() method should also base its result on the contents. The hashCode() method is provided for the benefit of hashtables, which store and retrieve elements using key values called hashcodes. The internal placement of a particular piece of data is determined by its hashcode; hashtables are designed to use hashcodes to provide efficient retrieval. The java.util.Hashtable class provides an implementation of a hashtable that stores values of type Object. Each object is stored in the hashtable based on the hash code of its key object. It is important that each object have the most unique hash code possible. If two objects have the same hash code but they are not equal (as determined by equals()), a Hashtable that stores these two objects may need to spend additional time searching when it is trying to retrieve objects. The implementation of hashCode() in Object tries to make sure that every object has a distinct hash code by basing its result on the internal representation of a reference to the object. Some classes, such as String, override the hashCode() method to produce values based on the contents of individual objects, instead of the objects themselves. In other words, two String objects that contain the exact same strings have the same hash code. If String did not override the hashCode() method inherited from Object, these two String objects would have different hash code values and it would be impossible to use String objects as keys for hashtables. Any subclass can override the hashCode() method to implement an appropriate way of producing hash code values, as long as the overriding method satisfies the following rules: ❍ If the hashCode() method is called on the same object more than once during the execution of a Java http://localhost/java/javaref/langref/ch10_14.htm (3 of 8) [20/12/2001 11:23:00]
[Chapter 10] Object
❍
❍
application, it must consistently return the same integer value. The integer does not, however, need to be consistent between Java applications, or from one execution of an application to another execution of the same application. If two objects compare as equal according to their equals() methods, calls to the hashCode() methods for the objects must produce the same result. If two objects compare as not equal according to their equals() methods, calls to the hashCode() methods for the two objects are not required to produce distinct results. However, implementations of hashCode() that produce distinct results for unequal objects may improve the performance of hashtables.
In general, if a subclass overrides the equals() method of Object, it should also override the hashCode() method.
notify public final native void notify() Throws IllegalMonitorStateException If the method is called from a thread that does not hold this object's lock. Description The notify() method wakes up a thread that is waiting to return from a call to this object's wait() method. The awakened thread can resume executing as soon as it regains this object's lock. If more than one thread is waiting, the notify() method arbitrarily awakens just one of the threads. The notify() method can be called only by a thread that is the current owner of this object's lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object. A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class. This method is final, so it cannot be overridden by subclasses.
notifyAll public final native void notifyAll() Throws IllegalMonitorStateException If the method is called from a thread that does not hold this object's lock. Description The notifyAll() method wakes up all the threads that are waiting to return from a call to this object's wait() method. Each awakened thread can resume executing as soon as it regains this object's lock. The notifyAll() method can be called only by a thread that is the current owner of this object's lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object. A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class. This method is final, so it cannot be overridden by subclasses.
http://localhost/java/javaref/langref/ch10_14.htm (4 of 8) [20/12/2001 11:23:00]
[Chapter 10] Object
toString public String toString() Returns The string representation of this object. Description The toString() method of Object returns a generic string representation of this object. The method returns a String that consists of the object's class name, an "at" sign, and the unsigned hexadecimal representation of the value returned by the object's hashCode() method. Many classes override the toString() method to provide a string representation that is specific to that type of object. Any subclass can override the toString() method; the overriding method should simply return a String that represents the contents of the object with which it is associated.
wait public final native void wait() throws InterruptedException Throws IllegalMonitorStateException If the method is called from a thread that does not hold this object's lock. InterruptedException If another thread interrupted this thread. Description The wait() method causes a thread to wait until it is notified by another thread to stop waiting. When wait() is called, the thread releases its lock on this object and waits until another thread notifies it to wake up through a call to either notify() or notifyAll(). After the thread is awakened, it has to regain the lock on this object before it can resume executing. The wait() method can be called only by a thread that is the current owner of this object's lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object. A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class. This method is final, so it cannot be overridden by subclasses. public final native void wait(long timeout) throws InterruptedException Parameters timeout The maximum number of milliseconds to wait. Throws IllegalMonitorStateException If the method is called from a thread that does not hold this object's lock. InterruptedException If another thread interrupted this thread. Description
http://localhost/java/javaref/langref/ch10_14.htm (5 of 8) [20/12/2001 11:23:00]
[Chapter 10] Object
The wait() method causes a thread to wait until it is notified by another thread to stop waiting or until the specified amount of time has elapsed, whichever comes first. When wait() is called, the thread releases its lock on this object and waits until another thread notifies it to wake up through a call to either notify() or notifyAll(). If the thread is not notified within the specified timeout period, it is automatically awakened when that amount of time has elapsed. If timeout is zero, the thread waits indefinitely, just as if wait() had been called without a timeout argument. After the thread is awakened, it has to regain the lock on this object before it can resume executing. The wait() method can be called only by a thread that is the current owner of this object's lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object. A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class. This method is final, so it cannot be overridden by subclasses. public final native void wait(long timeout, int nanos) throws InterruptedException Parameters timeout The maximum number of milliseconds to wait. nanos An additional number of nanoseconds to wait. Throws IllegalMonitorStateException If the method is called from a thread that does not hold this object's lock. InterruptedException If another thread interrupted this thread. Description The wait() method causes a thread to wait until it is notified by another thread to stop waiting or until the specified amount of time has elapsed, whichever comes first. When wait() is called, the thread releases its lock on this object and waits until another thread notifies it to wake up through a call to either notify() or notifyAll(). If the thread is not notified within the specified time period, it is automatically awakened when that amount of time has elapsed. If timeout and nanos are zero, the thread waits indefinitely, just as if wait() had been called without any arguments. After the thread is awakened, it has to regain the lock on this object before it can resume executing. The wait() method can be called only by a thread that is the current owner of this object's lock. A thread holds the lock on this object while it is executing a synchronized instance method of the object or executing the body of a synchronized statement that synchronizes on the object. A thread can also hold the lock for a Class object if it is executing a synchronized static method of that class. Note that Sun's reference implementation of Java does not attempt to implement the precision implied by this method. Instead, it rounds to the nearest millisecond (unless timeout is 0, in which case it rounds up to 1 millisecond) and calls wait(long). This method is final, so it cannot be overridden by subclasses.
Protected Instance Methods
http://localhost/java/javaref/langref/ch10_14.htm (6 of 8) [20/12/2001 11:23:00]
[Chapter 10] Object
clone protected native Object clone() throws CloneNotSupportedException Returns A clone of this object. Throws OutOfMemoryError If there is not enough memory to create the new object. CloneNotSupportedException If the object is of a class that does not support clone(). Description A clone of an object is another object of the same type that has all of its instance variables set to the same values as the object being cloned. In other words, a clone is an exact copy of the original object. The clone() method of Object creates a new object that is a clone of this object. No constructor is used in creating the clone. The clone() method only clones an object if the class of that object indicates that its instances can be cloned. A class indicates that its objects can be cloned by implementing the Cloneable interface. Although array objects do not implement the Cloneable interface, the clone() method works for arrays. The clone of an array is an array that has the same number of elements as the original array, and each element in the clone array has the same value as the corresponding element in the original array. Note that if an array element contains an object reference, the clone array contains a reference to the same object, not a copy of the object. A subclass of Object can override the clone() method in Object to provide any additional functionality that is needed. For example, if an object contains references to other objects, the clone() method should recursively call the clone() methods of all the referenced objects. An overriding clone() method can throw a CloneNotSupportedException to indicate that particular objects cannot be cloned.
finalize protected void finalize() throws Throwable Throws Throwable For any reason that suits an overriding implementation of this method. Description The finalize() method is called by the garbage collector when it decides that an object can never be referenced again. The method gives an object a chance to perform any cleanup operations that are necessary before it is destroyed by the garbage collector. The finalize() method of Object does nothing. A subclass overrides the finalize() method to perform any necessary cleanup operations. The overriding method should call super.finalize() as the very last thing it does, so that any finalize() method in the superclass is called. When the garbage collector calls an object's finalize() method, the garbage collector does not immediately destroy the object because the finalize() method might do something that results in a reference to the object. Thus the garbage collector waits to destroy the object until it can again prove it is safe to do so. The next time the garbage collector decides it is safe to destroy the object, it does so without calling finalize() again. In other words, the garbage collector never calls the finalize() method more than once for a particular object.
http://localhost/java/javaref/langref/ch10_14.htm (7 of 8) [20/12/2001 11:23:00]
[Chapter 10] Object
A finalize() method can throw any kind of exception. An exception causes the finalize() method to stop running. The garbage collector then catches and ignores the exception, so it has no further effect on a program.
See Also Equality Comparison Operators; Exceptions; Object Destruction; The finalize method; String; Threads 8; Throwable
Number
http://localhost/java/javaref/langref/ch10_14.htm (8 of 8) [20/12/2001 11:23:00]
Process
[Chapter 10] System
Chapter 10 The java.lang Package
System Name System
Synopsis Class Name: java.lang.System Superclass: java.lang.Object Immediate Subclasses: None Interfaces Implemented: None Availability: JDK 1.0 or later
Description The System class provides access to various information about the operating system environment in which a program is running. For example, the System class defines variables that allow access to the standard I/O streams and methods that allow a program to run the garbage collector and stop the Java virtual machine. All of the variables and methods in the System class are static. In other words, it is not necessary to create an instance of the System class in order to use its variables and methods. In fact, the System class does not define any public constructors, so it cannot be instantiated. The System class supports the concept of system properties that can be queried and set. The following properties are guaranteed always to be defined: Property Name
Description
http://localhost/java/javaref/langref/ch10_22.htm (1 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
The character encoding for the default locale (Java 1.1 only) The package that contains converters between local encodings and Unicode (Java 1.1 file.encoding.pkg only) File separator ('/' on UNIX, ' \' on Windows) file.separator The class path java.class.path java.class.version Java class version number The just-in-time compiler to use, if any (Java 1.1 only) java.compiler Java installation directory java.home Java vendor-specific string java.vendor Java vendor URL java.vendor.url Java version number java.version Line separator(' \n' on UNIX, ' \r\n' on Windows) line.separator Operating system architecture os.arch Operating system name os.name Operating system version os.version Path separator (':' on UNIX, ',' on Windows) path.separator User's current working directory when the properties were initialized user.dir User's home directory user.home The two-letter language code of the default locale (Java 1.1 only) user.language User's account name user.name The two-letter country code of the default locale (Java 1.1 only) user.region The default time zone (Java 1.1 only) user.timezone file.encoding
Additional properties may be defined by the run-time environment. The -D command-line option can be used to define system properties when a program is run. The Runtime class is related to the System class; it provides access to information about the environment in which a program is running.
Class Summary public final class java.lang.System extends java.lang.Object { // Constants public static final PrintStream err; public static final InputStream in; public static final PrintStream out; // Class Methods public static void arraycopy(Object src, int srcOffset, Object dst, int dstOffset, int length); public static long currentTimeMillis(); public static void exit(int status); public static void gc(); public static Properties getProperties(); public static String getProperty(String key);
http://localhost/java/javaref/langref/ch10_22.htm (2 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
public public public public public public public public public public public public public
static static static static static static static static static static static static static
String getProperty(String key, String default); SecurityManager getSecurityManager(); String getenv(String name); // Deprecated in 1.1 native int identityHashCode(Object x); // New in 1.1 void load(String filename); void loadLibrary(String libname); void runFinalization(); void runFinalizersOnExit(boolean value); // New in 1.1 void setErr(PrintStream err); // New in 1.1 void setIn(InputStream in); // New in 1.1 void setOut(PrintStream out); // New in 1.1 void setProperties(Properties props); void setSecurityManager(SecurityManager s);
}
Variables err public static final PrintStream err Description The standard error stream. In an application environment, this variable refers to a java.io.PrintStream object that is associated with the standard error output for the process running the Java virtual machine. In an applet environment, the PrintStream is likely to be associated with a separate window, although this is not guaranteed. The value of err can be set using the setErr() method. The value of err can only be set if the currenly installed SecurityManager does not throw a SecurityException when the request is made. Prior to to Java 1.1, err was not final. It has been made final as of Java 1.1 because the unchecked ability to set err is a security hole.
in public static final InputStream in Description The standard input stream. In an application environment, this variable refers to a java.io.InputStream object that is associated with the standard input for the process running the Java virtual machine. The value of in can be set using the setIn() method. The value of in can only be set if the currenly installed SecurityManager does not throw a SecurityException when the request is made. Prior to to Java 1.1, in was not final. It has been made final as of Java 1.1 because the unchecked ability to set in is a security hole.
http://localhost/java/javaref/langref/ch10_22.htm (3 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
out public static final PrintStream out Description The standard output stream. In an application environment, this variable refers to a java.io.PrintStream object that is associated with the standard output for the process running the Java virtual machine. In an applet environment, the PrintStream is likely to be associated with a separate window, although this is not guaranteed. out is the most commonly used of the three I/O streams provided by the System class. Even in GUI-based applications, sending output to this stream can be useful for debugging. The usual idiom for sending output to this stream is: System.out.println("Some text"); The value of out can be set using the setOut() method. The value of out can only be set if the currenly installed SecurityManager does not throw a SecurityException when the request is made. Prior to to Java 1.1, out was not final. It has been made final as of Java 1.1 because the unchecked ability to set out is a security hole.
Class Methods arraycopy public static void arraycopy(Object src, int src_position, Object dst, int dst_position, int length) Parameters src The source array. src_position An index into the source array. dst The destination array. dst_position An index into the destination array. length The number of elements to be copied. Throws ArrayIndexOutOfBoundsException If the values of the src_position, dst_position, and length arguments imply accessing http://localhost/java/javaref/langref/ch10_22.htm (4 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
either array with an index that is less than zero or an index greater than or equal to the number of elements in the array. ArrayStoreException If the type of value stored in the src array cannot be stored in the dst array. NullPointerException If src or dst is null. Description This method copies a range of array elements from the src array to the dst array. The number of elements that are copied is specified by length. The elements at positions src_position through src_position+length-1 in src are copied to the positions dst_position through dst_position+length-1 in dst, respectively. If src and dst refer to the same array, the copying is done as if the array elements were first copied to a temporary array and then copied to the destination array. Before this method does any copying, it performs a number of checks. If either src or dst are null, the method throws a NullPointerException and dst is not modified. If any of the following conditions are true, the method throws an ArrayStoreException, and dst is not modified: ❍ Either src or dst refers to an object that is not an array. ❍ src and dst refer to arrays whose element types are different primitive types. ❍ src refers to an array that has elements that contain a primitive type, while dst refers to an array that has elements that contain a reference type, or vice versa. If any of the following conditions are true, the method throws an ArrayIndexOutOfBoundsException, and dst is not modified: ❍ srcOffset, dstOffset, or length is negative. ❍ srcOffset+length is greater than src.length(). ❍ dstOffset+length is greater than dst.length(). Otherwise, if an element in the source array being copied cannot be converted to the type of the destination array using the rules of the assignment operator, the method throws an ArrayStoreException when the problem occurs. Since the problem is discovered during the copy operation, the state of the dst array reflects the incomplete copy operation.
currentTimeMillis public static native long currentTimeMillis() Returns The current time as the number of milliseconds since 00:00:00 UTC, January 1, 1970. Description This method returns the current time as the number of milliseconds since 00:00:00 UTC, January 1, 1970. It will not overflow until the year 292280995.
http://localhost/java/javaref/langref/ch10_22.htm (5 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
The java.util.Date class provides more extensive facilities for dealing with times and dates.
exit public static void exit(int status) Parameters status The exit status code to use. Throws SecurityException If the checkExit() method of the SecurityManager throws a SecurityException. Description This method causes the Java virtual machine to exit with the given status code. This method works by calling the exit() method of the current Runtime object. By convention, a nonzero status code indicates abnormal termination. This method never returns.
gc public static void gc() Description This method causes the Java virtual machine to run the garbage collector in the current thread. This method works by calling the gc() method of the current Runtime object. The garbage collector finds objects that will never be used again because there are no live references to them. After it finds these objects, the garbage collector frees the storage occupied by these objects. The garbage collector is normally run continuously in a thread with the lowest possible priority, so that it works intermittently to reclaim storage. The gc() method allows a program to invoke the garbage collector explicitly when necessary.
getProperties public static Properties getProperties() Returns A Properties object that contains the values of all the system properies. Throws SecurityException If the checkPropertiesAccess() method of the SecurityManager throws a SecurityException. Description This method returns all of the defined system properties encapsulated in a java.util.Properties
http://localhost/java/javaref/langref/ch10_22.htm (6 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
object. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed in the description of the System class, some system properties are guaranteed always to be defined.
getProperty public static String getProperty(String key) Parameters key The name of a system property. Returns The value of the named system property or null if the named property is not defined. Throws SecurityException If the checkPropertyAccess() method of the SecurityManager throws a SecurityException. Description This method returns the value of the named system property. If there is no definition for the named property, the method returns null. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed in the description of the System class, some system properties are guaranteed always to be defined. public static String getProperty(String key, String def) Parameters key The name of a system property. def A default value for the property. Returns The value of the named system property, or the default value if the named property is not defined. Throws SecurityException If the checkPropertyAccess() method of the SecurityManager throws a SecurityException. Description This method returns the value of the named system property. If there is no definition for the named property, the method returns the default value as specified by the def parameter. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed earlier in the description of the System class, some system properties are guaranteed to always be
http://localhost/java/javaref/langref/ch10_22.htm (7 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
defined.
getSecurityManager public static SecurityManager getSecurityManager() Returns A reference to the installed SecurityManager object or null if there is no SecurityManager object installed. Description This method returns a reference to the installed SecurityManager object. If there is no SecurityManager object installed, the method returns null.
getenv public static String getenv(String name) Availability Deprecated as of JDK 1.1 Parameters name The name of a system-dependent environment variable. Returns The value of the environment variable or null if the variable is not defined. Description This method is obsolete; it always throws an error. Use getProperties() and the -D option instead.
identityHashCode public static native int identityHashCode(Object x) Availability New as of JDK 1.1 Parameters x An object. Returns The identity hashcode value for the specified object. Description This method returns the same hashcode value for the specified object as would be returned by the default hashCode() method of Object, regardless of whether or not the object's class overrides http://localhost/java/javaref/langref/ch10_22.htm (8 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
hashCode().
load public void load(String filename) Parameters filename A string that specifies the complete path of the file to be loaded. Throws SecurityException If the checkLink() method of the SecurityManager throws a SecurityException. UnsatisfiedLinkError If the method is unsuccessful in loading the specified dynamically linked library. Description This method loads the specified dynamically linked library. This method works by calling the load() method of the current Runtime object.
loadLibrary public void loadLibrary(String libname) Parameters libname A string that specifies the name of a dynamically linked library. Throws SecurityException If the checkLink() method of the SecurityManager throws a SecurityException. UnsatisfiedLinkError If the method is unsuccessful in loading the specified dynamically linked library. Description This method loads the specified dynamically linked library. It looks for the specified library in a platform-specific way. This method works by calling the loadLibrary() method of the current Runtime object.
runFinalization public static void runFinalization() Description This method causes the Java virtual machine to run the finalize() methods of any objects in the
http://localhost/java/javaref/langref/ch10_22.htm (9 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
finalization queue in the current thread. This method works by calling the runFinalization() method of the current Runtime object. When the garbage collector discovers that there are no references to an object, it checks to see if the object has a finalize() method that has never been called. If the object has such a finalize() method, the object is placed in the finalization queue. While there is a reference to the object in the finalization queue, the object is no longer considered garbage collectable. Normally, the objects in the finalization queue are handled by a separate finalization thread that runs continuously at a very low priority. The finalization thread removes an object from the queue and calls its finalize() method. As long as the finalize() method does not generate a reference to the object, the object again becomes available for garbage collection. Because the finalization thread runs at a very low priority, there may be a long delay from the time that an object is put on the finalization queue until the time that its finalize() method is called. The runFinalization() method allows a program to run the finalize() methods explicitly. This can be useful when there is a shortage of some resource that is released by a finalize() method.
runFinalizersOnExit public static void runFinalizersOnExit(boolean value) Availability New as of JDK 1.1 Parameters value A boolean value that specifies whether or not finalization occurs on exit. Throws SecurityException If the checkExit() method of the SecurityManager throws a SecurityException. Description This method specifies whether or not the finalize() methods of all objects that have finalize() methods are run before the Java virtual machine exits. By default, the finalizers are not run on exit. This method works by calling the runFinalizersOnExit() method of the current Runtime object.
setErr public static void setErr(PrintStream err) Availability New as of JDK 1.1 Parameters err A PrintStream object to use for the standard error stream. Throws http://localhost/java/javaref/langref/ch10_22.htm (10 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
SecurityException If the checkExec() method of the SecurityManager throws a SecurityException. Description This method sets the standard error stream to be this PrintStream object.
setIn public static void setIn(InputStream in) Availability New as of JDK 1.1 Parameters in A InputStream object to use for the standard input stream. Throws SecurityException If the checkExec() method of the SecurityManager throws a SecurityException. Description This method sets the standard input stream to be this InputStream object.
setOut public static void setOut(PrintStream out) Availability New as of JDK 1.1 Parameters out A PrintStream object to use for the standard output stream. Throws SecurityException If the checkExec() method of the SecurityManager throws a SecurityException. Description This method sets the standard output stream to be this PrintStream object.
setProperties public static void setProperties(Properties props) Parameters
http://localhost/java/javaref/langref/ch10_22.htm (11 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
props A reference to a Properties object. Throws SecurityException If the checkPropertiesAccess() method of the SecurityManager throws a SecurityException. Description This method replaces the current set of system property definitions with a new set of system property definitions that are encapsulated by the given Properties object. As discussed in the description of the System class, some system properties are guaranteed to always be defined.
setSecurityManager public static void setSecurityManager(SecurityManager s) Parameters s A reference to a SecurityManager object. Throws SecurityException If a SecurityManager object has already been installed. Description This method installs the given SecurityManager object. If s is null, then no SecurityManager object is installed. Once a SecurityManager object is installed, any subsequent calls to this method throw a SecurityException.
Inherited Methods Method Inherited From Method Inherited From clone() Object equals(Object) Object finalize() Object getClass() Object hashCode() Object notify() Object notifyAll() Object toString() Object wait() Object wait(long) Object wait(long, int) Object
See Also Assignment Compatibility; Errors; Exceptions; Object; Object Destruction; Process; Runtime; SecurityManager
http://localhost/java/javaref/langref/ch10_22.htm (12 of 13) [20/12/2001 11:23:09]
[Chapter 10] System
StringBuffer
http://localhost/java/javaref/langref/ch10_22.htm (13 of 13) [20/12/2001 11:23:09]
Thread
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
A abs( ) : Math abstract classes Abstract classes Class Modifiers abstract modifier interfaces and : Interface Modifiers methods and Method modifiers Interface method modifiers AbstractMethodError error : Errors access (see also security, SecurityManager class) acos( ) : Math activeCount( ) Thread class : Thread ThreadGroup class : ThreadGroup activeGroupCount( ) : ThreadGroup addition (+) operator, arithmetic : Arithmetic Addition Operator + additive operators : Additive Operators align attribute ( tag) : Embedding an Applet in a Web Page alive threads : Controlling a Thread allocation Reference Types Allocation Expressions Object-Orientation Java Style allowThreadSuspension( ) : ThreadGroup alt attribute ( tag) : Embedding an Applet in a Web Page
http://localhost/java/javaref/langref/index/idx_a.htm (1 of 3) [20/12/2001 11:23:14]
Index
AND (&) operator, bitwise : Bitwise/Logical AND Operator & AND (&&) operator, boolean : Boolean AND Operator && append( ) StringBuffer class : StringBuffer Applet class : Applets tag (HTML) : Embedding an Applet in a Web Page applets Applets Threads application : Running a Java Application applications : Applications archive attribute ( tag) : Embedding an Applet in a Web Page arithmetic addition (+) operator : Arithmetic Addition Operator + arithmetic data types : Arithmetic Types arithmetic subtraction (-) operator : Arithmetic Subtraction Operator ArithmeticException exception : Runtime exceptions ArrayIndexOutOfBoundsException exception Array Types Runtime exceptions arrays : Array Types allocation expressions for : Array Allocation Expressions arraycopy( ) : System assigning elements (see assignment operators) creating : Allocation Expressions index expressions : Index Expressions length of : Array Types local : Local variable type multi-dimensional Array Types Array Allocation Expressions Variable type Local variable type ArrayStoreException exception : Runtime exceptions asin( ) : Math http://localhost/java/javaref/langref/index/idx_a.htm (2 of 3) [20/12/2001 11:23:14]
Index
assignment compatibility Integer types Floating-point types Assignment Compatibility operators Operators Assignment Operators associativity, operator : Order of Operations atan( ) : Math atan2( ) : Math @author tag (javadoc) : Documentation Comments
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_a.htm (3 of 3) [20/12/2001 11:23:14]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
B balking strategy (threads) : Balking binary addition (+) operator : Arithmetic Addition Operator + division (/) operator : Division Operator / multiplication (*) operator : Multiplication Operator * remainder (%) operator : Remainder Operator % subtraction (-) operator : Arithmetic Subtraction Operator bit shifting : Shift Operators bitwise operators : Bitwise/Logical Operators AND (&) : Bitwise/Logical AND Operator & negation (~) : Bitwise Negation Operator ~ OR (^) operator : Bitwise/Logical Exclusive OR Operator ^ OR (|) operator : Bitwise/Logical Inclusive OR Operator | blocks, statement Lexical Scope of Declarations Blocks BNF notation : Notational Conventions Boolean( ) : Boolean Boolean class Boolean Type Boolean boolean data type Boolean literals Boolean Type boolean operators : Boolean Operators AND (&&) operator : Boolean AND Operator &&
http://localhost/java/javaref/langref/index/idx_b.htm (1 of 2) [20/12/2001 11:23:15]
Index
negation (!) : Boolean Negation Operator ! OR (||) operator : Boolean OR Operator || booleanValue( ) : Boolean break statement : The break Statement Byte( ) : Byte Byte class : Byte byte data type : Integer types byteValue( ) : Byte Double class : Double Float class : Float Integer class : Integer Long class : Long Number class : Number Short class : Short
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_b.htm (2 of 2) [20/12/2001 11:23:15]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
C C-style comments (see comments) C++ programming language : Introduction capacity( ) : StringBuffer carriage return Division of the Input Stream into Lines Character literals case labels : The switch Statement case sensitivity class names : Applications filenames : Compiling a Java Source File naming conventions and : Naming Conventions package names : Packages cast operations : Casts catch clause (see try statement) Handling Exceptions Handling Exceptions catching exceptions (see exceptions) ceil( ) : Math char data type : Integer types Character( ) : Character Character class : Character characters character literals : Character literals integer data types for : Arithmetic Types string literals : String literals Unicode
http://localhost/java/javaref/langref/index/idx_c.htm (1 of 6) [20/12/2001 11:23:19]
Index
Pre-Processing Packages Unicode 2.0 character set : The Unicode 2.0 Character Set charAt( ) String class : String StringBuffer class : StringBuffer charValue( ) Character class : Character checkAccept( ) : SecurityManager checkAccess( ) SecurityManager class : SecurityManager Thread class : Thread ThreadGroup class : ThreadGroup checkAwtEventQueueAccess( ) : SecurityManager checkConnect( ) : SecurityManager checkCreateClassLoader( ) : SecurityManager checkDelete( ) : SecurityManager checkExec( ) : SecurityManager checkExit( ) : SecurityManager checkLink( ) : SecurityManager checkListen( ) : SecurityManager checkMemberAccess( ) : SecurityManager checkMulticast( ) : SecurityManager checkPackageAccess( ) : SecurityManager checkPackageDefinition( ) : SecurityManager checkPrintJobAccess( ) : SecurityManager checkPropertiesAccess( ) : SecurityManager checkRead( ) : SecurityManager checkSecurityAccess( ) SecurityManager SecurityManager checkSetFactory( ) : SecurityManager checkSystemClipboardAccess( ) : SecurityManager checkTopLevelWindow( ) : SecurityManager http://localhost/java/javaref/langref/index/idx_c.htm (2 of 6) [20/12/2001 11:23:19]
Index
checkWrite( ) : SecurityManager Class : Class class data types : Class Types casting : Casts .class files : Packages ClassCastException exception Casts Runtime exceptions ClassCircularityError error : Errors classDepth( ) : SecurityManager classes A "Hello World" Program Classes abstract : Abstract classes Class class : Class constructors : Constructors declaring : Lexical Scope of Declarations documentation for : Documentation Comments exception : The try Statement final : Final classes import directive : The import Directive inheritance (see inheritance) loading (static initializers) : Static Initializers methods : Methods specially supported : Specially supported classes variables of : Variables ClassFormatError error : Errors ClassLoader class : ClassLoader classLoaderDepth( ) : SecurityManager ClassNotFoundException exception : Other exceptions CLASSPATH variable Compiling a Java Source File Packages clone( ) http://localhost/java/javaref/langref/index/idx_c.htm (3 of 6) [20/12/2001 11:23:19]
Index
Object class : Object Cloneable interface : Cloneable CloneNotSupportedException exception : Other exceptions code attribute ( tag) : Embedding an Applet in a Web Page codebase attribute ( tag) : Embedding an Applet in a Web Page comma (,) Operators The for Statement command( ) : Compiler comments A "Hello World" Program Comments Documentation Comments compareTo( ) : String comparing (see also equals( )) comparison operators : Relational Comparison Operators compatibility, assignment Integer types Floating-point types Assignment Compatibility compilation units : Compilation Units compileClass( ) : Compiler compileClasses( ) : Compiler Compiler class : Compiler compiling Java source files : Compiling a Java Source File compound assignment operators : Assignment Operators concat( ) : String concatenation (+) operator null String Concatenation Operator + conditional (?:) operator : Conditional Operator conditional AND (&&) operator : Boolean AND Operator && conditional operators (see boolean operators) conditional OR (||) operator : Boolean OR Operator || http://localhost/java/javaref/langref/index/idx_c.htm (4 of 6) [20/12/2001 11:23:19]
Index
conditional statements : The if Statement constants constant expressions : Constant Expressions integer : Integer types special floating-point : Floating-point types constructors Object Creation Constructors chaining : Constructor implementation default : The default constructor inheritance : Constructor inheritance selecting to invoke : Object Allocation Expressions super keyword and : super for threads : Associating a Method with a Thread continue statement The for Statement The continue Statement converting data types Integer types Casts programs to Unicode : Conversion to Unicode copyValueOf( ) : String cos( ) : Math countStackFrames( ) : Thread critical section : Single-Threaded Execution currentClassLoader( ) : SecurityManager currentLoadedClass( ) : SecurityManager currentThread( ) : Using Thread Objects Thread class : Thread currentTimeMillis( ) : System
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
http://localhost/java/javaref/langref/index/idx_c.htm (5 of 6) [20/12/2001 11:23:19]
Index
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_c.htm (6 of 6) [20/12/2001 11:23:19]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
D daemon threads : Daemon threads data types Data Types Variable type assignment compatibility : Assignment Compatibility cast operations : Casts comparing with instanceof operator : The instanceof Operator of expressions : Data Type of an Expression local variables : Local variable type decimal literals Integer literals Integer literals declaring classes : Class Declarations exceptions : Declaring Exceptions interfaces : Interface Declarations lexical scope : Lexical Scope of Declarations methods Methods Interface Methods variables : Variables decode( ) Byte( ) : Byte Integer class : Integer Short class : Short decrement (- -) operator
http://localhost/java/javaref/langref/index/idx_d.htm (1 of 3) [20/12/2001 11:23:22]
Index
Field Expressions Increment/Decrement Operators default constructor : The default constructor defineClass( ) : ClassLoader @deprecated tag (javadoc) : Documentation Comments destroy( ) : Applets Process class : Process Thread class : Thread ThreadGroup class : ThreadGroup destruction, object (see garbage collection) Digit characters : Conversion to Unicode digit( ) : Character disable( ) : Compiler dividing by zero : Division Operator / division (/) operator, binary : Division Operator / do statement The do Statement documentation : Related Books documentation comments Comments Documentation Comments domain names : Packages Double( ) : Double Double class Floating-point types Double double data type Floating-point literals Floating-point types double-precision numbers (see floating-point data types) doubleToLongBits( ) : Double doubleValue( ) : Byte Double class : Double Float class : Float http://localhost/java/javaref/langref/index/idx_d.htm (2 of 3) [20/12/2001 11:23:22]
Index
Integer class : Integer Long class : Long Number class : Number Short class : Short dumpStack( ) : Thread dynamic allocation Reference Types Object-Orientation Java Style dynamic method lookup : Method Call Expression
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_d.htm (3 of 3) [20/12/2001 11:23:22]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
E elements, array (see arrays) else clause (see if statement) embedding applets in Web pages : Embedding an Applet in a Web Page empty statements : The Empty Statement empty string : String enable( ) : Compiler encapsulation : Encapsulation encoding (see Unicode characters) end-of-line characters : Division of the Input Stream into Lines endsWith( ) : String ensureCapacity( ) : StringBuffer enumerate( ) Thread class : Thread ThreadGroup class : ThreadGroup equal-to (= =) operator : Equal-To Operator == equality operators : Equality Comparison Operators equals( ) : The instanceof Operator Boolean class : Boolean Byte class : Byte Character class : Character Double class : Double equalsIgnoreCase( ) : String Integer class : Integer Long class : Long Object class : Object Short class : Short
http://localhost/java/javaref/langref/index/idx_e.htm (1 of 3) [20/12/2001 11:23:25]
Index
String class : String err variable : System Error class Declaring Exceptions The Exception Hierarchy Errors errors : Errors EscapedSourceCharacter sequence Conversion to Unicode Character literals Exception class : The Exception Hierarchy @exception tag (javadoc) : Documentation Comments ExceptionInInitializerError error : Errors exceptions (see also under specific exception name) The try Statement Exception Handling rethrowing : Rethrowing Exceptions runtime : Runtime exceptions stack traces : Printing Stack Traces throw statement : The throw Statement throws clause Method throws clause Constructor throws clause Interface method throws clause try statement and : The try Statement exclusive OR (^) operator : Bitwise/Logical Exclusive OR Operator ^ exec( ) Runtime class : Runtime exit( ) Runtime class : Runtime System class : System exitValue( ) Process class : Process exp( ) : Math http://localhost/java/javaref/langref/index/idx_e.htm (2 of 3) [20/12/2001 11:23:25]
Index
explicit synchronization : Explicit Synchronization expressions : Expression Statements allocation : Allocation Expressions constant : Constant Expressions data types of : Data Type of an Expression field : Field Expressions index : Index Expressions literal : Literal Expressions method calls : Method Call Expression order of operations in : Order of Operations parenthetical : Parenthetical Expressions extends clause Inheritance Class Inheritance Interface Inheritance
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_e.htm (3 of 3) [20/12/2001 11:23:25]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
F FALSE constant : Boolean Type FALSE value : Boolean field declarations : Class Members field expressions : Field Expressions FIFO (first-in, first-out) queue : Optimistic Single-Threaded Execution files : Compiling a Java Source File source files Compilation Units Packages fillInStackTrace( ) Rethrowing Exceptions Throwable final modifier classes and Final classes Class Modifiers methods and : Method modifiers variables and : Variable modifiers finalize( ) Object Destruction The finalize method Object class : Object runFinalization( ) and Runtime System runFinalizersOnExit( ) and
http://localhost/java/javaref/langref/index/idx_f.htm (1 of 3) [20/12/2001 11:23:28]
Index
Runtime System finally clause (see try statement) Handling Exceptions Handling Exceptions findLoadedClass( ) : ClassLoader findSystemClass( ) : ClassLoader Float( ) : Float Float class Floating-point types Float float data type Floating-point literals Floating-point types floating-point data types Floating-point literals Floating-point types floating-point numbers : Floating-point literals unary minus (-) and : Unary Minus Operator floatToIntBits( ) : Float floatValue( ) : Byte Double class : Double Float class : Float Integer class : Integer Long class : Long Number class : Number Short class : Short floor( ) : Math for statement Lexical Scope of Declarations The for Statement forDigit( ) : Character formal parameters Field Expressions http://localhost/java/javaref/langref/index/idx_f.htm (2 of 3) [20/12/2001 11:23:28]
Index
Method Call Expression Object Allocation Expressions Method formal parameters Constructor formal parameters forName( ) : Class freeMemory( ) : Runtime friendly access Variable modifiers Method modifiers Constructor modifiers
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_f.htm (3 of 3) [20/12/2001 11:23:28]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
G garbage collection Object Destruction The finalize method Daemon threads Runtime System gc( ) Runtime class Runtime System getBoolean( ) : Boolean getBytes( ) String class : String getChars( ) String class : String StringBuffer class : StringBuffer getClass( ) Object class : Object getClassContext( ) : SecurityManager getClasses( ) : Class getClassLoader( ) : Class getComponentType( ) : Class getConstructor( ) : Class getConstructors( ) : Class getDeclaredClasses( ) : Class getDeclaredConstructor( ) : Class
http://localhost/java/javaref/langref/index/idx_g.htm (1 of 4) [20/12/2001 11:23:32]
Index
getDeclaredConstructors( ) : Class getDeclaredField( ) : Class getDeclaredFields( ) : Class getDeclaredMethod( ) : Class getDeclaredMethods( ) : Class getDeclaringClass( ) : Class getenv( ) : System getErrorStream( ) Process class : Process getField( ) : Class getFields( ) : Class getInCheck( ) : SecurityManager getInputStream( ) Process class : Process getInteger( ) Integer class : Integer getInterfaces( ) : Class getLocalizedInputStream( ) : Runtime getLocalizedMessage( ) : Throwable getLocalizedOutputStream( ) : Runtime getLong( ) Long Long getMaxPriority( ) : ThreadGroup getMessage( ) : Throwable getMethod( ) : Class getMethods( ) : Class getModifiers( ) : Class getName( ) Class class : Class Thread class : Thread ThreadGroup class : ThreadGroup getNumericValue( ) : Character getOutputStream( ) http://localhost/java/javaref/langref/index/idx_g.htm (2 of 4) [20/12/2001 11:23:32]
Index
Process class : Process getParent( ) : ThreadGroup getPriority( ) : Thread Thread class : Thread priority getProperties( ) System class : System getProperty( ) System class : System getResource( ) Class ClassLoader getResourceAsStream( ) Class ClassLoader getRuntime( ) : Runtime getSecurityContext( ) : SecurityManager getSecurityManager( ) : System getSigners( ) : Class getSuperclass( ) : Class getSystemResource( ) : ClassLoader getSystemResourceAsStream( ) : ClassLoader getThreadGroup( ) SecurityManager Thread getType( ) : Character graphical user interface : Applications greater-than (>) operator : Greater-Than Operator > greater-than-or-equal-to (>=) operator : Greater-Than-Or-Equal-To Operator >= groups, thread Thread priority Controlling groups of threads GUI (graphical user interface) : Applications
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z http://localhost/java/javaref/langref/index/idx_g.htm (3 of 4) [20/12/2001 11:23:32]
Index
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_g.htm (4 of 4) [20/12/2001 11:23:32]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
H handling exceptions (see exceptions) hashCode( ) Boolean class : Boolean Byte class : Byte Character class : Character Double class : Double Float class : Float Integer class : Integer Long class : Long Object class : Object Short class : Short String class : String height attribute ( tag) : Embedding an Applet in a Web Page hexadecimal literals Integer literals Integer literals HexDigit characters : Conversion to Unicode host application : Applets hspace attribute ( tag) : Embedding an Applet in a Web Page HTML (Hypertext Markup Language) Documentation Comments Embedding an Applet in a Web Page
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved. http://localhost/java/javaref/langref/index/idx_h.htm [20/12/2001 11:23:35]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
I identifiers : Identifiers identityHashCode( ) : System IEEEremainder( ) : Math if statement : The if Statement IllegalAccessError error : Errors IllegalAccessException exception : Other exceptions IllegalArgumentException exception : Runtime exceptions IllegalMonitorStateException exception : Runtime exceptions IllegalStateException exception : Runtime exceptions IllegalThreadStateException exception : Runtime exceptions implements clause : Interfaces import directive Packages The import Directive in variable : System inClass( ) : SecurityManager inClassLoader( ) : SecurityManager inclusive OR (|) operator : Bitwise/Logical Inclusive OR Operator | IncompatibleClassChangeError error : Errors increment (++) operator Field Expressions Increment/Decrement Operators index expressions : Index Expressions index, array (see arrays) indexOf( ) String class : String
http://localhost/java/javaref/langref/index/idx_i.htm (1 of 5) [20/12/2001 11:23:37]
Index
IndexOutOfBoundsException exception : Runtime exceptions infinity values : Floating-point types inheritance Introduction Inheritance Class Inheritance Constructor inheritance Interface Inheritance private methods and : Method name init( ) : Applets initializers Variable initializers Interface variable initializers local variable : Local variable initializers static : Static Initializers insert( ) StringBuffer class : StringBuffer instanceof operator : The instanceof Operator InstantiationError error : Errors InstantiationException exception : Other exceptions int data type : Integer types intBitsToFloat( : Float Integer( ) : Integer Integer class : Integer integer data types : Integer types integer literals : Integer literals interface data types : Interface Types casting Casts Casts Casts interfaces Encapsulation Interfaces http://localhost/java/javaref/langref/index/idx_i.htm (2 of 5) [20/12/2001 11:23:37]
Index
Interface Declarations declaring : Lexical Scope of Declarations import directive : The import Directive modifiers for : Interface Modifiers variables in : Interface Variables intern( ) : String InternalError error : Errors interrupt( ) Interrupting a thread Thread interrupted( ) : Thread InterruptedException exception Interrupting a thread Other exceptions interrupting threads : Interrupting a thread intValue( ) : Byte Double class : Double Integer class : Integer Long class : Long Number class : Number Short class : Short isAlive( ) : Thread Thread class : Controlling a Thread isArray( ) : Class isAssignableFrom( ) : Class isDaemon( ) : Daemon threads Thread class : Thread ThreadGroup class : ThreadGroup isDestroyed( ) : ThreadGroup isDigit( ) : Character isIdentifierIgnorable( ) : Character isInfinite( ) Double class Double http://localhost/java/javaref/langref/index/idx_i.htm (3 of 5) [20/12/2001 11:23:37]
Index
Double Float class Float Float isInstance( ) : Class isInterface( ) : Class isInterrupted( ) Thread class Interrupting a thread Thread isISOControl( ) : Character isJavaIdentifierPart( ) : Character isJavaIdentifierStart( ) : Character isJavaLetter( ) : Character isJavaLetterOrDigit( ) : Character isLetter( ) : Character isLetterOrDigit( ) : Character isLowerCase( ) : Character isNaN( ) Double class Double Double Float class Float Float isPrimitive( ) : Class isSpace( ) : Character isSpaceChar( ) : Character isTitleCase( ) : Character isUnicodeIdentifierPart( ) : Character isUnicodeIdentifierStart( ) : Character isUpperCase( ) : Character isWhitespace( ) : Character iteration statements : Iteration Statements http://localhost/java/javaref/langref/index/idx_i.htm (4 of 5) [20/12/2001 11:23:37]
Index
continue statement and : The continue Statement
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_i.htm (5 of 5) [20/12/2001 11:23:37]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
J Java Development Kit (JDK) : Compiling a Java Source File .java files : Lexical Scope of Declarations java interpreter : Running a Java Application java.lang package : The java.lang Package javac compiler : Compiling a Java Source File javadoc program : Documentation Comments join( ) : Thread Thread class : Rendezvous
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_j.htm [20/12/2001 11:23:40]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
K keywords : Keywords
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
Copyright © 1996 O'Reilly & Associates, Inc. All Rights Reserved.
http://localhost/java/javaref/langref/index/idx_k.htm [20/12/2001 11:23:41]
Index
Symbols | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | R | S | T | U | V | W | Y | Z
L labeled statements : Labeled Statements lastIndexOf( ) : String left shift (